pax_global_header00006660000000000000000000000064151271563570014526gustar00rootroot0000000000000052 comment=8e511b70f3ceb6e9d305d0774abe8db6490fe254 hvisage-metalog-8e511b7/000077500000000000000000000000001512715635700151405ustar00rootroot00000000000000hvisage-metalog-8e511b7/.gitignore000066400000000000000000000005271512715635700171340ustar00rootroot00000000000000*~ *.a *.la *.o *.tar.* .deps .libs .cache *.diff *.orig *.patch *.rej aclocal.m4 autom4te.cache config.guess config.h config.h.in config.log config.status config.sub configure compile depcomp install-sh Makefile Makefile.in missing stamp-h1 compile_commands.json /metalog.lsm /metalog.spec /man/metalog.8 /man/metalog.conf.5 /src/metalog hvisage-metalog-8e511b7/AUTHORS000066400000000000000000000007211512715635700162100ustar00rootroot00000000000000* Laurent Wandrebeck patches, etc * Leo Lipelis Tiny patch to allow /var/run/metalog.pid * Hendrik Visage Implemented neg_regex, program_regex and neg_program_regex. * Frank DENIS "Jedi/Sector One" The remaining crap. * Mike Frysinger Keeping the bitrot away. * Jovan Lanik Port to PCRE2, implemented perms and --group hvisage-metalog-8e511b7/COPYING000066400000000000000000000431331512715635700161770ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. hvisage-metalog-8e511b7/ChangeLog000066400000000000000000000000161512715635700167070ustar00rootroot00000000000000See NEWS file hvisage-metalog-8e511b7/INSTALL000066400000000000000000000366261512715635700162060ustar00rootroot00000000000000Installation Instructions ************************* Copyright (C) 1994-1996, 1999-2002, 2004-2017, 2020-2021 Free Software Foundation, Inc. Copying and distribution of this file, with or without modification, are permitted in any medium without royalty provided the copyright notice and this notice are preserved. This file is offered as-is, without warranty of any kind. Basic Installation ================== Briefly, the shell command './configure && make && make install' should configure, build, and install this package. The following more-detailed instructions are generic; see the 'README' file for instructions specific to this package. Some packages provide this 'INSTALL' file but do not implement all of the features documented below. The lack of an optional feature in a given package is not necessarily a bug. More recommendations for GNU packages can be found in *note Makefile Conventions: (standards)Makefile Conventions. The 'configure' shell script attempts to guess correct values for various system-dependent variables used during compilation. It uses those values to create a 'Makefile' in each directory of the package. It may also create one or more '.h' files containing system-dependent definitions. Finally, it creates a shell script 'config.status' that you can run in the future to recreate the current configuration, and a file 'config.log' containing compiler output (useful mainly for debugging 'configure'). It can also use an optional file (typically called 'config.cache' and enabled with '--cache-file=config.cache' or simply '-C') that saves the results of its tests to speed up reconfiguring. Caching is disabled by default to prevent problems with accidental use of stale cache files. If you need to do unusual things to compile the package, please try to figure out how 'configure' could check whether to do them, and mail diffs or instructions to the address given in the 'README' so they can be considered for the next release. If you are using the cache, and at some point 'config.cache' contains results you don't want to keep, you may remove or edit it. The file 'configure.ac' (or 'configure.in') is used to create 'configure' by a program called 'autoconf'. You need 'configure.ac' if you want to change it or regenerate 'configure' using a newer version of 'autoconf'. The simplest way to compile this package is: 1. 'cd' to the directory containing the package's source code and type './configure' to configure the package for your system. Running 'configure' might take a while. While running, it prints some messages telling which features it is checking for. 2. Type 'make' to compile the package. 3. Optionally, type 'make check' to run any self-tests that come with the package, generally using the just-built uninstalled binaries. 4. Type 'make install' to install the programs and any data files and documentation. When installing into a prefix owned by root, it is recommended that the package be configured and built as a regular user, and only the 'make install' phase executed with root privileges. 5. Optionally, type 'make installcheck' to repeat any self-tests, but this time using the binaries in their final installed location. This target does not install anything. Running this target as a regular user, particularly if the prior 'make install' required root privileges, verifies that the installation completed correctly. 6. You can remove the program binaries and object files from the source code directory by typing 'make clean'. To also remove the files that 'configure' created (so you can compile the package for a different kind of computer), type 'make distclean'. There is also a 'make maintainer-clean' target, but that is intended mainly for the package's developers. If you use it, you may have to get all sorts of other programs in order to regenerate files that came with the distribution. 7. Often, you can also type 'make uninstall' to remove the installed files again. In practice, not all packages have tested that uninstallation works correctly, even though it is required by the GNU Coding Standards. 8. Some packages, particularly those that use Automake, provide 'make distcheck', which can by used by developers to test that all other targets like 'make install' and 'make uninstall' work correctly. This target is generally not run by end users. Compilers and Options ===================== Some systems require unusual options for compilation or linking that the 'configure' script does not know about. Run './configure --help' for details on some of the pertinent environment variables. You can give 'configure' initial values for configuration parameters by setting variables in the command line or in the environment. Here is an example: ./configure CC=c99 CFLAGS=-g LIBS=-lposix *Note Defining Variables::, for more details. Compiling For Multiple Architectures ==================================== You can compile the package for more than one kind of computer at the same time, by placing the object files for each architecture in their own directory. To do this, you can use GNU 'make'. 'cd' to the directory where you want the object files and executables to go and run the 'configure' script. 'configure' automatically checks for the source code in the directory that 'configure' is in and in '..'. This is known as a "VPATH" build. With a non-GNU 'make', it is safer to compile the package for one architecture at a time in the source code directory. After you have installed the package for one architecture, use 'make distclean' before reconfiguring for another architecture. On MacOS X 10.5 and later systems, you can create libraries and executables that work on multiple system types--known as "fat" or "universal" binaries--by specifying multiple '-arch' options to the compiler but only a single '-arch' option to the preprocessor. Like this: ./configure CC="gcc -arch i386 -arch x86_64 -arch ppc -arch ppc64" \ CXX="g++ -arch i386 -arch x86_64 -arch ppc -arch ppc64" \ CPP="gcc -E" CXXCPP="g++ -E" This is not guaranteed to produce working output in all cases, you may have to build one architecture at a time and combine the results using the 'lipo' tool if you have problems. Installation Names ================== By default, 'make install' installs the package's commands under '/usr/local/bin', include files under '/usr/local/include', etc. You can specify an installation prefix other than '/usr/local' by giving 'configure' the option '--prefix=PREFIX', where PREFIX must be an absolute file name. You can specify separate installation prefixes for architecture-specific files and architecture-independent files. If you pass the option '--exec-prefix=PREFIX' to 'configure', the package uses PREFIX as the prefix for installing programs and libraries. Documentation and other data files still use the regular prefix. In addition, if you use an unusual directory layout you can give options like '--bindir=DIR' to specify different values for particular kinds of files. Run 'configure --help' for a list of the directories you can set and what kinds of files go in them. In general, the default for these options is expressed in terms of '${prefix}', so that specifying just '--prefix' will affect all of the other directory specifications that were not explicitly provided. The most portable way to affect installation locations is to pass the correct locations to 'configure'; however, many packages provide one or both of the following shortcuts of passing variable assignments to the 'make install' command line to change installation locations without having to reconfigure or recompile. The first method involves providing an override variable for each affected directory. For example, 'make install prefix=/alternate/directory' will choose an alternate location for all directory configuration variables that were expressed in terms of '${prefix}'. Any directories that were specified during 'configure', but not in terms of '${prefix}', must each be overridden at install time for the entire installation to be relocated. The approach of makefile variable overrides for each directory variable is required by the GNU Coding Standards, and ideally causes no recompilation. However, some platforms have known limitations with the semantics of shared libraries that end up requiring recompilation when using this method, particularly noticeable in packages that use GNU Libtool. The second method involves providing the 'DESTDIR' variable. For example, 'make install DESTDIR=/alternate/directory' will prepend '/alternate/directory' before all installation names. The approach of 'DESTDIR' overrides is not required by the GNU Coding Standards, and does not work on platforms that have drive letters. On the other hand, it does better at avoiding recompilation issues, and works well even when some directory options were not specified in terms of '${prefix}' at 'configure' time. Optional Features ================= If the package supports it, you can cause programs to be installed with an extra prefix or suffix on their names by giving 'configure' the option '--program-prefix=PREFIX' or '--program-suffix=SUFFIX'. Some packages pay attention to '--enable-FEATURE' options to 'configure', where FEATURE indicates an optional part of the package. They may also pay attention to '--with-PACKAGE' options, where PACKAGE is something like 'gnu-as' or 'x' (for the X Window System). The 'README' should mention any '--enable-' and '--with-' options that the package recognizes. For packages that use the X Window System, 'configure' can usually find the X include and library files automatically, but if it doesn't, you can use the 'configure' options '--x-includes=DIR' and '--x-libraries=DIR' to specify their locations. Some packages offer the ability to configure how verbose the execution of 'make' will be. For these packages, running './configure --enable-silent-rules' sets the default to minimal output, which can be overridden with 'make V=1'; while running './configure --disable-silent-rules' sets the default to verbose, which can be overridden with 'make V=0'. Particular systems ================== On HP-UX, the default C compiler is not ANSI C compatible. If GNU CC is not installed, it is recommended to use the following options in order to use an ANSI C compiler: ./configure CC="cc -Ae -D_XOPEN_SOURCE=500" and if that doesn't work, install pre-built binaries of GCC for HP-UX. HP-UX 'make' updates targets which have the same timestamps as their prerequisites, which makes it generally unusable when shipped generated files such as 'configure' are involved. Use GNU 'make' instead. On OSF/1 a.k.a. Tru64, some versions of the default C compiler cannot parse its '' header file. The option '-nodtk' can be used as a workaround. If GNU CC is not installed, it is therefore recommended to try ./configure CC="cc" and if that doesn't work, try ./configure CC="cc -nodtk" On Solaris, don't put '/usr/ucb' early in your 'PATH'. This directory contains several dysfunctional programs; working variants of these programs are available in '/usr/bin'. So, if you need '/usr/ucb' in your 'PATH', put it _after_ '/usr/bin'. On Haiku, software installed for all users goes in '/boot/common', not '/usr/local'. It is recommended to use the following options: ./configure --prefix=/boot/common Specifying the System Type ========================== There may be some features 'configure' cannot figure out automatically, but needs to determine by the type of machine the package will run on. Usually, assuming the package is built to be run on the _same_ architectures, 'configure' can figure that out, but if it prints a message saying it cannot guess the machine type, give it the '--build=TYPE' option. TYPE can either be a short name for the system type, such as 'sun4', or a canonical name which has the form: CPU-COMPANY-SYSTEM where SYSTEM can have one of these forms: OS KERNEL-OS See the file 'config.sub' for the possible values of each field. If 'config.sub' isn't included in this package, then this package doesn't need to know the machine type. If you are _building_ compiler tools for cross-compiling, you should use the option '--target=TYPE' to select the type of system they will produce code for. If you want to _use_ a cross compiler, that generates code for a platform different from the build platform, you should specify the "host" platform (i.e., that on which the generated programs will eventually be run) with '--host=TYPE'. Sharing Defaults ================ If you want to set default values for 'configure' scripts to share, you can create a site shell script called 'config.site' that gives default values for variables like 'CC', 'cache_file', and 'prefix'. 'configure' looks for 'PREFIX/share/config.site' if it exists, then 'PREFIX/etc/config.site' if it exists. Or, you can set the 'CONFIG_SITE' environment variable to the location of the site script. A warning: not all 'configure' scripts look for a site script. Defining Variables ================== Variables not defined in a site shell script can be set in the environment passed to 'configure'. However, some packages may run configure again during the build, and the customized values of these variables may be lost. In order to avoid this problem, you should set them in the 'configure' command line, using 'VAR=value'. For example: ./configure CC=/usr/local2/bin/gcc causes the specified 'gcc' to be used as the C compiler (unless it is overridden in the site shell script). Unfortunately, this technique does not work for 'CONFIG_SHELL' due to an Autoconf limitation. Until the limitation is lifted, you can use this workaround: CONFIG_SHELL=/bin/bash ./configure CONFIG_SHELL=/bin/bash 'configure' Invocation ====================== 'configure' recognizes the following options to control how it operates. '--help' '-h' Print a summary of all of the options to 'configure', and exit. '--help=short' '--help=recursive' Print a summary of the options unique to this package's 'configure', and exit. The 'short' variant lists options used only in the top level, while the 'recursive' variant lists options also present in any nested packages. '--version' '-V' Print the version of Autoconf used to generate the 'configure' script, and exit. '--cache-file=FILE' Enable the cache: use and save the results of the tests in FILE, traditionally 'config.cache'. FILE defaults to '/dev/null' to disable caching. '--config-cache' '-C' Alias for '--cache-file=config.cache'. '--quiet' '--silent' '-q' Do not print messages saying which checks are being made. To suppress all normal output, redirect it to '/dev/null' (any error messages will still be shown). '--srcdir=DIR' Look for the package's source code in directory DIR. Usually 'configure' can determine that directory automatically. '--prefix=DIR' Use DIR as the installation prefix. *note Installation Names:: for more details, including other options available for fine-tuning the installation locations. '--no-create' '-n' Run the configure checks, but stop before creating any output files. 'configure' also accepts some other, not widely useful, options. Run 'configure --help' for more details. hvisage-metalog-8e511b7/Makefile.am000066400000000000000000000002131512715635700171700ustar00rootroot00000000000000EXTRA_DIST = \ metalog.conf \ metalog.spec.in \ metalog.lsm.in sysconf_DATA = metalog.conf SUBDIRS = \ src \ man ACLOCAL_AMFLAGS = hvisage-metalog-8e511b7/NEWS000066400000000000000000000153071512715635700156450ustar00rootroot00000000000000* Version 20260105 - andy-bower: -- replace scandirat() with scandir() for POSIX compatibility * Version 20260103 - SimonGottsch: -- support different logging formats for local and remote logging (log_format, remote_format): legacy_timestamp (the current format, still default), legacy, rfc3164, rfc5424 -- support multiple remote syslog servers (remote_host, remote_port, remote_log, remote_format) -- introduce optional severity levels (log_severity); optionally filter logs sent to remote servers (remote_severity_level) - andy-bower: -- fix config directory feature: config files are sorted now alphanumerically to get determined behaviour -- support multiple sockets as logging source, e.g. for chrooted or containerized applications (socket) -- introduce optional native log compression for rotated logs (compress), when linked with zlib (--without-compress) -- introduce delayed log compression (compress_delay), so the latest log(s) stay uncompressed -- some clean ups, e.g. get rid of PATH_MAX - m-kress: -- introduce config test parameter (--test-config or -t) * Version 20230719 - m-kress: -- Do not substitute trailing control characters of a log line, but eliminate them completelly. Be aware, that this change will break existing filters that rely on the trailing underscore! -- note in config file and man page: comments must be started with # only at the beginning of a line -- add "configdir" to config, which allows reading additional config files ending with *.conf * Version 20230707 - m-kress: -- add missing brackets to harmonize code -- check (stat) the program path given as command and ignore the command, if not existing - auouymous: -- fix behavior of (program_)?regex and (program_)?neg_regex conditions - LonEox78: -- pointer to directory name was not initialized, so eventually weird directories were created - orbea: -- replace RETSIGTYPE with void -- silence obsolete warnings * Version 20220214 - jovanlanik: -- port to pcre2 -- doku has been updated, removed a lot of inconsistencies -- add an option to change group -- add permissions to configuration -- remove unused errptr * Version 20200113 - avoid writing logs to STDOUT twice - add line feed to sent UDP log entries - rkonrad: -- add support for nanoseconds in time stamp * Version 20181125 - closed memory leaks for remote syslog * Version 2018510 - orbea: -- clean up automake files * Version 20180327 - minor fix in man page * Version 20180326 - moved to GitHub hvisage/metalog - m-kress: -- add remote logging to a log server via UDP -- silences a minor compiler warning (unused return value) and a missing cast -- add the special value "NONE" as parameter for the keyword "logdir". A log entry with "NONE will not be written to a log file. * Version 3 - fix interaction between "postrotate_cmd" and "logdir" (by Matt Whitlock #2887065) - switch to pkg-config for pcre look up - update bundled gnulib code * Version 2 - fix long standing typo where the minute field in the rotated log was replaced with the current month: %m instead of %M (by dorian33 #3027782) - add support for rate limiting of messages with the new "ratelimit" and "ratelimit_burst" keywords (by Martin von Gagern #2777251) - standardize warning/error output * Version 1 - switch over to using daemon() by default - fix stupid semicolon typo causing breaks on all lines (Gentoo Bug #258830) - add "flush" keyword to control flushing per log output (by Martin von Gagern #2549231) - add --with-unicode option to control unicode mangling #2669923 * Version 0.9 - add --no-kernel option by Adrian Perez de Castro to disable kernel message monitoring (#1727129 and #1751757) - convert source tree to use gnulib rather than random local replacements - fix by Amigac to not skip the "command" line when "logdir" and "break" are both in use (#2401520) - add "stamp_fmt" keyword to control the timestamp format in messages (based partially on work from cJ #1910360 and Philip White #1690349, and for #1232638) - make sure to flush all buffers on exit in buffered mode as pointed out by Ingo Bormuth (Gentoo Bug #233794) * Version 0.8 - tweak signal handlers some more (#1655169) - when dequeuing messages from the signal pipe, abort if malloc() failed - add hal filter to default metalog.conf (Gentoo Bug #174847) - add support from Eric Schwimmer / Debian for a new "postrotate_cmd" option (#1706160) - fix from Eric Schwimmer for div by zero error when maxtime = 0 (#1706158) - add support from Eric Schwimmer for controlling the "Last output repeated N times" message (#1706164) - use %e rather than %d for logging dates (Gentoo Bug #177258) * Version 0.8-rc4 - fix typo in previous change when checking the return of strftime() as reported by Mark Wagner. * Version 0.8-rc3 - use strftime() rather than printing out time values ourself so we get localization for free via the system libc and so we don't have to manipulate time structs ourselves (#1054478). * Version 0.8-rc2 - config file in package updated (pull fixes from Gentoo) - cleanup code a bit - make --help more [non-root] friendly - change default 'command spawn' messages to off (use --verbose to get back old noisy behavior) - check for setprogname() so we build on FreeBSD 6.1 (#1557585, fix from Diego Petteno) - fix error in memory allocation when using multiple facilities #1217560 - queue up messages in signal handlers via a pipe so that we don't hit deadlocks by using functions that are unsafe for use inside these states * Version 0.8-rc1 - new keyword: break - config file in package updated (synch with break keyword) - kernel logging problem fix - race condition fix - metalog.conf man page added - log rotation can be disabled with maxsize or maxtime = 0 * Version 0.7 - Logging is now synchronous by default. Use --async to get back to the asynchronous behavior. - Duplicate messages are now only logged once. - Negative regexes were implemented and programs can now also be matched against regexes. See the new neg_regex, program_regex and program_neg_regex keywords. - The maximum urgency can now be specified for each block. A new keyword, "maximum" completes "minimum". - A PID file is now created. It defaults to /var/run/metalog.pid but it can be changed with the --pidfile switch. - The location of the configuration file can now be changed with --with-configfile. - The code was cleaned up. * Version 0.7-beta - This is a transitional version with new features contributed by Hendrick Visage. * Version 0.6 - Metalog is now working on Linux, OpenBSD, FreeBSD and NetBSD. - New --consolelevel option to set up the console level on Linux. - RPM packages are now available. * Version 0.5 - First public release. hvisage-metalog-8e511b7/README000066400000000000000000000412031512715635700160200ustar00rootroot00000000000000 .:. METALOG .:. ------------------------ BLURB ------------------------ Metalog is a modern replacement for syslogd and klogd. The logged messages can be dispatched according to their facility, urgency, program name and/or Perl-compatible regular expressions. Log files can be automatically rotated when they exceed a certain size or age. External shell scripts (e.g., mail) can be launched when specific patterns are found. Logs are written according to RFC3164, RFC5423 or a minimal format with optional severity levels. It can send its logs to remote syslog servers via UDP. It can gather info from the kernel or /dev/log as well as from several Unix Domain Sockets. This allows logging from chrooted or containerized applications. Metalog is simple to configure, accepts unlimited number of rules and has (switchable) memory bufferization for maximal performance. http://metalog.sourceforge.net/ ------------------------ COMPILATION ------------------------ In order to compile Metalog, you need to have the PCRE2 library. It's used to process Perl-compatible regular expressions. libpcre2 comes with many distributions, but you can also download it from: https://www.pcre.org/ In case you want to use the optional native gzip compression for rotated log files you need to have zlib. It's very likely, that this it's already installed, but you can also download it from: https://www.zlib.net/ Then, compiling and installing Metalab isn't rocket science: ./autogen.sh ./configure make make install ------------------------ CONFIGURATION ------------------------ A configuration file should be installed. Its default location is /etc/metalog.conf (unless you tweaked --with-sysconfdir). You can find a sample file in this directory, but it's certainly not perfect for your system and your needs. So read on. A configuration file has the following syntax: [default values]
:
...
:
... [...] To make it clear, here's an example: maxsize = 100000 maxtime = 86400 maxfiles = 5 Kernel messages: facility = "kern" logdir = "/var/log/kernel" Crond: program = "crond" logdir = "/var/log/crond" A section defines several things: - A title (useless for the software, it's just to make your configuration file look better). - Filters: you can define facilities, program names, urgency levels and regular expressions. An incoming message will pass through all filters. If all conditions are matching, actions defined for the section are performed. - Actions: they are taken only when all previous conditions are met. Only two actions are currently possible: write the message to a log file, and/or launch an external script. Here's a list of values that can be independently assigned for each section: * minimum = : only record a message if its urgency is inferior or equal to . Level '0' is the most critical one, while level '7' is for debugging messages. 'minimum = 5' will strip all non-important messages. The default minimum level is 7 (ie. keep all messages). Example: record only critical messages to /var/log/important: Critical messages: facility = "*" minimum = 1 logdir = "/var/log/important" * maximum = : don't log if the message level exceeds that value. By default, maximum is the largest possible level. * facility = : only record a message if the application that issued it uses syslog facility . * break = 0|1 (default=0): if set to 1 and a section is matched, perform action, but don't consider any more possible section matches below this one in the config file. This is useful for creating a config where specific types of log messages are matched and dispatched, while a "catch-all" section at the bottom of the config file handles the default case. Using break=0 would cause messages to be potentially handled by multiple sections, causing message duplication, while using break=1 (default) on the sections above the "catch-all" would avoid duplication. Facility names are: "auth", "authpriv", "cron", "daemon", "ftp", "kern", "lpr", "mail", "news", "security", "syslog", "user", "uucp", "local0", "local1" ... "local7". All kernel messages are logged with facility "kern". A section can have several "facility = ..." lines to match more than one facility. If is "*", it'll match all the facilities. Example: record all authentication messages to /var/log/auth: Authentication messages: facility = "auth" facility = "authpriv" logdir = "/var/log/auth" * program = : only record messages signed by a specific daemon or program. You can use this as a modern alternative to syslog facilities: use "*" as a facility, and set a program name with that directive. Kernel messages can be caught with 'program = "kernel"'. Example: record Pure-FTPd messages in a directory, and in.ftpd messages in another directory (although the facility is the same: FTP): In.FTPd messages: facility = "*" program = "in.ftpd" logdir = "/var/log/in.ftpd" Pure-FTPd messages: facility = "*" program = "pure-ftpd" logdir = "/var/log/pure-ftpd" * program_regex = : similar to program, but not just a string equal match, but a regular expression. Example: this would match program fields with [postfix/smtp], [postfix/smtpd] and [postfix/cleanup] etc. All Postfix messages: facility = "*" program_regex = "postfix" logdir = /var/log/postfix * program_neg_regex = : log programs that do _not_ match the regex. * regex = : a message must match the regular expression to pass that filter. Multiple regexes are allowed for a single section. All Perl extensions are allowed, and matching is case insensitive. Example: record all authentication failures to /var/log/pwdfail: Password failures: regex = "(password|login|authentication)\s+(fail|invalid)" regex = "(failed|invalid)\s+(password|login|authentication)" regex = "ILLEGAL ROOT LOGIN" logdir = "/var/log/pwdfail" * neg_regex = : this is the opposite of the previous directive. Logging will occur if the regex doesn't match. It can be useful to remove the crap, and it can be freely mixed with "regex" directives. "regex" and "neg_regex" directives are scanned in order. Example: facility = "mail" neg_regex= "starting daemon" logdir = "/var/log/mail" * socket = : metalog will create a socket file on the given path and listen on this Unix Domain Socket. That way applications in a chroot jail can still send log messages that will be received by metalog. Such a socket could also get bind mounted in LXC containers and overmount /dev/log in there. Within the container then is no longer a own logger necessary. This option can be set in the default part of the config or within a section. When used within a section it can we use as a selector for a specific log file instead of flags like "program", "facility", "regex" and so on. * maxsize = : automatically rotate log files when their size have exceeded that size. Messages are never truncated and no message can be lost during a rotation. Every section can have a different maxsize value. * maxfiles = : how many files to keep after rotation. This parameter can be set independently for each section. It defaults to 5. * maxtime = : automatically rotate log files when they are older than this number of seconds. Every section can have a different maxtime value. maxsize and maxtime can be combined together, so that rotation occurs when any of these conditions occurs. * compress = 0|1: With this active and when compiled with zlib support the rotated log files will get compress with gzip. * compress_delay = : This will leave the amount of the latest rotated log files uncompressed. Example: rotate log files daily or when they are more than 1,000,000 bytes long, keep only 3 history files with the first and second uncompressed and the third one compressed: maxsize = 1000000 maxtime = 86400 maxfiles = 3 compress = 1 compress_delay = 2 * log_format = : The log entries can be written in different formats: "legacy", "legacy_timestamp", "rfc3164" and "rfc5424". The legacy ones are quite similar to the format defined in obsolete RFC3164. legacy_timestamp is the default format. * log_severity = : In case a legacy format is used, this will introduce the severity info to a log entry. In both RFC formats this is already included and can't get disabled. * showrepeats = 0|1: disable printing the "last message repeated N times" summary messages. When showrepeats is set to 1, messages will be printed directly to the log, without summarizing them based on number received (which can cause problems for some log monitoring programs, as well as delaying repeated messages if another unique message isn't received promptyly). Defaults to 0 (i.e. repeated messages will be summarized) * logdir = : record messages in the specified directory. If the directory doesn't exist, it will be automatically created when the first matching message will be logged (the parent directory has to exist, though). * perms = permissions for the log directory. Defaults to 0700 Example: Let those in the group with the GID of the process read the log. Don't forget to run metalog as the group. perms = 0770 * command = : run a program or a shell-script when all conditions are met. This directive is not incompatible with logdir: a message can be both logged and passed to an external command. When the command is launched, the first argument is filled with the date the message was received, the second argument is the program name, and the last one is the text of the message itself. Environment variables aren't cleared. Example: send a mail to root when authentication failures occur: Mail password failures: regex = "(password|login|authentication)\s+(fail|invalid)" regex = "(failed|invalid)\s+(password|login|authentication)" regex = "ILLEGAL ROOT LOGIN" command = "/usr/local/sbin/pwdfail.sh" "pwdfail.sh" can be a simple shell script like this one: #! /bin/sh echo "$3" | mail -s "Password failure (program: $2)" root Don't forget to properly quote arguments to avoid security problems. * postrotate_cmd = : run a script after rotating If specified, the postrotate_cmd is run after log-files are rotated. The following parameters are provided, environments are not cleared: date: date of the last message received prog: program name of the last message received file: file name with path of the rotated log-file Example: compress rotated log files with bzip2 postrotate_cmd = /usr/local/bin/compress.sh "/usr/local/bin/compress.sh" provides bzip2 compression: #!/bin/sh #* #* Copyright (c) 2006 by Lukas Ruf (lukas.ruf@lpr.ch), #* Computer Engineering and Networks Laboratory (TIK), #* Swiss Federal Institute of Technology (ETH) Zurich #* DATE="$1" PRG="$2" FILE="$3" # tests to run bzip2 # parameter file is provided # file exists # file has a size greater than zero if [ -n "${FILE}" -a -f "${FILE}" -a -s "${FILE}" ]; then bzip2 -9 ${FILE} fi * configdir = : This optional directory can contain more config files that will get interpreted at metalog start. Only file names ending with ".conf" are interpreted. This option is only allowed once, all repetitions will be ignored. The content of the additional config files will be appended to the existing config in alphanumeric order of the file names, to get a determined behaviour of metalog. The config files could contain sections for specific services. Example: Content of /etc/metalog.d/: 00_kernel.conf 10_metalog.conf 11_crond.conf 20_application_xy.conf 21_apache.conf --------- CONFIGURATION: REMOTE SYSLOG SERVERS ------------ metalog can send log messages to syslog server(s) via UDP. * remote_log = 0|1: Log messages will be sent to a remote syslog server. If defined in the default settings section, all log files will be sent. It can also be defined in the seperate sections, so remote logging can get activated/deactivated for every single section. * remote_host = : This is the remote syslog server. * remote_port = : This is the UDP the syslog server listens for new log messages. * remote_format = : It makes sense to set the format to "rfc3164" or "rfc5424", so the host name of the sender will be included in the message. * remote_severity_level = : This defines which log messages will be sent to the remote syslog servers. It filters the less important messages and so reduces the amount of messages sent. Example: send all logs to a remote server: remote_host = 10.1.0.1 remote_port = 514 remote_format = rfc5424 remote_severity_level = 3 This will send all log messages also to the remote syslog server, that have a severity level of 3 [ERROR] or a higher (that have a lower number). If several syslog servers should receive the logs, the above remote_* commands can be replaced with remote_*[], where is a alphanumeric value. Example: This will send the logs to two servers: one called "main" and the other one "backup". remote_log[main] = 1 remote_host[main] = 10.1.0.1 remote_port[main] = 514 remote_format[main] = rfc5424 remote_severity_level[main] = 3 remote_log[backup] = 1 remote_host[backup] = 192.168.1.10 remote_port[backup] = 514 remote_format[backup] = rfc5424 remote_severity_level[backup] = 3 ------------------------ LOG FILES ------------------------ With the "logdir" directive, messages from a specific section are recorded in a directory. In that directory, the following files are created: - "current": this file contains the latest recorded messages. It can be incomplete (ie. data is being written to the file when you are reading it). - ".timestamp": the creation date of "current". Needed for the "maxtime" directive. - "log----::": old logs, chronologically sorted. If you ever delete these files by hand for some obscure reasons, it's not a bad idea to restart the daemon (and even better: to stop it before you mess the directories). ------------------------ RUNNING METALOG ------------------------ Kill "klogd" and "syslogd" first. Don't run Metalog while they are running. Multiple programs listening for the same source of data is a silly idea. Once these programs are killed (and you are *sure* they are killed), check that /etc/metalog.conf is installed, and simply run: /usr/local/sbin/metalog & On GNU/Linux systems, two processes are spawned: one is the "MASTER", doing much of the work. The other one (named "KERNEL") is needed for Linux and replaces the "klogd" daemon. It is responsible for logging kernel messages. By default, messages are immediately recorded into log files, and the I/O cache is flushed to be sure that you don't loose any message if a fatal crash or a power outage occurs. But if you prefer speed, Metalog can work asynchronously, using the --async switch. In this mode, to avoid disk I/O, and unlike traditional syslog daemons, Metalog works in memory buffers, then flushes the data to disk by blocks. It improves a lot overall performances. If you temporarely want to switch to the asynchronous mode, send an USR2 signal to the process. Something like: kill -USR2 $(cat /var/run/metalog.pid) should do the trick. Later, if you want to watch activity in real-time (like a good old "tail -f" on a log file), you can disable buffering. Just send an USR1 signal to the "MASTER" process. You can always re-enable buffering afterwards. ------------------------ RUN-TIME OPTIONS ------------------------ Metalog accepts some run-time options: - '-a' or '--async': improve performance by using buffers (but log files won't get updated in real time). - '-B' or '--daemonize': have the server start in background (daemonization). - '-c ' or '--consolelevel=': set the console log level on Linux. Valid values are from 0 to 7. The default is 7. - '-C ' or '--configfile=': use an alternative configuration file. - '-g ' or '--group=': change the GID of the metalog process. Created files will be owned by this group. - '-h' or '--help': show help and version number. - '-p ' or '--pidfile=': set the name of the file that will hold the PID number. It defaults to /var/run/metalog.pid - '-s' or '--sync': start in synchronous mode, with no bufferization. - '-t' or '--test-config': Exit after parsing the config file(s). Returns 0 if config is ok. -Frank DENIS "Jedi/Sector One" . hvisage-metalog-8e511b7/autogen.sh000077500000000000000000000000441512715635700171370ustar00rootroot00000000000000#!/bin/sh set -e autoreconf -i -f hvisage-metalog-8e511b7/configure.ac000066400000000000000000000046501512715635700174330ustar00rootroot00000000000000AC_PREREQ(2.68) AC_INIT([metalog], [4], [metalog-users@lists.sourceforge.net]) AM_INIT_AUTOMAKE([1.11 dist-xz no-dist-gzip silent-rules -Wall]) AM_SILENT_RULES([yes]) AC_CONFIG_SRCDIR(src/metalog.c) AC_CONFIG_HEADERS([config.h]) gl_cv_func_printf_infinite_long_double=yes dnl Checks for programs. AC_PROG_INSTALL AC_USE_SYSTEM_EXTENSIONS AC_PROG_CC AC_SYS_LARGEFILE PKG_PROG_PKG_CONFIG dnl Checks for header files AC_CHECK_HEADERS(sys/klog.h) dnl Checks for typedefs, structures, and compiler characteristics. AC_PROG_GCC_TRADITIONAL AC_C_INLINE AC_C_CONST AC_TYPE_MODE_T AC_TYPE_PID_T AC_STRUCT_TM AC_TYPE_UID_T AC_TYPE_OFF_T dnl Options AM_WITH_DMALLOC AC_MSG_CHECKING([whether syslog names are available]) AC_COMPILE_IFELSE( [AC_LANG_PROGRAM( [[ #define SYSLOG_NAMES 1 #include #include ]], [[ (void) facilitynames ]], )], [ AC_MSG_RESULT(yes) AC_DEFINE(HAVE_SYSLOG_NAMES, , [Define if syslog names are defined]) ], [ AC_MSG_RESULT(no) ]) dnl Checks for libraries. dnl Checks for library functions. AC_FUNC_ALLOCA AC_FUNC_MEMCMP AC_FUNC_STRFTIME AC_FUNC_STAT AC_FUNC_VPRINTF AC_FUNC_GETGROUPS AC_CHECK_FUNCS_ONCE(m4_flatten([ daemon klogctl setproctitle setprogname ])) dnl Conditional functionality AC_ARG_WITH(compress, [AS_HELP_STRING([--without-compress],[Disable support for compressing rotated logs])]) AS_IF([test "x$with_compress" != "xno"], [ PKG_CHECK_MODULES([ZLIB], [zlib]) AC_DEFINE([WITH_COMPRESS], [1], [Define to include support for compression with zlib]) ]) dnl Libraries PKG_CHECK_MODULES([PCRE2], [libpcre2-8]) CFLAGS="$CFLAGS $PCRE2_CFLAGS $ZLIB_CFLAGS" LIBS="$LIBS $PCRE2_LIBS $ZLIB_LIBS" dnl Options AM_WITH_DMALLOC WFLAGS="" AC_DEFUN([W_CHECK_CFLAG],[AX_CHECK_COMPILE_FLAG([$1],[WFLAGS="$WFLAGS $1"])]) W_CHECK_CFLAG([-Wall]) W_CHECK_CFLAG([-W]) W_CHECK_CFLAG([-Wcast-qual]) W_CHECK_CFLAG([-Wcast-align]) W_CHECK_CFLAG([-Wmissing-noreturn]) W_CHECK_CFLAG([-Wbad-function-cast]) W_CHECK_CFLAG([-Wstrict-prototypes]) W_CHECK_CFLAG([-Wwrite-strings]) W_CHECK_CFLAG([-Wreturn-type]) AC_SUBST(WFLAGS, $WFLAGS) AC_ARG_WITH(unicode, [AS_HELP_STRING([--with-unicode],[Enable unicode support (default no)])]) AS_IF([test "x$with_unicode" = "xyes"], [ AC_DEFINE([ACCEPT_UNICODE_CONTROL_CHARS], [1], [Don't scramble unicode]) ]) AC_CONFIG_FILES(m4_flatten([ Makefile src/Makefile man/Makefile man/metalog.8 man/metalog.conf.5 metalog.spec metalog.lsm ])) AC_OUTPUT hvisage-metalog-8e511b7/man/000077500000000000000000000000001512715635700157135ustar00rootroot00000000000000hvisage-metalog-8e511b7/man/Makefile.am000066400000000000000000000000441512715635700177450ustar00rootroot00000000000000man_MANS = metalog.8 metalog.conf.5 hvisage-metalog-8e511b7/man/metalog.8.in000066400000000000000000000052261512715635700200460ustar00rootroot00000000000000.TH "metalog" "8" "@VERSION@" "Frank DENIS" "Syslog daemon" .SH "NAME" .LP metalog \- an alternative syslog daemon .SH "SYNTAX" .LP metalog [\fIoptions\fR] .SH "DESCRIPTION" .LP Metalog is a modern replacement for syslogd and klogd. The logged messages can be dispatched according to their facility, urgency, program name and/or Perl\-compatible regular expressions. Log files can be automatically rotated when they exceed a certain size or age. External shell scripts (ex: mail) can be launched when specific patterns are found. Logs are written according to RFC3164, RFC5423 or a minimal format with optional severity levels. It can send its logs to remote syslog servers via UDP. It can gather info from the kernel or /dev/log as well as from several Unix Domain Sockets. This allows logging from chrooted or containerized applications. Metalog is easier to configure than syslogd and syslog\-ng, accepts unlimited number of rules and has (switchable) memory bufferisation for maximal performance. .SH "OPTIONS" .LP .TP .BR \-a ", " \-\-async Improve performance by using buffers (bug log files won't get updated in real time). Can be overridden for individual logs. .TP .BR \-B ", " \-\-daemonize Have the server start in background (daemonization). .TP .BR \-c ", " \-\-consolelevel = \fR\fI0..7\fR Set the console log level (Linux only). .TP .BR \-C ", " \-\-configfile = \fR\fIfile\fR Use an alternate configuration file. .TP .BR \-g ", " \-\-group = \fR\fIgroup\fR Change the GID of the metalog process. Created files will be owned by this group. .TP .BR \-h ", " \-\-help Output help information and exit. .TP .BR \-N ", " \-\-no\-kernel Do not attempt to log messages from the kernel. .TP .BR \-P ", " \-\-pidfile = \fR\fIfile\fR Use an alternate file to store the process number. .TP .BR \-s ", " \-\-sync ", " \-\-synchronous Start in synchronous mode, with no bufferization. Can be overridden for individual logs. .TP .BR \-t ", " \-\-test-config Exit after parsing the config file(s). Returns 0 if config is ok. .TP .BR \-v ", " \-\-verbose Run in verbose mode (useful for debugging behavior). .TP .BR \-V ", " \-\-version Display metalog version information. .SH "SIGNALS" .TP .B SIGUSR1 Enable synchronous mode. .TP .B SIGUSR2 Disable synchronous mode. .fi .SH "FILES" .LP Note that the exact paths depend on the build settings. These are the standard paths. .nf .I /etc/metalog.conf .I /var/run/metalog.pid .I /dev/log .fi .SH "AUTHORS" .LP .nf Mike Frysinger Laurent Wandrebeck (low) Leo Lipelis Hendrik Visage Frank DENIS (Jedi/Sector One) .fi .SH "SEE ALSO" .BR metalog.conf (5) hvisage-metalog-8e511b7/man/metalog.conf.5.in000066400000000000000000000265731512715635700207770ustar00rootroot00000000000000.TH "metalog.conf" "5" "@VERSION@" "Frank DENIS" "Metalog configuration file" .SH "NAME" .LP metalog.conf \- configuration file for metalog .SH "SYNTAX" .LP .nf [default values]
# Comments are introduced with "#", which is ONLY allowed at the beginning of a line. .fi .SH "DESCRIPTION" .LP [default values] will be used if you do not redefine them in a section. You can choose
as you wish. It doesn't mean anything, just allow you to keep an easy to read config file. Values names can be one of the following: .TP \fBmaxsize\fR = \fI\fR Once a logfile has exceeded the value defined (in bytes), it will be rotated. If \fBmaxfile\fR is equal to zero, it disables log rotation. Defining a default value is a good idea. .TP \fBmaxtime\fR = \fI\fR Once a logfile is older than the value defined (in seconds), it will be rotated. Defining a default value is a good idea. NB: A logfile is rotated when either \fBmaxsize\fR or \fBmaxtime\fR limit is reached. If either one or both is equal 0, then log rotation is disabled. .TP \fBmaxfiles\fR = \fI\fR This value indicates the maximum number of rotated files kept. So you'll have x rotated files (log-date-string filename type), plus the file named "current". .TP \fBfacility\fR = \fI""\fR Only records a message if the application that issued it uses syslog facility . Facility names are : "auth", "authpriv", "cron", "daemon", "ftp", "kern", "lpr", "mail", "news", "security", "syslog", "user", "uucp", "local0", "local1" ... "local7". All kernel messages are logged with facility "kern". A section can have several "facility = ..." lines to match more than one facility. If is "*", it'll match all the facilities. .TP \fBremote_host\fR = \fI\fR Log entries are sent to the remote log server defined by this IP address or domain name. This can only be defined in the default values section. Before configuring other remote host options (port, format, ...) remote_host must be set. All log messages are sent there, limitations via "ratelimit", "ratelimit_burst" or "showrepeats" are ignored for log message sent to the remote log server. In case a domain or host name is configured, the necessary DNS request will be repeated after every failed attempt or after 120 seconds when the name has been successfully resolved. .TP \fBremote_host[]\fR = \fI\fR Equal to \fBremote_host\fR, but can be used multiple times to add more remote log servers. The \fIname\fR part can be any string, but must be the same for \fBremote_port[]\fR etc. .TP \fBremote_port\fR = \fI\fR The UDP port of the remote log server. Default is "514". This can only be defined in the default values section. .TP \fBremote_port[]\fR = \fI\fR Equal to \fBremote_port\fR, but can be used multiple times to add more remote log servers.The \fIname\fR part can be any string, but must be the same for \fBremote_host[]\fR etc. .TP \fBremote_log\fR = \fI\fR Default is \fI0\fR. Log messages are sent to the remote log server when set to \fI1\fR. Can be defined for default values or in sections. .TP \fBremote_log[]\fR = \fI\fR Equal to \fBremote_log\fR, but can be used multiple times to add more remote log servers. The \fIname\fR part can be any string, but must be the same for \fBremote_host[]\fR etc. .TP \fBremote_format\fR = \fI\fR Default is \fIlegacy_timestamp\fR. Log messages are sent to the remote log server with the defined format. Format options are : "legacy", "legacy_timestamp", "rfc3164" and "rfc5424" .TP \fBremote_format[]\fR = \fI\fR Equal to \fBremote_format\fR, but can be used multiple times to add more remote log servers. The \fIname\fR part can be any string, but must be the same for \fBremote_host[]\fR etc. .TP \fBremote_severity_level\fR = \fI\fR Default is \fI7\fR. Log messages are sent to the remote log server only when its urgency is inferior or equal to \fI\fR. Level '0' is the most critical one, while level '7' is for debugging messages. .TP \fBremote_severity_level[]\fR = \fI\fR Equal to \fBremote_severity_level\fR, but can be used multiple times to add more remote log servers. The \fIname\fR part can be any string, but must be the same for \fBremote_host[]\fR etc. .TP \fBlog_format\fR = \fI\fR Default is \fIlegacy_timestamp\fR. Log messages are written to filesystem or stdout with the defined format. Format options are: "legacy", "legacy_timestamp", "rfc3164" and "rfc5424" .TP \fBlog_severity\fr = \fI\fR Default is \fI0\fR. Log the severity level when logging in "legacy", "legacy_timestamp". The severity level will always be part of log entries when in "rfc3164" or "rfc5424". .TP \fBbreak\fR = \fI\fR Default is \fI0\fR. If set to \fI1\fR and a section is matched, perform action, but don't consider any more possible section matches below this one in the config file. This is useful for creating a config where specific types of log messages are matched and dispatched, while a "catch-all" section at the bottom of the config file handles the default case. Using \fI0\fR would cause messages to be potentially handled by multiple sections, causing message duplication, while using \fI1\fR on the sections above a final "catch-all" would avoid duplication. .TP \fBminimum\fR = \fI\fR Only record a message if its urgency is inferior or equal to \fI\fR. Level '0' is the most critical one, while level '7' is for debugging messages. \fI5\fR will strip all non-important messages. The default minimum level is \fI7\fR (i.e. keep all messages). .TP \fBmaximum\fR = \fI\fR Don't log if the message level exceeds that value. By default, \fBmaximum\fR is the largest possible level. .TP \fBlogdir\fR = \fI"/dir/where/logs/will/be/written/"\fR Files will be written under the specified directory. The special value \fI"NONE"\fR will skip the log message. .TP \fBperms\fR = \fI\fR Permissions for the log directory. Defaults to \fI0700\fR .TP \fBprogram\fR = \fI"name"\fR Can be used to do filtering instead of \fBfacility\fR. Remember to use the executable name. .TP \fBregex\fR = \fI"perl compatible regular expression"\fR Can be used when you only want to log messages that match the \fIpattern\fR (like "invalid", "fail", etc...) to send them to a single directory. Multiple \fBregex\fR may be defined in a single section, only one must match. .TP \fBneg_regex\fR = \fI"perl compatible regular expression"\fR Can be used when you only want to log messages that do not match the \fIpattern\fR. A \fBneg_regex\fR match will override any \fBregex\fR matches and not log the message. When one or more \fBregex\fR are provided, at least one of them must match to log the message. The lack of any \fBregex\fR will result in message being logged when no \fBneg_regex\fR match. Multiple \fBneg_regex\fR may be defined in a section, only one must match. .TP \fBpostrotate_cmd\fR = \fI"/path/to/a/program"\fR Run specified program after a log file has been rotated. The program is passed the date, the program name ("metalog"), and the new logfile name. .TP \fBprogram_regex\fR = \fI"perl compatible regular expression"\fR Similar to \fBprogram\fR, this is a regex that matches the program name to send all messages from related programs to the same log file. Multiple \fBprogram_regex\fR may be defined in a section, only one must match. .TP \fBprogram_neg_regex\fR = \fI"perl compatible regular expression"\fR The inverse of \fBprogram_regex\fR to filter out logs from programs that match. A \fBprogram_neg_regex\fR match will override any \fBprogram_regex\fR matches and not log the message. When one or more \fBprogram_regex\fR are provided, at least one of them must match to log the message. The lack of any \fBprogram_regex\fR will result in message being logged when no \fBprogram_neg_regex\fR match. Multiple \fBprogram_neg_regex\fR may be defined in a section, only one must match. .TP \fBshowrepeats\fR = \fI\fR Set to \fI0\fR to filter out repeat log messages. .TP \fBcommand\fR = \fI"/path/to/program/to/execute"\fR Run the specified program as soon as something is logged in a given section. The program is passed the date, the matching program name, and the log message. In case the program doesn't exist at metalog startup, metalog will not exit and just ignore that config line. .TP \fBstamp_fmt\fR = \fI"%b %e %T"\fR Format of the human readable timestamp prepended to all log messages. The format string supports all conversion specifications from strftime plus %[nnn]N for nanoseconds (default: nine numbers long, can be shortened with nnn < 9). The format string with %[nnn]N replaced is then passed to the .BR strftime (3) function. An empty string is used to disable timestamps (for cases where the log messages already include its own). Will be ignored for logging if \fBlog_format\fR and for remote logging if \fBremote_format\fR is set to \fIrfc3164\fR or \fIrfc5424\fR. .TP \fBflush\fR = \fI\fR If set to \fI0\fR, matching log messages will always be buffered. If set to \fI1\fR, they will always be written to the file system immediately. Both settings override the global default given through command line parameters (\fB\-a\fR/\fB\-s\fR) or signals. .TP \fBratelimit\fR = \fI"5/m"\fR Limits the rate of logged messages to the specified number of messages per unit of time. Valid units of time are \fIs\fRecond, \fIm\fRinute, \fIh\fRour and \fId\fRay, each identified by its first letter. Fractional values are allowed such as \fI"0.5/m"\fR to make human parsing easier. A limit of \fI0\fR (the default) may be used to disable any rate limit handling. In this case, the unit of time may be omitted. .TP \fBratelimit_burst\fR = \fI\fR Up to this number of lines will be printed at the beginning of a burst of message, if the rate of messages has been well below the limit before. The specified message rate will not be exceeded. The default value of 1 disables special treatment for bursts. Values less than 1 are invalid and will be rejected. .TP \fBconfigdir = \fI"/path/to/directory/with/more/config/files"\fR This optional directory can contain more config files that will get interpreted at metalog start. Only file names ending with ".conf" are interpreted. This option is only allowed once, all repetitions will be ignored. The content of the additional config files will be appended to the existing config in alphanumeric order of the file names, to get a determined behaviour of metalog. .TP \fBsocket = \fI"/path/to/logging/socket"\fR Listen and filter on an additional logging socket. If creation of the sockets fails metalog will continue without that source of logs. .TP \fBcompress = \fI\fR Default is \fI0\fR. If set to \fI1\fR, rotated logs are compressed in gzip format. This option will be ignored if metalog was built without compression support. .TP \fBcompress_delay = \fI\fR Default is \fI0\fR. The number of most recent rotated log files to leave uncompressed. .SH "FILES" .LP Note that the exact paths depend on the build settings. These are the standard paths. .nf .I /etc/metalog.conf .fi .SH "AUTHORS" .LP .nf Mike Frysinger Laurent Wandrebeck (low) Leo Lipelis Hendrik Visage Frank DENIS (Jedi/Sector One) .fi .SH "SEE ALSO" .BR metalog (8) hvisage-metalog-8e511b7/metalog.conf000066400000000000000000000113051512715635700174370ustar00rootroot00000000000000# Sample Metalog configuration file # Comments are introduced with "#", which is ONLY allowed at the beginning of a line. # Rotate log after file size (1048576 = 1 megabyte) maxsize = 1048576 # Rotate log at least after 30 days (in seconds) maxtime = 2592000 # Number of archive files per directory maxfiles = 5 # Compress rotated logs compress = 1 # Leave one rotated log file uncompressed compress_delay = 1 # Directory with more config files to load; files names must end with ".conf" #configdir = /etc/metalog.d # Permissions for log directories. 0750 allows group to read logs. 0700 is default. #perms = 0750 # Format of the timestamp: YYYY-MM-DD HH:MM:SS.NNN #stamp_fmt = "%F %T.%3N" # Listen for additional log messages on a socket (Unix Domain Socket) #socket /var/chrooted/app/metalog.socket # Set the standard how to format the log entries, available are # "legacy_timestamp" (is default), "legacy", "rfc3164" and "rfc5424" #log_format = rfc5424 # Print severity level in formats "legacy" or "legacy_timestamp" #log_severity = 1 # Send all logs via UDP to a remote log server #remote_log = 1 # Configures a single remote log server #remote_host = 192.168.1.2 #remote_port = 514 #remote_format = rfc5424 #remote_severity_level = 7 # Alternative configuration: remote log server(s), differenciate with strings within [] #remote_log[another_server] = 1 #remote_host[another_server] = 192.168.1.3 #remote_port[another_server] = 514 #remote_format[another_server] = rfc5424 #remote_severity_level[another_server] = 7 # This will capture all of the internal log messages that metalog itself # generates. If you use any "command" options below, you will want this # as metalog generates a lot of status messages whenever it executes a # command and children processes exit. # #Metalog: # program = "metalog" # logdir = "/var/log/metalog" # break = 1 # Uncomment and adjust the following lines according to your console logging # needs. If you want to only output things that were not caught by other log # sections, move this to the end of the file. Make sure this command is on # your root partition if you have /usr mounted separately. This script should # merely write $@ to some device (your console for messages): # echo "$@" > /dev/tty10 # #console logging: # facility = "*" # command = "/sbin/consolelog.sh" Everything important: facility = "*" minimum = 6 logdir = "/var/log/everything" #if break keyword does not appear, rules after here will be run. Everything very important: facility = "*" minimum = 1 logdir = "/var/log/critical" Password failures: regex = "(password|login|authentication)\s+(fail|invalid)" regex = "(failed|invalid)\s+(password|login|authentication|user)" regex = "ILLEGAL ROOT LOGIN" logdir = "/var/log/pwdfail" # command = "/usr/local/sbin/mail_pwd_failures.sh" # If you changed default permissions it may be a good idea to set more # restrictive permissions on sensitive logs. # perms = 0700 Kernel messages: facility = "kern" logdir = "/var/log/kernel" break = 1 # Additionally send this log entries via UDP to a remote log server # remote_log = 1 # Alternative configuration: send the log to a specific remote log server # remote_log[another_server] = 1 Crond: facility = "cron" logdir = "/var/log/cron" break = 1 Dudes firewalled by IPTrap: program = "iptrap" logdir = "/var/log/iptrap" break = 1 FTP Server: facility = "ftp" logdir = "/var/log/ftpd" break = 1 News Server: facility = "news" logdir = "/var/log/news" break = 1 SSH Server: program = "sshd" logdir = "/var/log/sshd" break = 1 # why the hell do you still run that thing !? Telnet: program = "login" logdir = "/var/log/telnet" break = 1 # log output from program "imapd" Imap: program = "/usr/sbin/imapd" logdir = "/var/log/imap" break = 1 Mail: facility = "mail" neg_regex= "starting daemon" logdir = "/var/log/mail" break = 1 Imap: program = "/usr/sbin/imapd" logdir = "/var/log/imap" break = 1 # log output from every program whose name begins with "postmaster" or "postgres". Postgresql: program_regex = "^postmaster" program_regex = "^postgres" logdir = "/var/log/postgres" break = 1 Apache: program_regex = "^httpd" logdir = "/var/log/http" break = 1 # log output from an UDS that later can get bind mounted within an LXC container at /dev/log LXC container "SDK": socket = /var/spool/metalog_sockets/sdk.socket logdir = /var/log/sdk break = 1 # log everything else in misc Misc: logdir = /var/log/misc hvisage-metalog-8e511b7/metalog.lsm.in000066400000000000000000000015401512715635700177120ustar00rootroot00000000000000Begin4 Title: metalog Version: @VERSION@ Entered-date: 9 Jul 2001 Description: Metalog is a modern replacement for syslogd and klogd. The logged messages can be dispatched according to their facility, urgency, program name and/or Perl-compatible regular expressions. Log files can be automatically rotated when they exceed a certain size or age. External shell scripts (e.g., mail) can be launched when specific patterns are found. Metalog is simple to configure, accepts unlimited number of rules and has (switchable) memory bufferization for maximal performance. Keywords: syslog,syslogd,logger Author: j@pureftpd.org (Frank DENIS) Maintained-by: j@pureftpd.org (Frank DENIS) Primary-site: ftp://ftp.fr.pureftpd.org/metalog/ Alternate-site: Original-site: http://metalog.sourceforge.net/ Platforms: Linux,FreeBSD,NetBSD,OpenBSD,MicroBSD Copying-policy: GPL End hvisage-metalog-8e511b7/metalog.spec.in000066400000000000000000000053561512715635700200620ustar00rootroot00000000000000%define name metalog %define version @VERSION@ %define release 1 %define builddir $RPM_BUILD_DIR/%{name}-%{version} %define no_install_post_compress_docs 1 #dont change these. Use --define instead. See below. %define prefixdef /usr/local %define sysconfdef /etc #If you don't like the prefix '/usr/local' you can override it like this: #rpm -ba|--rebuild --define 'prefix /usr' %{?!prefix:%define prefix %{prefixdef}} #If you don't like the sysconfdir '/etc' you can override it like this: #rpm -ba|--rebuild --define 'sysconfdir /usr/local/etc' %{?!sysconfdir:%define sysconfdir %{sysconfdef}} Name: %{name} Version: %{version} Release: %{release} Vendor: Generic Packager: Frank DENIS URL: http://metalog.sourceforge.net/ Source: ftp://ftp.fr.pureftpd.org/metalog/%{name}-%{version}.tar.gz Group: System/Logging Copyright: GPL Provides: syslog-daemon BuildRoot: %{_tmppath}/%{name}-%{version} Summary: An efficient alternative to syslogd Obsoletes: syslogd klogd %description Metalog is a modern replacement for syslogd and klogd. The logged messages can be dispatched according to their facility, urgency, program name and/or Perl-compatible regular expressions. Log files can be automatically rotated when they exceed a certain size or age. External shell scripts (e.g., mail) can be launched when specific patterns are found. Metalog is easier to configure than syslogd and accepts an unlimited number of rules and it has (switchable) memory bufferization for maximal performance. %prep %setup -n %{name}-%{version} %build CFLAGS="$RPM_OPT_FLAGS" ./configure --prefix=%{prefix} \ --mandir=%{_mandir} --sysconfdir=%{sysconfdir} if [ "$SMP" != "" ]; then (make "MAKE=make -k -j $SMP"; exit 0) make else make fi %install [ -n "$RPM_BUILD_ROOT" -a "$RPM_BUILD_ROOT" != / ] && rm -rf "$RPM_BUILD_ROOT" make DESTDIR="$RPM_BUILD_ROOT" install-strip if [ ! -d $RPM_BUILD_ROOT%{prefix}/sbin ]; then mkdir -p $RPM_BUILD_ROOT%{prefix}/sbin fi if [ ! -d $RPM_BUILD_ROOT%{sysconfdir} ]; then mkdir -p $RPM_BUILD_ROOT%{sysconfdir} fi if [ ! -d $RPM_BUILD_ROOT%{_mandir}/man8 ]; then mkdir -p $RPM_BUILD_ROOT%{_mandir}/man8 fi gzip --best $RPM_BUILD_ROOT/%{_mandir}/man8/*.8 install -m 644 metalog.conf $RPM_BUILD_ROOT%{sysconfdir}/ %clean [ -n "$RPM_BUILD_ROOT" -a "$RPM_BUILD_ROOT" != / ] && rm -rf "$RPM_BUILD_ROOT" %files %defattr(0755, root, root) %{prefix}/sbin/* %defattr(0644, root, root) %{_mandir}/man8/* %defattr(-, root, root) %doc README AUTHORS NEWS %config(noreplace) %{sysconfdir}/*.conf %changelog * Mon Jul 9 2001 Frank DENIS - First RPM build of this package. * Sun Apr 6 2003 Frank DENIS - Cleanups hvisage-metalog-8e511b7/src/000077500000000000000000000000001512715635700157275ustar00rootroot00000000000000hvisage-metalog-8e511b7/src/Makefile.am000066400000000000000000000003111512715635700177560ustar00rootroot00000000000000AM_CFLAGS = $(WFLAGS) sbin_PROGRAMS = \ metalog AM_CPPFLAGS = \ -DCONFDIR=\"$(sysconfdir)\" metalog_SOURCES = \ helpers.h \ metalog.c \ metalog.h \ metalog_p.h syslognames.h metalog_LDADD = hvisage-metalog-8e511b7/src/helpers.h000066400000000000000000000032671512715635700175520ustar00rootroot00000000000000#ifndef __HELPERS_H__ #define __HELPERS_H__ 1 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof(arr[0])) #define warn(fmt, args...) \ fprintf(stderr, "%s: " fmt "\n", "metalog" , ## args) #define warnf(fmt, args...) warn("%s():%i: " fmt, __func__, __LINE__ , ## args) #define warnp(fmt, args...) warn(fmt ": %s" , ## args , strerror(errno)) #define _err(wfunc, fmt, args...) \ do { \ wfunc("error: " fmt, ## args); \ exit(EXIT_FAILURE); \ } while (0) #define err(fmt, args...) _err(warn, fmt, ## args) #define errf(fmt, args...) _err(warnf, fmt, ## args) #define errp(fmt, args...) _err(warnp, fmt , ## args) static pcre2_code *wpcre2_compile(const char *pattern, uint32_t options) { int errcode; PCRE2_SIZE erroffset; pcre2_code *ret = pcre2_compile((PCRE2_SPTR)pattern, PCRE2_ZERO_TERMINATED, options, &errcode, &erroffset, NULL); if (!ret) { PCRE2_UCHAR buffer[256]; pcre2_get_error_message(errcode, buffer, sizeof(buffer)); warn("Invalid regex [%s] at %zu: %s", pattern, erroffset, buffer); } return ret; } static void *wmalloc(size_t size) { void *ret = malloc(size); if (!ret) { warnp("malloc(%zu) failed", size); } return ret; } static void *wrealloc(void *ptr, size_t size) { void *ret = realloc(ptr, size); if (!ret) { warnp("realloc(%p, %zu) failed", ptr, size); } return ret; } static char *wstrdup(const char *s) { char *ret = strdup(s); if (!ret) { warnp("strdup(\"%s\") failed", s); } return ret; } static char *xstrdup(const char *s) { char *ret = strdup(s); if (!ret) { errp("strdup(\"%s\") failed", s); } return ret; } #endif hvisage-metalog-8e511b7/src/metalog.c000066400000000000000000002460011512715635700175260ustar00rootroot00000000000000#include #define SYSLOG_NAMES 1 #include "metalog.h" #include "metalog_p.h" #ifdef WITH_DMALLOC # include #endif static int spawn_recursion = 0; static int dolog_queue[2]; static bool keep_running = true; static pcre2_code *re_compressed; static pcre2_match_data *pcre_matches; static void signal_doLog_dequeue(void); static void add_remote_host(RemoteHost **hosts, const char *name, const char *hostname, const char *port, LogFormat format, int severity_level); static char *extract_remote_host_name(const char * const keyword, const char *pattern); static int update_remote_host_field(char **field, const char *value); static RemoteHost *find_remote_host(RemoteHost **hosts, const char *name); static RemoteHost* find_or_add_remote_host(const char *name, const char *hostname, const char *port, int format, int severity_level); static void free_remote_hosts(RemoteHost *remote_hosts_head); static const char* get_stamp_fmt_for_rfc_format(LogFormat format); static bool isRemoteHostInConfigBlock(RemoteHost **hosts_list, int num_hosts, RemoteHost *host); static const char* build_priority_str(const int severity); static char* build_log_line(const char * const prg, const char * const pid, const char * const info, LogFormat format, const char * const datebuf, const int priority, const int facility, bool print_hostname, bool log_severity); static void get_hostname(char *hostname, size_t size, bool print_hostname); static char* handle_rfc3164_format(int pri, const char *datebuf_safe, char *hostname, const char *prg_safe, const char *pid_safe, const char *info, bool print_hostname); static char* handle_rfc5424_format(int pri, const char *datebuf_safe, char *hostname, const char *prg_safe, const char *pid_safe, const char *info, bool print_hostname); static char* format_log_line(const char *format, ...); static char* allocate_log_line(size_t size); static LogFormat translate_log_format(const char * const format); static int doLog(const char * fmt, ...); static DataSource *add_data_source(LogLineType type, const char *path, bool required) { DataSource *s; /* Find and return duplicate source */ for (s = data_sources; s; s = s->next_source) { if (type == s->type && ((path == NULL && s->path == NULL) || (path != NULL && s->path != NULL && strcmp(path, s->path) == 0))) { return s; } } /* Create new source */ if ((s = wmalloc(sizeof *s)) == NULL || (path && (s->path = wstrdup(path)) == NULL)) { return NULL; } s->type = type; s->required = required; s->fd = -1; /* Link new source into list */ s->next_source = data_sources; return data_sources = s; } static void free_data_sources(DataSource **data_sources_head) { while (*data_sources_head) { DataSource *node = *data_sources_head; *data_sources_head = node->next_source; free(node->path); free(node); } } /* Return values: * 0 - success * -3 - memory failure * <-3 - parse error on specific lines * * Caller only cares about success; the rest are for developers while debugging */ static int parseLine(char * const line, ConfigBlock **cur_block, const ConfigBlock * const default_block, pcre2_code * const re_newblock, pcre2_code * const re_newstmt, pcre2_code * const re_comment, pcre2_code * const re_null) { pcre2_match_data *match_data = pcre2_match_data_create(16, NULL); pcre2_code *new_regex; char *keyword; char *value; int line_size; int stcount; int ret = 0; if ((line_size = (int) strlen(line)) <= 0) { ret = 0; goto free_match_data; } if (line[line_size - 1] == '\n') { if (line_size < 2) { ret = 0; goto free_match_data; } line[--line_size] = 0; } if (pcre2_match(re_null, (PCRE2_SPTR)line, (PCRE2_SIZE)line_size, 0, 0, match_data, NULL) >= 0 || pcre2_match(re_comment, (PCRE2_SPTR)line, (PCRE2_SIZE)line_size, 0, 0, match_data, NULL) >= 0) { ret = 0; goto free_match_data; } if (pcre2_match(re_newblock, (PCRE2_SPTR)line, (PCRE2_SIZE)line_size, 0, 0, match_data, NULL) >= 0) { ConfigBlock *previous_block = *cur_block; if ((*cur_block = wmalloc(sizeof **cur_block)) == NULL) { ret = -3; goto free_match_data; } **cur_block = *default_block; if (config_blocks == NULL) { config_blocks = *cur_block; } else { previous_block->next_block = *cur_block; } /* create an independent copy of the hosts array */ if (default_block->hosts != NULL) { (*cur_block)->hosts = wmalloc(default_block->num_hosts * sizeof(RemoteHost *)); if ((*cur_block)->hosts == NULL) { ret = -3; goto free_match_data; } memcpy((*cur_block)->hosts, default_block->hosts, default_block->num_hosts * sizeof(RemoteHost *)); (*cur_block)->num_hosts = default_block->num_hosts; } else { (*cur_block)->hosts = NULL; (*cur_block)->num_hosts = 0; } ret = 0; goto free_match_data; } if ((stcount = pcre2_match(re_newstmt, (PCRE2_SPTR)line, (PCRE2_SIZE)line_size, 0, 0, match_data, NULL)) >= 3) { PCRE2_SIZE len; pcre2_substring_get_bynumber(match_data, 1, (PCRE2_UCHAR **)&keyword, &len); pcre2_substring_get_bynumber(match_data, 2, (PCRE2_UCHAR **)&value, &len); if (strcasecmp(keyword, "minimum") == 0) { (*cur_block)->minimum = atoi(value); } else if (strcasecmp(keyword, "maximum") == 0) { (*cur_block)->maximum = atoi(value); } else if (strcasecmp(keyword, "facility") == 0) { int n = 0; if (*value == '*' && value[1] == 0) { if ((*cur_block)->facilities != NULL) { free((*cur_block)->facilities); } (*cur_block)->facilities = NULL; (*cur_block)->nb_facilities = 0; ret = 0; goto free_substring; } while (facilitynames[n].c_name != NULL && strcasecmp(facilitynames[n].c_name, value) != 0) { n++; } if (facilitynames[n].c_name == NULL) { warn("Unknown facility : [%s]", value); ret = -4; goto free_substring; } (*cur_block)->facilities = wrealloc((*cur_block)->facilities, ((*cur_block)->nb_facilities + 1) * sizeof(*(*cur_block)->facilities)); if ((*cur_block)->facilities == NULL) { ret = -3; goto free_substring; } (*cur_block)->facilities[(*cur_block)->nb_facilities] = LOG_FAC(facilitynames[n].c_val); (*cur_block)->nb_facilities++; } else if (strcasecmp(keyword, "regex") == 0 || strcasecmp(keyword, "neg_regex") == 0) { char *regex; RegexWithSign *new_regexeswithsign; if ((regex = wstrdup(value)) == NULL) { ret = -3; goto free_substring; } if ((new_regexeswithsign = wrealloc((*cur_block)->regexeswithsign, ((*cur_block)->nb_regexes + 1) * sizeof *((*cur_block)->regexeswithsign))) == NULL) { free(regex); ret = -3; goto free_substring; } (*cur_block)->regexeswithsign = new_regexeswithsign; if ((new_regex = wpcre2_compile(regex, PCRE2_CASELESS)) == NULL) { free(regex); ret = -5; goto free_substring; } else { RegexWithSign * const this_regex = &((*cur_block)->regexeswithsign[(*cur_block)->nb_regexes]); free(regex); if (strcasecmp(keyword, "neg_regex") == 0) { this_regex->sign = REGEX_SIGN_NEGATIVE; } else { this_regex->sign = REGEX_SIGN_POSITIVE; } this_regex->regex = new_regex; } (*cur_block)->nb_regexes++; } else if (strcasecmp(keyword, "program_regex") == 0 || strcasecmp(keyword, "program_neg_regex") == 0) { char *regex; RegexWithSign *new_regexeswithsign; if ((regex = wstrdup(value)) == NULL) { ret = -3; goto free_substring; } if ((new_regexeswithsign = wrealloc((*cur_block)->program_regexeswithsign, ((*cur_block)->program_nb_regexes + 1) * sizeof *((*cur_block)->program_regexeswithsign))) == NULL) { free(regex); ret = -3; goto free_substring; } (*cur_block)->program_regexeswithsign = new_regexeswithsign; if ((new_regex = wpcre2_compile(regex, PCRE2_CASELESS)) == NULL) { free(regex); ret = -5; goto free_substring; } else { free(regex); RegexWithSign * const this_regex = &((*cur_block)->program_regexeswithsign [(*cur_block)->program_nb_regexes]); if (strcasecmp(keyword, "program_neg_regex") == 0) { this_regex->sign = REGEX_SIGN_NEGATIVE; } else { this_regex->sign = REGEX_SIGN_POSITIVE; } this_regex->regex = new_regex; } (*cur_block)->program_nb_regexes++; } else if (strcasecmp(keyword, "maxsize") == 0) { (*cur_block)->maxsize = (off_t) strtoull(value, NULL, 0); if ((*cur_block)->output != NULL) { (*cur_block)->output->maxsize = (*cur_block)->maxsize; } } else if (strcasecmp(keyword, "maxfiles") == 0) { (*cur_block)->maxfiles = atoi(value); if ((*cur_block)->output != NULL) { (*cur_block)->output->maxfiles = (*cur_block)->maxfiles; } } else if (strcasecmp(keyword, "maxtime") == 0) { (*cur_block)->maxtime = (time_t) strtoull(value, NULL, 0); if ((*cur_block)->output != NULL) { (*cur_block)->output->maxtime = (*cur_block)->maxtime; } } else if (strcasecmp(keyword, "showrepeats") == 0) { (*cur_block)->showrepeats = atoi(value); if ((*cur_block)->output != NULL) { (*cur_block)->output->showrepeats = (*cur_block)->showrepeats; } } else if (strcasecmp(keyword, "perms") == 0) { (*cur_block)->perms = (mode_t) strtoul(value, NULL, 8); if ((*cur_block)->output != NULL) { (*cur_block)->output->perms = (*cur_block)->perms; } } else if (strcasecmp(keyword, "configdir") == 0) { /* allow only once to avoid recursion */ if (config_dir != NULL) { warnp("Ignore repeated \"configdir\" statement"); } else { if ((config_dir = wstrdup(value)) == NULL) { ret = -3; goto free_substring; } } } else if (strcasecmp(keyword, "logdir") == 0) { char *logdir = NULL; Output *outputs_scan = outputs; Output *previous_scan = NULL; Output *new_output; while (outputs_scan != NULL) { if (outputs_scan->directory != NULL && strcmp(outputs_scan->directory, value) == 0) { (*cur_block)->output = outputs_scan; goto duplicate_output; } previous_scan = outputs_scan; outputs_scan = outputs_scan->next_output; } if ((new_output = wmalloc(sizeof *new_output)) == NULL || (logdir = wstrdup(value)) == NULL) { free(new_output); free(logdir); ret = -3; goto free_substring; } if (strcasecmp(value, "NONE") != 0) { new_output->directory = logdir; } else { free(logdir); new_output->directory = NULL; } new_output->fp = NULL; new_output->perms = (*cur_block)->perms; new_output->size = (off_t) 0; new_output->maxsize = (*cur_block)->maxsize; new_output->maxfiles = (*cur_block)->maxfiles; new_output->maxtime = (*cur_block)->maxtime; new_output->postrotate_cmd = (*cur_block)->postrotate_cmd; new_output->showrepeats = (*cur_block)->showrepeats; new_output->stamp_fmt = (*cur_block)->stamp_fmt; new_output->flush = (*cur_block)->flush; new_output->compress = (*cur_block)->compress; new_output->compress_delay = (*cur_block)->compress_delay; new_output->dt.previous_prg = NULL; new_output->dt.previous_info = NULL; new_output->dt.sizeof_previous_prg = (size_t) 0U; new_output->dt.sizeof_previous_info = (size_t) 0U; new_output->dt.previous_sizeof_prg = (size_t) 0U; new_output->dt.previous_sizeof_info = (size_t) 0U; new_output->dt.same_counter = 0U; new_output->rate.usec_between_msgs = (*cur_block)->usec_between_msgs; new_output->rate.bucket_size = (*cur_block)->burst_length; new_output->rate.token_bucket = (*cur_block)->burst_length; new_output->rate.last_tick = 0; new_output->next_output = NULL; if (previous_scan != NULL) { previous_scan->next_output = new_output; } else { outputs = new_output; } (*cur_block)->output = new_output; duplicate_output: (void) 0; } else if (strcasecmp(keyword, "command") == 0) { char *command = NULL; struct stat st; char *p = NULL; if ((command = wstrdup(value)) == NULL) { ret = -3; goto free_substring; } p = strchr(command, (int) ' '); if (p != NULL) { *p = '\0'; } if (stat(command, &st) < 0) { warnp("Ignoring command \"%s\"", command); free(command); ret = 0; goto free_substring; } free(command); if (((*cur_block)->command = wstrdup(value)) == NULL) { ret = -3; goto free_substring; } } else if (strcasecmp(keyword, "program") == 0) { if (((*cur_block)->program = wstrdup(value)) == NULL) { ret = -3; goto free_substring; } } else if (strcasecmp(keyword, "postrotate_cmd") == 0) { if (((*cur_block)->postrotate_cmd = wstrdup(value)) == NULL) { ret = -3; goto free_substring; } if ((*cur_block)->output != NULL) { (*cur_block)->output->postrotate_cmd = (*cur_block)->postrotate_cmd; } } else if (strncmp(keyword, "remote_host", strlen("remote_host")) == 0) { char *name = extract_remote_host_name(keyword, "remote_host"); RemoteHost *current_remote_host = find_or_add_remote_host(name, value, DEFAULT_UPD_PORT, LEGACY, LOG_DEBUG); free(name); if (current_remote_host != NULL) { if (update_remote_host_field(¤t_remote_host->hostname, value) != 0) { ret = -3; goto free_substring; } } } else if (strncmp(keyword, "remote_port", strlen("remote_port")) == 0) { char *name = extract_remote_host_name(keyword, "remote_port"); RemoteHost *current_remote_host = find_remote_host(&remote_hosts, name); free(name); if (current_remote_host != NULL) { if (update_remote_host_field(¤t_remote_host->port, value) != 0) { ret = -3; goto free_substring; } } } else if (strncmp(keyword, "remote_format", strlen("remote_format")) == 0) { char *name = extract_remote_host_name(keyword, "remote_format"); RemoteHost *current_remote_host = find_remote_host(&remote_hosts, name); free(name); if (current_remote_host != NULL) { current_remote_host->format = translate_log_format(value); } } else if (strncmp(keyword, "remote_severity_level", strlen("remote_severity_level")) == 0) { char *name = extract_remote_host_name(keyword, "remote_severity_level"); RemoteHost *current_remote_host = find_remote_host(&remote_hosts, name); free(name); if (current_remote_host != NULL) { current_remote_host->severity_level = atoi(value); } } else if (strncmp(keyword, "remote_log", strlen("remote_log")) == 0) { int value_int = atoi(value); char *name = extract_remote_host_name(keyword, "remote_log"); RemoteHost *current_remote_host = find_remote_host(&remote_hosts, name); free(name); if (current_remote_host != NULL) { if (value_int == 1) { RemoteHost **temp = wrealloc((*cur_block)->hosts, ((*cur_block)->num_hosts + 1) * sizeof(RemoteHost *)); if (temp == NULL) { warn("failed to realloc memory for remote hosts"); free((*cur_block)->hosts); (*cur_block)->hosts = NULL; ret = -3; goto free_substring; } (*cur_block)->hosts = temp; (*cur_block)->num_hosts++; (*cur_block)->hosts[(*cur_block)->num_hosts - 1] = current_remote_host; } else if (value_int == 0) { /* remove the RemoteHost from the ConfigBlock if already added in default values */ int found = 0; for (int i = 0; i < (*cur_block)->num_hosts; i++) { if ((*cur_block)->hosts[i] == current_remote_host) { found = 1; for (int j = i; j < (*cur_block)->num_hosts - 1; j++) { (*cur_block)->hosts[j] = (*cur_block)->hosts[j + 1]; } (*cur_block)->num_hosts--; break; } } if (found) { RemoteHost **temp = wrealloc((*cur_block)->hosts, (*cur_block)->num_hosts * sizeof(RemoteHost *)); if (temp == NULL && (*cur_block)->num_hosts > 0) { warn("failed to realloc memory for remote hosts"); free((*cur_block)->hosts); (*cur_block)->hosts = NULL; ret = -3; goto free_substring; } (*cur_block)->hosts = temp; } } } } else if (strcasecmp(keyword, "break") == 0) { (*cur_block)->brk = atoi(value); } else if (strcasecmp(keyword, "stamp_fmt") == 0) { if (((*cur_block)->stamp_fmt = wstrdup(value)) == NULL) { ret = -3; goto free_substring; } if ((*cur_block)->output != NULL) { (*cur_block)->output->stamp_fmt = (*cur_block)->stamp_fmt; } } else if (strcasecmp(keyword, "flush") == 0) { if (atoi(value)) { (*cur_block)->flush = FLUSH_ALWAYS; } else { (*cur_block)->flush = FLUSH_NEVER; } if ((*cur_block)->output != NULL) { (*cur_block)->output->flush = (*cur_block)->flush; } } else if (strcasecmp(keyword, "ratelimit") == 0) { double base_rate; int64_t usec_between_msgs; char *end; base_rate = strtod(value, &end); if (end == value) { warnp("Missing number : [%s]", value); ret = -6; goto free_substring; } if (base_rate < 0.) { warn("Negative number : [%s]", value); ret = -6; goto free_substring; } if (base_rate) { double usec; if (end[0] != '/') { warn("Missing unit of time : [%s]", value); ret = -6; goto free_substring; } switch (end[1]) { case 's': usec = 1000000.; break; case 'm': usec = 1000000. * 60; break; case 'h': usec = 1000000. * 60 * 60; break; case 'd': usec = 1000000. * 60 * 60 * 24; break; default: warn("Invalid unit of time : [%s]", end + 1); ret = -6; goto free_substring; } usec_between_msgs = usec / base_rate; } else { usec_between_msgs = base_rate; } assert(usec_between_msgs >= 0); (*cur_block)->usec_between_msgs = usec_between_msgs; if ((*cur_block)->output != NULL) { (*cur_block)->output->rate.usec_between_msgs = usec_between_msgs; } } else if (strcasecmp(keyword, "ratelimit_burst") == 0) { int burst_length = atoi(value); if (burst_length < 1) { warn("Non-positive bust length : [%s]", value); ret = -6; goto free_substring; } (*cur_block)->burst_length = burst_length; if ((*cur_block)->output != NULL) { (*cur_block)->output->rate.bucket_size = burst_length; (*cur_block)->output->rate.token_bucket = burst_length; } } else if (strcasecmp(keyword, "log_format") == 0) { (*cur_block)->log_format = translate_log_format(value); } else if (strcasecmp(keyword, "log_severity") == 0) { if (atoi(value)) { (*cur_block)->log_severity = true; } else { (*cur_block)->log_severity = false; } } else if (strcasecmp(keyword, "socket") == 0) { (*cur_block)->source = add_data_source(LOGLINETYPE_SYSLOG, value, false); } else if (strcasecmp(keyword, "compress") == 0) { (*cur_block)->compress = atoi(value) == 1 ? true : false; #ifndef WITH_COMPRESS if ((*cur_block)->compress) { warn("Log compression configuration ignored as support not compiled in"); } #endif if ((*cur_block)->output != NULL) { (*cur_block)->output->compress = (*cur_block)->compress; } } else if (strcasecmp(keyword, "compress_delay") == 0) { (*cur_block)->compress_delay = atoi(value); if ((*cur_block)->output != NULL) { (*cur_block)->output->compress_delay = (*cur_block)->compress_delay; } } else { err("Unknown keyword '%s'! line: %s", keyword, line); } free_substring: pcre2_substring_free((PCRE2_UCHAR *)keyword); pcre2_substring_free((PCRE2_UCHAR *)value); } free_match_data: pcre2_match_data_free(match_data); return ret; } /* config file names must end with ".conf" */ static int conffile_filter(const struct dirent *ep) { char *p = strchr(ep->d_name, (int) '.'); return (p != NULL && strstr(p, ".conf") != NULL); } static int configParser(const char * const file) { char line[LINE_MAX]; FILE *fp = NULL; pcre2_code *re_newblock; pcre2_code *re_newstmt; pcre2_code *re_comment; pcre2_code *re_null; int retcode = 0; ConfigBlock default_block = { DEFAULT_MINIMUM, /* minimum */ DEFAULT_MAXIMUM, /* maximum */ NULL, /* facilities */ 0, /* nb_facilities */ NULL, /* regexes */ 0, /* nb_regexes */ (off_t) DEFAULT_MAXSIZE, /* maxsize */ DEFAULT_MAXFILES, /* maxfiles */ (time_t) DEFAULT_MAXTIME, /* maxtime */ (mode_t) DEFAULT_PERMS, /* perms */ NULL, /* output */ NULL, /* command */ NULL, /* program */ 0, /* break flag */ NULL, /* program_regexes */ 0, /* program_nb_regexes */ NULL, /* next_block */ NULL, /* postrotate_cmd */ 0, /* showrepeats */ DEFAULT_STAMP_FMT, /* stamp_fmt */ FLUSH_DEFAULT, /* flush */ 0, /* usec_between_msgs */ 1, /* max_burst_length */ NULL, /* list of remote hosts */ 0, /* number of remote hosts */ DEFAULT_LOG_FORMAT, /* log format */ false, /* severity level in legacy formats */ NULL, /* data source */ false, /* compress */ DEFAULT_COMPRESS_DELAY, /* compress delay */ }; ConfigBlock *cur_block = &default_block; if ((fp = fopen(file, "r")) == NULL) { warnp("Can't open the configuration file"); return -2; } re_newblock = wpcre2_compile(":\\s*$", 0); re_newstmt = wpcre2_compile("^\\s*(.+?)\\s*=\\s*\"?([^\"]*)\"?\\s*$", 0); re_comment = wpcre2_compile("^\\s*#", 0); re_null = wpcre2_compile("^\\s*$", 0); if (!re_newblock || !re_newstmt || !re_comment || !re_null) { retcode = -1; goto rtn; } while (fgets(line, sizeof line, fp) != NULL) { if ((retcode = parseLine(line, &cur_block, &default_block, re_newblock, re_newstmt, re_comment, re_null)) != 0) { break; } } /* read all config files of an eventually configured directory */ if (retcode == 0 && config_dir != NULL) { struct dirent **dp; int count; int i; count = scandir(config_dir, &dp, conffile_filter, alphasort); if (count == -1) { warnp("Can't scan the config dir %s", config_dir); retcode = -1; goto rtn; } for (i = 0; i < count; i++) { struct dirent *ep = dp[i]; FILE *fp2 = NULL; char *file_path = NULL; if ((file_path = wmalloc(strlen(ep->d_name) + strlen(config_dir) + 2)) == NULL) { retcode = -1; goto rtn; } sprintf(file_path, "%s/%s", config_dir, ep->d_name); if ((fp2 = fopen(file_path, "r")) == NULL) { warnp("Can't open the config file %s", file_path); retcode = -1; free(file_path); goto rtn; } while (fgets(line, sizeof line, fp2) != NULL) { if ((retcode = parseLine(line, &cur_block, &default_block, re_newblock, re_newstmt, re_comment, re_null)) != 0) { break; } } free(file_path); fclose(fp2); } free(dp); } rtn: if (re_newblock != NULL) { pcre2_code_free(re_newblock); } if (re_newstmt != NULL) { pcre2_code_free(re_newstmt); } if (re_comment != NULL) { pcre2_code_free(re_comment); } if (re_null != NULL) { pcre2_code_free(re_null); } fclose(fp); return retcode; } static void clearargs(int argc, char **argv) { #ifndef NO_PROCNAME_CHANGE # if defined(__linux__) && !defined(HAVE_SETPROCTITLE) int i; for (i = 0; environ[i] != NULL; i++); argv0 = argv; if (i > 0) { argv_lth = environ[i-1] + strlen(environ[i-1]) - argv0[0]; } else { argv_lth = argv0[argc-1] + strlen(argv0[argc-1]) - argv0[0]; } if (environ != NULL) { char **new_environ; unsigned int env_nb = 0U; while (environ[env_nb] != NULL) { env_nb++; } if ((new_environ = malloc((1U + env_nb) * sizeof (char *))) == NULL) { abort(); } new_environ[env_nb] = NULL; while (env_nb > 0U) { env_nb--; /* Can any bad thing happen if strdup() ever fails? */ new_environ[env_nb] = xstrdup(environ[env_nb]); } environ = new_environ; } # else (void) argc; (void) argv; # endif #endif } #ifndef HAVE_SETPROGNAME static void setprogname(const char * const title) { #ifndef NO_PROCNAME_CHANGE # ifdef HAVE_SETPROCTITLE setproctitle("-%s", title); # elif defined(__linux__) if (argv0 != NULL) { memset(argv0[0], 0, argv_lth); strncpy(argv0[0], title, argv_lth - 2); argv0[1] = NULL; } # elif defined(__hpux__) union pstun pst; pst.pst_command = title; pstat(PSTAT_SETCMD, pst, strlen(title), 0, 0); # endif #endif (void) title; } #endif static int getKernelDataSource(DataSource *source) { #ifdef HAVE_KLOGCTL int fdpipe[2]; pid_t pgid; int loop = 1; #endif #ifdef HAVE_KLOGCTL /* larger buffers compared to a pipe() */ if (socketpair(AF_UNIX, SOCK_STREAM, 0, fdpipe) < 0) { warnp("Unable to create a pipe"); close(source->fd); return -3; } pgid = getpgrp(); if ((child = fork()) < (pid_t) 0) { warnp("Unable to create the klogd child"); close(source->fd); return -3; } else if (child == (pid_t) 0) { char line[LINE_MAX]; int s; signal(SIGUSR1, SIG_IGN); signal(SIGUSR2, SIG_IGN); setpgid((pid_t) 0, pgid); setprogname(PROGNAME_KERNEL); if (klogctl(1, NULL, 0) < 0 || klogctl(8, NULL, console_level) < 0 || klogctl(6, NULL, 0) < 0) { warnp("Unable to control the kernel logging device"); return -4; } while (loop) { while ((s = klogctl(2, line, sizeof (line))) < 0 && errno == EINTR) { continue; } if (s == -1) { loop = 0; break; } /* make sure we write the whole buffer into the pipe line parsing is done on the other end */ int out = 0; while (out < s) { int w = write(fdpipe[1], &line[out], s - out); if (w == -1 && errno != EINTR) { loop = 0; break; } out += w; } } klogctl(7, NULL, 0); klogctl(0, NULL, 0); return 0; } source->fd = fdpipe[0]; #else /* !HAVE_KLOGCTL */ { int klogfd; if ((klogfd = open(KLOG_FILE, O_RDONLY)) < 0) { return source->required ? -1 : 0; /* non-fatal? */ } source->fd = klogfd; } #endif source->semantics = SOCK_STREAM; return 0; } static int getSyslogDataSource(DataSource *source) { struct sockaddr_un sa; int fd; if ((fd = socket(PF_UNIX, source->semantics = SOCK_DGRAM, 0)) < 0) { warnp("Unable to create a local socket"); return -1; } sa.sun_family = AF_UNIX; if (snprintf(sa.sun_path, sizeof sa.sun_path, "%s", source->path) < 0) { warnp("Socket name too long"); close(fd); return -2; } unlink(sa.sun_path); if (bind(fd, (struct sockaddr *) &sa, (socklen_t) sizeof sa) < 0) { warnp("Unable to bind local socket: %s", source->path); close(fd); /* The earlier failures are fatal; binding failure could mean that * the parent directory is missing and this source is not applicable. */ return source->required ? -1 : 0; } chmod(sa.sun_path, 0666); source->fd = fd; return 0; } static int getDataSources(void) { DataSource *source; int ret = 0; int count = 0; /* setup the signal handler pipe */ if (socketpair(AF_LOCAL, SOCK_STREAM, 0, dolog_queue) < 0) { if (pipe(dolog_queue) < 0) { warnp("Unable to create a pipe"); return -4; } } for (source = data_sources; ret == 0 && source; source = source->next_source) { if (source->type == LOGLINETYPE_KLOG) { ret = getKernelDataSource(source); } else { ret = getSyslogDataSource(source); } count += (source->fd == -1) ? 0 : 1; } assert(ret <= 0); return ret == 0 ? count : ret; } static int spawnCommand(const char * const command, const char * const date, const char * const prg, const char * const info) { pid_t pid; if (spawn_recursion) { return 1; } spawn_recursion++; pid = fork(); if (pid == 0) { execl(command, command, date, prg, info, (char *) NULL); _exit(127); } if (verbose) doLog("Forked command \"%s \"%s\" \"%s\" \"%s\" [%u].", command, date, prg, info, (unsigned) pid); spawn_recursion--; return 0; } static int parseLogLine(const LogLineType loglinetype, char *line, int * const logcode, const char ** const prg, const char ** const pid, char ** const info) { #ifndef HAVE_KLOGCTL if (loglinetype != LOGLINETYPE_KLOG) { #endif if (*line != '<') { return -1; } line++; if ((*logcode = atoi(line)) <= 0) { return -1; } while (*line != '>') { if (*line == 0) { return -1; } line++; } line++; #ifndef HAVE_KLOGCTL } else { *logcode = 0; } #endif if (loglinetype == LOGLINETYPE_KLOG) { *logcode |= LOG_KERN; *prg = CF_PROGNAME_KERNEL; *pid = "0"; *info = line; return 0; } while (*line != ':') { if (*line == 0) { return -1; } line++; } line++; while (isspace(*line) == 0) { if (*line == 0) { return -1; } line++; } *line++ = 0; *prg = line; while (*line != '[' && *line != ':') { if (*line == 0) { return -1; } line++; } if (*line == '[') { *line++ = 0; *pid = line; while (*line != ']') { if (*line == 0) { return -1; } line++; } *line++ = 0; while (*line != ':') { if (*line == 0) { return -1; } line++; } } else { *line = 0; } line++; while (isspace(*line) != 0) { if (*line == 0) { return -1; } line++; } *info = line; return 0; } static bool is_compressed(const char *name) { return pcre2_match(re_compressed, (PCRE2_SPTR)name, PCRE2_ZERO_TERMINATED, 0, 0, pcre_matches, NULL) >= 0; } /* Identify details of rotated log. Returns true on success, * false if the filename is not in a conformant pattern */ static bool oldlog_identify(struct tm *stamp, const struct dirent *dirent) { char *s = strptime(dirent->d_name, OUTPUT_DIR_LOGFILES_PREFIX OUTPUT_DIR_LOGFILES_SUFFIX, stamp); return s && (*s == '\0' || is_compressed(s)); } int oldlog_filter(const struct dirent *a) { struct tm ta; return oldlog_identify(&ta, a); } int oldlog_sorter(const struct dirent **a, const struct dirent **b) { struct tm ta, tb; oldlog_identify(&ta, *a); oldlog_identify(&tb, *b); return timegm(&ta) - timegm(&tb); } #ifndef WITH_COMPRESS static void compressLogFile(int, const char *) { } #else static void compressLogFile(int dir_fd, const char *in_name) { int in_fd, out_fd; struct stat statbuf; char *in_buf; char *out_name; int sz = 0; gzFile gz; if ((in_fd = openat(dir_fd, in_name, O_RDONLY)) == -1) { return; } if (fstat(in_fd, &statbuf) == -1 || (in_buf = mmap(NULL, statbuf.st_size, PROT_READ, MAP_SHARED, in_fd, 0)) == MAP_FAILED) { goto fail1; } sz = asprintf(&out_name, "%s.gz", in_name); if (sz == -1) { goto fail2; } out_fd = openat(dir_fd, out_name, O_CREAT | O_RDWR | O_TRUNC, statbuf.st_mode); free(out_name); if (out_fd == -1) { goto fail2; } if ((gz = gzdopen(out_fd, "w")) == NULL) { close(out_fd); goto fail2; } sz = gzwrite(gz, in_buf, statbuf.st_size); if (gzclose(gz) == Z_OK && sz > 0) { unlinkat(dir_fd, in_name, 0); } else { sz = 0; } fail2: munmap(in_buf, statbuf.st_size); fail1: close(in_fd); if (sz <= 0) { warn("Unable to compress [%s]", in_name); } } #endif static int rotateLogFiles(const char * const directory, const int maxfiles, bool compress, int compress_delay) { struct dirent **dirent; int foundlogs; int ret = 0; int dirfd; int i; if ((dirfd = open(directory, O_DIRECTORY | O_RDONLY)) == -1) { warnp("Unable to rotate [%s]", directory); return -1; } foundlogs = scandir(directory, &dirent, oldlog_filter, oldlog_sorter); for (i = 0; i < foundlogs; i++) { if (i < foundlogs - maxfiles) { /* Delete excess logs */ if (unlinkat(dirfd, dirent[i]->d_name, 0) < 0) { ret = -2; } } else if (compress && i < foundlogs - compress_delay && !is_compressed(dirent[i]->d_name)) { /* Compress old logs; ignore failures */ compressLogFile(dirfd, dirent[i]->d_name); } } free(dirent); close(dirfd); return ret; } static int rateLimit(RateLimiter * const rl) { struct timeval tv; int64_t current_tick, diff_ticks; if (rl->usec_between_msgs == 0) { return 0; /* output channel is not limited */ } if (gettimeofday(&tv, NULL)) { return 0; /* if in doubt, never limit */ } /* Fill up bucket with one token every usec_between_msgs microseconds */ current_tick = tv.tv_sec * (int64_t)1000000 + tv.tv_usec; current_tick /= rl->usec_between_msgs; diff_ticks = current_tick - rl->last_tick; if (diff_ticks > 0) { diff_ticks += rl->token_bucket; if (diff_ticks < rl->bucket_size) { rl->token_bucket = (int)diff_ticks; } else { /* bucket overflow */ rl->token_bucket = rl->bucket_size; } } rl->last_tick = current_tick; /* Log message only if token available to pay for it */ if (rl->token_bucket <= 0) { return 1; /* suppress this message due to rate limit */ } --rl->token_bucket; return 0; /* message is within limit */ } static int writeLogLine(Output * const output, const char * const date, const char * const prg, const char * const pid, const char * const info, const int priority, const int facility, LogFormat log_format, const bool log_severity) { size_t sizeof_prg; size_t sizeof_info; time_t now; if (output == NULL || output->directory == NULL || (sizeof_prg = strlen(prg)) <= (size_t) 0U || (sizeof_info = strlen(info)) <= (size_t) 0U) { return 0; } if (sizeof_info > MAX_SIGNIFICANT_LENGTH) { sizeof_info = MAX_SIGNIFICANT_LENGTH; } if (sizeof_prg > MAX_SIGNIFICANT_LENGTH) { sizeof_prg = MAX_SIGNIFICANT_LENGTH; } if (rateLimit(&output->rate)) { return 0; } if (output->showrepeats == 0 && sizeof_info == output->dt.previous_sizeof_info && sizeof_prg == output->dt.previous_sizeof_prg && memcmp(output->dt.previous_info, info, sizeof_info) == 0 && memcmp(output->dt.previous_prg, prg, sizeof_prg) == 0) { if (output->dt.same_counter < UINT_MAX) { output->dt.same_counter++; } return 0; } if (sizeof_info > output->dt.sizeof_previous_info) { char *pp = output->dt.previous_info; if ((pp = wrealloc(output->dt.previous_info, sizeof_info)) != NULL) { output->dt.previous_info = pp; memcpy(output->dt.previous_info, info, sizeof_info); output->dt.sizeof_previous_info = sizeof_info; } } else { memcpy(output->dt.previous_info, info, sizeof_info); output->dt.previous_sizeof_info = sizeof_info; } if (sizeof_prg > output->dt.sizeof_previous_prg) { char *pp = output->dt.previous_prg; if ((pp = wrealloc(output->dt.previous_prg, sizeof_prg)) != NULL) { output->dt.previous_prg = pp; memcpy(output->dt.previous_prg, prg, sizeof_prg); output->dt.sizeof_previous_prg = sizeof_prg; } } else { memcpy(output->dt.previous_prg, prg, sizeof_prg); output->dt.previous_sizeof_prg = sizeof_prg; } now = time(NULL); if (output->fp == NULL) { struct stat st; FILE *fp; FILE *fp_ts; time_t creatime; char path[PATH_MAX]; testdir: if (stat(output->directory, &st) < 0) { if (mkdir(output->directory, output->perms) < 0) { warnp("Can't create [%s]", output->directory); return -1; } } else if (!S_ISDIR(st.st_mode)) { if (unlink(output->directory) < 0) { warnp("Can't unlink [%s]", output->directory); return -1; } goto testdir; } if (snprintf(path, sizeof path, "%s/" OUTPUT_DIR_CURRENT, output->directory) < 0) { warnp("Path name too long for current in [%s]", output->directory); return -2; } if ((fp = fopen(path, "a")) == NULL) { warnp("Unable to access [%s]", path); return -3; } if (snprintf(path, sizeof path, "%s/" OUTPUT_DIR_TIMESTAMP, output->directory) < 0) { warnp("Path name too long for timestamp in [%s]", output->directory); fclose(fp); return -2; } if ((fp_ts = fopen(path, "r")) == NULL) { recreate_ts: creatime = time(NULL); if ((fp_ts = fopen(path, "w")) == NULL) { warnp("Unable to write the timestamp [%s]", path); fclose(fp); return -3; } fprintf(fp_ts, "%llu\n", (unsigned long long) creatime); } else { unsigned long long creatime_; if (fscanf(fp_ts, "%llu", &creatime_) <= 0) { fclose(fp_ts); goto recreate_ts; } creatime = (time_t) creatime_; } if (fclose(fp_ts) != 0) { warnp("Unable to close [%s]", path); return -3; } output->creatime = creatime; if (output->maxtime) { output->creatime -= (creatime % output->maxtime); } output->size = (off_t) ftell(fp); output->fp = fp; } if ((output->maxsize != 0) && (output->maxtime != 0)) { if (output->size >= output->maxsize || now > (output->creatime + output->maxtime)) { struct tm *time_gm; char path[PATH_MAX]; char newpath[PATH_MAX]; if (output->fp == NULL) { warnf("Internal inconsistency"); return -6; } if ((time_gm = gmtime(&now)) == NULL) { warnp("Unable to find the current date"); return -4; } if (snprintf(newpath, sizeof newpath, "%s/" OUTPUT_DIR_LOGFILES_PREFIX, output->directory) < 0) { warnp("Path name too long for new path in [%s]", output->directory); return -2; } if (strftime(newpath + strlen(newpath), sizeof newpath - strlen(newpath), OUTPUT_DIR_LOGFILES_SUFFIX, time_gm) == 0) { warnp("Path name too long for new path in [%s]", output->directory); return -2; } if (snprintf(path, sizeof path, "%s/" OUTPUT_DIR_CURRENT, output->directory) < 0) { warnp("Path name too long for current in [%s]", output->directory); return -2; } fclose(output->fp); output->fp = NULL; if (rename(path, newpath) < 0 && unlink(path) < 0) { warnp("Unable to rename [%s] to [%s]", path, newpath); return -5; } if (output->postrotate_cmd != NULL) { spawnCommand(output->postrotate_cmd, date, prg, newpath); } rotateLogFiles(output->directory, output->maxfiles, output->compress, output->compress_delay); if (snprintf(path, sizeof path, "%s/" OUTPUT_DIR_TIMESTAMP, output->directory) < 0) { warnp("Path name too long for timestamp in [%s]", output->directory); return -2; } unlink(path); goto testdir; } } if (output->dt.same_counter > 0U) { if (output->dt.same_counter == 1) { fprintf(output->fp, LAST_OUTPUT_TWICE); output->size += (off_t) (sizeof LAST_OUTPUT_TWICE - (size_t) 1U); } else { int fps; fps = fprintf(output->fp, LAST_OUTPUT, output->dt.same_counter); if (fps >= (int) (sizeof LAST_OUTPUT - sizeof "%u")) { output->size += (off_t) fps; } else if (fps > 0) { output->size += (off_t) (sizeof LAST_OUTPUT + (size_t) 10U); } } output->dt.same_counter = 0U; } char *line = build_log_line(prg, pid, info, log_format, date, priority, facility, false, log_severity); fprintf(output->fp, "%s", line); output->size += (off_t) strlen(line); output->size += (off_t) 5; if (output->flush == FLUSH_ALWAYS || (output->flush == FLUSH_DEFAULT && synchronous != (sig_atomic_t) 0)) { fflush(output->fp); } free(line); return 0; } /* send a line to a remote syslog server */ static int sendRemote(const char * const prg, const char * const pid, const char * const info, RemoteHost *host, const char * const datebuf, const int priority, const int facility, bool log_severity) { struct timespec now; struct addrinfo hints; struct addrinfo *rp; char *line = NULL; int ret = 0; /* prepare log entry */ line = build_log_line(prg, pid, info, host->format, datebuf, priority, facility, true, log_severity); if (line == NULL) { return -1; } /* everything seems to be ready to send to remote host immediatelly */ clock_gettime(CLOCK_MONOTONIC, &now); if ((host->sock > 0) && ((host->last_dns.tv_sec + DEFAULT_DNS_LOOKUP_INTERVERVAL) > now.tv_sec)) { if (sendto(host->sock, line, strlen(line), 0, host->result->ai_addr, host->result->ai_addrlen) == -1) { close(host->sock); host->sock = -1; } else { free(line); return 0; } } /* sending failed or DNS info is too old, try again after updated DNS */ clock_gettime(CLOCK_MONOTONIC, &host->last_dns); memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_UNSPEC; hints.ai_flags = AI_ADDRCONFIG | AI_CANONNAME; hints.ai_socktype = SOCK_DGRAM; if (host->result != NULL) { freeaddrinfo(host->result); host->result = NULL; } if (getaddrinfo(host->hostname, host->port, &hints, &host->result) != 0) { free(line); return -1; } /* close an eventually open socket */ if (host->sock > 0) close(host->sock); /* establish the socket to the remote host using all its resolved addresses */ for (rp = host->result; rp != NULL; rp = rp->ai_next) { if (host->sock <= 0) { host->sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); } if (host->sock < 0) { continue; } if (connect(host->sock, rp->ai_addr, rp->ai_addrlen) == -1) { close(host->sock); host->sock = -1; continue; } /* try to send the line */ if (sendto(host->sock, line, strlen(line), 0, rp->ai_addr, rp->ai_addrlen) == -1) { close(host->sock); host->sock = -1; continue; } else { break; } } free(line); if(!rp) { ret = -1; } return ret; } static void flushAll(void) { ConfigBlock *block = config_blocks; while (block) { if (block->output && block->output->fp) { fflush_unlocked(block->output->fp); } block = block->next_block; } } static int get_stamp_fmt_timestamp(const char *stamp_fmt, char *datebuf, int datebuf_size) { struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); struct tm *tm = localtime(&ts.tv_sec); if ((!stamp_fmt) || (!datebuf) || datebuf_size < 1) { return -1; } if (tm) { /* make a copy as we may change the string */ char *fmt_str = strdup(stamp_fmt); /* Search for and process "%N" */ char *p = fmt_str; while ((p = strchr(p, '%')) != NULL) { char *tmp = NULL; int n, m; unsigned scale; unsigned long precision; p++; if (*p == '%') { p++; continue; } n = strspn(p, "0123456789"); if (p[n] != 'N') { p += n; continue; } /* We have "%[nnn]N" */ p[-1] = '\0'; p[n] = '\0'; scale = 1; precision = 9; if (n) { int old_errno = errno; char *e = NULL; errno = 0; precision = strtoul(p, &e, 10); if (!errno && p != e && !*e) { if (precision == 0 || precision > 9) { precision = 9; } m = 9 - precision; while (--m >= 0) { scale *= 10; } } errno = old_errno; } m = p - fmt_str; p += n + 1; if (asprintf(&tmp, "%s%0*u%s", fmt_str, (unsigned)precision, (unsigned)ts.tv_nsec / scale, p) <= 0) { break; } free(fmt_str); fmt_str = tmp; p = fmt_str + m; } strftime(datebuf, datebuf_size, fmt_str, tm); free(fmt_str); } return 0; } static int processLogLine(DataSource *source, const int logcode, const char * const prg, const char * const pid, char * const info) { pcre2_match_data *match_data = pcre2_match_data_create(16, NULL); ConfigBlock *block = config_blocks; RegexWithSign *this_regex; const int facility = LOG_FAC(logcode); const int priority = LOG_PRI(logcode); int nb_regexes; int info_len; int prg_len; int regex_result; RemoteHost *cur_host = NULL; while (block != NULL) { if (block->facilities != NULL) { int nb = block->nb_facilities; const int * const facilities = block->facilities; while (nb > 0) { nb--; if (facility == facilities[nb]) { goto facility_ok; } } goto nextblock; } facility_ok: if (priority > block->minimum && priority < block->maximum) { goto nextblock; } if (block->source != NULL && source != block->source) { goto nextblock; } if (block->program != NULL && strcasecmp(block->program, prg) != 0) { goto nextblock; } if ((nb_regexes = block->program_nb_regexes) > 0) { regex_result = 0; if ((prg_len = (int) strlen(prg)) < 0) { goto nextblock; } this_regex = block->program_regexeswithsign; do { if (this_regex->sign == REGEX_SIGN_POSITIVE) { if (pcre2_match(this_regex->regex, (PCRE2_SPTR)prg, (PCRE2_SIZE)prg_len, 0, 0, match_data, NULL) >= 0) { /* pass, unless a program_neg_regex matches */ regex_result = 1; } else if (regex_result != 1) { /* fail, unless another program_regex matches */ regex_result = -1; } } else { if (pcre2_match(this_regex->regex, (PCRE2_SPTR)prg, (PCRE2_SIZE)prg_len, 0, 0, match_data, NULL) >= 0) { /* fail immediately */ goto nextblock; } /* pass, unless a non-matching program_regex is found or another program_neg_regex matches */ } this_regex++; nb_regexes--; } while (nb_regexes > 0); if (regex_result == -1) { goto nextblock; } } if ((info_len = (int) strlen(info)) <= 0) { goto nextblock; } if ((nb_regexes = block->nb_regexes) > 0 && *info != 0) { regex_result = 0; this_regex = block->regexeswithsign; do { if (this_regex->sign == REGEX_SIGN_POSITIVE) { if (pcre2_match(this_regex->regex, (PCRE2_SPTR)info, (PCRE2_SIZE)info_len, 0, 0, match_data, NULL) >= 0) { /* pass, unless a neg_regex matches */ regex_result = 1; } else if (regex_result != 1) { /* fail, unless another regex matches */ regex_result = -1; } } else { if (pcre2_match(this_regex->regex, (PCRE2_SPTR)info, (PCRE2_SIZE)info_len, 0, 0, match_data, NULL) >= 0) { /* fail immediately */ goto nextblock; } /* pass, unless a non-matching regex is found or another neg_regex matches */ } this_regex++; nb_regexes--; } while (nb_regexes > 0); if (regex_result == -1) { goto nextblock; } } if ((size_t) info_len > MAX_LOG_LENGTH) { info[MAX_LOG_LENGTH] = 0; } char datebuf[100] = { '\0' }; if (block->output && block->output->stamp_fmt[0]) { const char *timestamp_fmt = get_stamp_fmt_for_rfc_format(block->log_format); if (timestamp_fmt != NULL) { get_stamp_fmt_timestamp(timestamp_fmt, datebuf, sizeof(datebuf)); } else { get_stamp_fmt_timestamp(block->output->stamp_fmt, datebuf, sizeof(datebuf)); } } bool do_break = false; if (block->output != NULL) { /* write a real log entry */ writeLogLine(block->output, datebuf, prg, pid, info, priority, facility, block->log_format, block->log_severity); /* write to stdout */ char *line = build_log_line(prg, pid, info, block->log_format, datebuf, priority, facility, false, block->log_severity); printf("%s", line); free(line); /* iterate over all remote hosts */ if(block->num_hosts) { cur_host = remote_hosts; while (cur_host != NULL) { if (cur_host->hostname != NULL && cur_host->severity_level >= priority && isRemoteHostInConfigBlock(block->hosts, block->num_hosts, cur_host) ) { /* if log format is not rfc3164 or rfc5424, use stamp_fmt */ const char *remote_timestamp_fmt = get_stamp_fmt_for_rfc_format(cur_host->format); if (remote_timestamp_fmt != NULL) { get_stamp_fmt_timestamp(remote_timestamp_fmt, datebuf, sizeof(datebuf)); } else { get_stamp_fmt_timestamp(block->output->stamp_fmt, datebuf, sizeof(datebuf)); } sendRemote(prg, pid, info, cur_host, datebuf, priority, facility, block->log_severity); } cur_host = cur_host->next_host; } } if (block->brk) { do_break = true; } } if (block->command != NULL) { spawnCommand(block->command, datebuf, prg, info); if (block->brk) do_break = true; } if (do_break) { break; } nextblock: block = block->next_block; } pcre2_match_data_free(match_data); return 0; } static int doLog(const char * fmt, ...) { char infobuf[512]; char pidbuf[16]; va_list ap; pid_t pid = getpid(); snprintf(pidbuf, sizeof(pidbuf), "%d", pid); va_start(ap, fmt); vsnprintf (infobuf, sizeof infobuf, fmt, ap); va_end(ap); return processLogLine(NULL, LOG_SYSLOG, "metalog", pidbuf, infobuf); } static void sanitize(char * const line_) { register unsigned char *line = (unsigned char *) line_; while (*line != 0U) { /* replace control characters of the line */ if (ISCTRLCODE(*line)) { /* eliminate a trailing control character (even '\n'), if it is the last one in this line */ if (*(line + 1) == 0U) { *line = 0U; } else { /* substitude a control character if it is in the middle of the line */ *line = NONPRINTABLE_SUSTITUTE_CHAR; } } line++; } } static int log_line(DataSource *source, char *buf) { int logcode; const char *prg; char *info; const char *pid = NULL; sanitize(buf); if (parseLogLine(source->type, buf, &logcode, &prg, &pid, &info) < 0) { return -1; } return processLogLine(source, logcode, prg, pid, info); } static int log_kernel(DataSource *source, char *buf, int bsize) { char *s = buf; int n = 0, start = 0; s = buf; while (n < bsize) { if (s[n] == '\n') { s[n] = '\0'; log_line(source, &s[start]); start = n + 1; } n++; } /* we couldn't find any \n ??? => invalidate this buffer */ if (start == 0) { return 0; } return bsize - start; } static int process(int num_sockets) { struct pollfd *fds, *first_source, *siglog; int nfds; int event; ssize_t rd; int ld; char (*buffer)[4096]; DataSource **source_map; DataSource *s; if ((fds = wmalloc((num_sockets + 1) * sizeof *fds)) == NULL || (buffer = wmalloc(num_sockets * sizeof *buffer)) == NULL || (source_map = wmalloc(num_sockets * sizeof *source_map)) == NULL) { return -3; } siglog = first_source = NULL; nfds = 0; siglog = &fds[nfds]; fds[nfds].fd = dolog_queue[0]; fds[nfds].events = POLLIN | POLLERR | POLLHUP | POLLNVAL; fds[nfds].revents = 0; ++nfds; first_source = &fds[nfds]; for (s = data_sources; s; s = s->next_source) { if (s->fd != -1) { struct pollfd *fd = &fds[nfds]; assert(nfds <= num_sockets); source_map[fd - first_source] = s; s->bpos = 0; fd->fd = s->fd; fd->events = POLLIN | POLLERR | POLLHUP | POLLNVAL; fd->revents = 0; ++nfds; } } while (keep_running) { int si; /* source index */ while (poll(fds, nfds, -1) < 0 && errno == EINTR && keep_running) { ; } /* Signal queue */ if (siglog && siglog->revents) { event = siglog->revents; siglog->revents = 0; if (event != POLLIN) { warn("Signal queue socket error - aborting"); close(siglog->fd); return -1; } signal_doLog_dequeue(); } for (si = 0; si < num_sockets; si++) { struct pollfd *fd = &first_source[si]; int event; if (!(event = fd->revents)) { continue; } s = source_map[si]; fd->revents = 0; if (event != POLLIN) { warn("%s socket error - aborting", s->type == LOGLINETYPE_KLOG ? "Klog" : "Syslog"); close(fd->fd); return -1; } if (s->semantics == SOCK_DGRAM) { /* Datagram socket (syslog): */ /* receive a single log line (datagram) and process it. receive one byte for '\0' */ while (((rd = read(fd->fd, buffer[si], sizeof(buffer[si]) - 1)) < 0) && (errno == EINTR)) { ; } if (rd == -1) { return -1; } buffer[si][rd] = '\0'; log_line(s, buffer[si]); } else { /* STREAM_SOCKET (klog): */ /* receive a chunk of kernel log message... */ while (((rd = read(fd->fd, &buffer[si][s->bpos], sizeof(buffer[si]) - s->bpos)) < 0) && (errno == EINTR)) { ; } if (rd == -1) { return -1; } /* ... and process them line by line */ rd += s->bpos; if ((ld = log_kernel(s, buffer[si], rd)) > 0) { /* move remainder of a message to the beginning of the buffer it'll be logged once we can read the whole line into buffer[1] */ memmove(buffer[si], &buffer[si][ld], s->bpos = rd - ld); } else { s->bpos = 0; } } } } return 0; } static int delete_pid_file(const char * const pid_file) { return pid_file ? unlink(pid_file) : 0; } static int update_pid_file(const char * const pid_file) { int fd; FILE *fp; if (pid_file == NULL || *pid_file != '/') { return 0; } fd = open(pid_file, O_CREAT | O_WRONLY | O_TRUNC | O_NOFOLLOW, 0644); if (fd == -1) { goto err; } if (fchmod(fd, 0644)) { goto err; } fp = fdopen(fd, "w"); if (!fp) { goto err; } if (fprintf(fp, "%lu\n", (unsigned long)getpid()) <= 0) { goto err; } if (ferror(fp)) { goto err; } if (fclose(fp)) { goto err; } return 0; err: warnp("pid file creation failed: %s", pid_file); return -1; } static void exit_hook(void) { /* Flush all buffers just to be sure */ synchronous = (sig_atomic_t) 1; flushAll(); if (child > (pid_t) 0) { kill(child, SIGTERM); } delete_pid_file(pid_file); keep_running = false; } static void signal_doLog_queue(const char *fmt, const unsigned int pid, const int status) { ssize_t ret; unsigned int fmt_len = (unsigned int)strlen(fmt); char buf[sizeof(pid) + sizeof(status) + sizeof(fmt_len)]; memcpy(buf, &pid, sizeof(pid)); memcpy(buf+sizeof(pid), &status, sizeof(status)); memcpy(buf+sizeof(pid)+sizeof(status), &fmt_len, sizeof(fmt_len)); ret = write(dolog_queue[1], buf, sizeof(buf)); assert(ret == sizeof(buf)); ret = write(dolog_queue[1], fmt, fmt_len); assert(ret == (ssize_t) fmt_len); } static void signal_doLog_dequeue(void) { unsigned int pid, fmt_len; int status; char *buf; ssize_t ret; ret = read(dolog_queue[0], &pid, sizeof(pid)); assert(ret == sizeof(pid)); ret = read(dolog_queue[0], &status, sizeof(status)); assert(ret == sizeof(status)); ret = read(dolog_queue[0], &fmt_len, sizeof(fmt_len)); assert(ret == sizeof(fmt_len)); buf = malloc(fmt_len+1); assert(buf != NULL); ret = read(dolog_queue[0], buf, fmt_len); assert(ret == (ssize_t) fmt_len); buf[fmt_len] = '\0'; ++spawn_recursion; doLog(buf, pid, status); --spawn_recursion; free(buf); } static void add_remote_host(RemoteHost **remote_hosts_head, const char *name, const char *hostname, const char *port, LogFormat format, int severity_level) { if (hostname == NULL) { warn("Hostname for remote_host[%s] has to be set first", name); return; } RemoteHost *new_host = wmalloc(sizeof(RemoteHost)); if (new_host == NULL) { err("Failed to allocate memory for remote host"); } if (name != NULL) { new_host->name = wstrdup(name); } if (port == NULL) { new_host->port = wstrdup(DEFAULT_UPD_PORT); } else { new_host->port = wstrdup(port); } new_host->hostname = wstrdup(hostname); new_host->sock = -1; new_host->last_dns.tv_sec = 0; new_host->result = NULL; new_host->format = format; new_host->severity_level = severity_level; new_host->next_host = NULL; if (*remote_hosts_head == NULL) { *remote_hosts_head = new_host; } else { RemoteHost *current = *remote_hosts_head; while (current->next_host != NULL) { current = current->next_host; } current->next_host = new_host; } } static char *extract_remote_host_name(const char *const keyword, const char *const pattern) { /* That must be the default remote host */ if (strlen(keyword) == strlen(pattern)) { return strdup(DEFAULT_REMOTE_HOST_NAME); } const char *start = strchr(keyword, '['); const char *end = strchr(keyword, ']'); if (start != NULL && end != NULL && end > start) { size_t length = end - start - 1; char *result = malloc(length + 1); if (result == NULL) { return NULL; } strncpy(result, start + 1, length); result[length] = '\0'; return result; } return strdup(DEFAULT_REMOTE_HOST_NAME); } static RemoteHost *find_remote_host(RemoteHost **hosts, const char *name) { RemoteHost *current = *hosts; while (current != NULL) { if (strcmp(current->name, name) == 0) { return current; } current = current->next_host; } return NULL; } static RemoteHost* find_or_add_remote_host(const char *name, const char *hostname, const char *port, int format, int severity_level) { RemoteHost *current_remote_host = find_remote_host(&remote_hosts, name); if (current_remote_host == NULL) { add_remote_host(&remote_hosts, name, hostname, port, format, severity_level); current_remote_host = find_remote_host(&remote_hosts, name); } return current_remote_host; } static int update_remote_host_field(char **field, const char *value) { free(*field); if ((*field = wstrdup(value)) == NULL) { return -3; } return 0; } static void free_remote_hosts(RemoteHost *remote_hosts_head) { RemoteHost *current = remote_hosts_head; RemoteHost *next; while (current != NULL) { next = current->next_host; free(current->name); free(current->hostname); free(current->port); freeaddrinfo(current->result); free(current); current = next; } } static const char* get_stamp_fmt_for_rfc_format(LogFormat format) { switch (format) { case RFC3164: return "%b %d %H:%M:%S"; case RFC5424: return "%Y-%m-%dT%H:%M:%S.%3NZ"; default: return NULL; } } static bool isRemoteHostInConfigBlock(RemoteHost **hosts_list, int num_hosts, RemoteHost *host) { if (hosts_list == NULL || num_hosts == 0) { return false; } for (int i = 0; i < num_hosts; i++) { if (hosts_list[i] == host) { return true; } } return false; } static const char* build_priority_str(const int severity) { switch (severity) { case LOG_EMERG: return "EMERG"; case LOG_ALERT: return "ALERT"; case LOG_CRIT: return "CRIT"; case LOG_ERR: return "ERR"; case LOG_WARNING: return "WARNING"; case LOG_NOTICE: return "NOTICE"; case LOG_INFO: return "INFO"; case LOG_DEBUG: return "DEBUG"; default: return "UNKNOWN"; } } static char* build_log_line(const char * const prg, const char * const pid, const char * const info, LogFormat format, const char * const datebuf, const int priority, const int facility, bool print_hostname, bool log_severity) { char *line = NULL; char hostname[HOST_NAME_MAX + 1] = {0}; int pri = facility * 8 + priority; const char *prg_safe = (prg != NULL) ? prg : NILVALUE; const char *pid_safe = (pid != NULL) ? pid : NILVALUE; const char *datebuf_safe = (datebuf != NULL) ? datebuf : NILVALUE; get_hostname(hostname, sizeof(hostname), print_hostname); switch (format) { case LEGACY: case LEGACY_TIMESTAMP: if (log_severity) { if (datebuf == NULL || format == LEGACY) { line = format_log_line("[%s][%s] %s\n", prg_safe, build_priority_str(priority), info); } else { line = format_log_line("%s [%s][%s] %s\n", datebuf_safe, prg_safe, build_priority_str(priority), info); } break; } else { if (datebuf == NULL || format == LEGACY) { line = format_log_line("[%s] %s\n", prg_safe, info); } else { line = format_log_line("%s [%s] %s\n", datebuf_safe, prg_safe, info); } break; } case RFC3164: line = handle_rfc3164_format(pri, datebuf_safe, hostname, prg_safe, pid_safe, info, print_hostname); break; case RFC5424: line = handle_rfc5424_format(pri, datebuf_safe, hostname, prg_safe, pid_safe, info, print_hostname); break; default: err("Failed to set log format"); return NULL; } return line; } static void get_hostname(char *hostname, size_t size, bool print_hostname) { if (print_hostname) { if (gethostname(hostname, size) != 0) { snprintf(hostname, size, "%s", NILVALUE); } } } static char* handle_rfc3164_format(int pri, const char *datebuf_safe, char *hostname, const char *prg_safe, const char *pid_safe, const char *info, bool print_hostname) { char *line; if (strcmp(prg_safe, "kernel") == 0) { if (print_hostname) { line = format_log_line("<%d>%s %s %s: %s\n", pri, datebuf_safe, hostname, prg_safe, info); } else { line = format_log_line("<%d>%s %s: %s\n", pri, datebuf_safe, prg_safe, info); } } else { if (print_hostname) { line = format_log_line("<%d>%s %s %s[%s]: %s\n", pri, datebuf_safe, hostname, prg_safe, pid_safe, info); } else { line = format_log_line("<%d>%s %s[%s]: %s\n", pri, datebuf_safe, prg_safe, pid_safe, info); } } return line; } static char* handle_rfc5424_format(int pri, const char *datebuf_safe, char *hostname, const char *prg_safe, const char *pid_safe, const char *info, bool print_hostname) { struct addrinfo hints = {0}, *res = NULL; hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_CANONNAME; if (print_hostname) { if (getaddrinfo(hostname, NULL, &hints, &res) != 0) { snprintf(hostname, HOST_NAME_MAX + 1, "%s", NILVALUE); } else { snprintf(hostname, HOST_NAME_MAX + 1, "%s", res->ai_canonname); } } char *line; if (strcmp(prg_safe, "kernel") == 0) { if (print_hostname) { line = format_log_line("<%d>1 %s %s %s - - - %s%s\n", pri, datebuf_safe, hostname, prg_safe, BOM_UTF8, info); } else { line = format_log_line("<%d>1 %s %s - - - %s%s\n", pri, datebuf_safe, prg_safe, BOM_UTF8, info); } } else { if (print_hostname) { line = format_log_line("<%d>1 %s %s %s %s - - %s%s\n", pri, datebuf_safe, hostname, prg_safe, pid_safe, BOM_UTF8, info); } else { line = format_log_line("<%d>1 %s %s %s - - %s%s\n", pri, datebuf_safe, prg_safe, pid_safe, BOM_UTF8, info); } } if (res != NULL) { freeaddrinfo(res); } return line; } static char* format_log_line(const char *format, ...) { va_list args; va_start(args, format); size_t size = vsnprintf(NULL, 0, format, args) + 1; va_end(args); char *line = allocate_log_line(size); if (line == NULL) { return NULL; } va_start(args, format); vsnprintf(line, size, format, args); va_end(args); return line; } static char* allocate_log_line(size_t size) { char *line = (char *)malloc(size); if (line == NULL) { err("Failed to allocate memory for log line"); } return line; } static LogFormat translate_log_format(const char * const format) { static const LogFormatMapping log_format_mappings[] = { {"legacy", LEGACY}, {"legacy_timestamp", LEGACY_TIMESTAMP}, {"rfc3164", RFC3164}, {"rfc5424", RFC5424} }; static const size_t log_format_mappings_count = sizeof(log_format_mappings) / sizeof(log_format_mappings[0]); for (size_t i = 0; i < log_format_mappings_count; ++i) { if (strcmp(format, log_format_mappings[i].name) == 0) { return log_format_mappings[i].format; } } warn("Invalid log_format: %s - set default format\n", format); return RFC5424; } #ifndef __SANITIZE_ADDRESS__ __attribute__ ((noreturn)) #endif static void metalog_signal_exit(int exit_status) { exit_hook(); #ifndef __SANITIZE_ADDRESS__ _exit(exit_status); #endif } __attribute__ ((noreturn)) static void sigkchld(int sig) { signal_doLog_queue("Process [%u] died with signal [%d]\n", (unsigned int) getpid(), sig); metalog_signal_exit(EXIT_FAILURE); keep_running = false; } static void sigchld(int sig) { pid_t pid; signed char should_exit = 0; int child_status; (void) sig; while ((pid = waitpid((pid_t) -1, &child_status, WNOHANG)) > (pid_t) 0) { if (pid == child) { signal_doLog_queue("Klog child [%u] died.", (unsigned) pid, 0); should_exit = 1; } else { if (WIFEXITED(child_status) && WEXITSTATUS(child_status)) { signal_doLog_queue("Child [%u] exited with return code %u.", (unsigned) pid, WEXITSTATUS(child_status)); } else if (!WIFEXITED(child_status)) { signal_doLog_queue("Child [%u] caught signal %u.", (unsigned) pid, WTERMSIG(child_status)); } else if (verbose) { signal_doLog_queue("Child [%u] exited successfully.", (unsigned) pid, 0); } } } if (should_exit != 0) { child = (pid_t) 0; keep_running = false; metalog_signal_exit(EXIT_FAILURE); } } static void sigusr1(int sig) { (void) sig; synchronous = (sig_atomic_t) 1; signal_doLog_queue("Got SIGUSR1 - enabling synchronous mode.", 0, 0); flushAll(); } static void sigusr2(int sig) { (void) sig; synchronous = (sig_atomic_t) 0; signal_doLog_queue("Got SIGUSR2 - disabling synchronous mode.", 0, 0); } static void setsignals(void) { atexit(exit_hook); signal(SIGCHLD, sigchld); signal(SIGPIPE, sigkchld); signal(SIGHUP, sigkchld); signal(SIGTERM, sigkchld); signal(SIGQUIT, sigkchld); signal(SIGINT, sigkchld); signal(SIGUSR1, sigusr1); signal(SIGUSR2, sigusr2); } #ifndef HAVE_DAEMON static int closedesc_all(const int closestdin) { int fodder; if (closestdin != 0) { (void) close(0); if ((fodder = open("/dev/null", O_RDONLY)) == -1) { return -1; } (void) dup2(fodder, 0); if (fodder > 0) { (void) close(fodder); } } if ((fodder = open("/dev/null", O_WRONLY)) == -1) { return -1; } (void) dup2(fodder, 1); (void) dup2(1, 2); if (fodder > 2) { (void) close(fodder); } return 0; } #endif static void dodaemonize(void) { if (daemonize != 0) { #ifndef HAVE_DAEMON pid_t child; if ((child = fork()) == (pid_t) -1) { warnp("Daemonization failed - fork"); return; } else if (child != (pid_t) 0) { _exit(EXIT_SUCCESS); } else if (setsid() == (pid_t) -1) { errp("Daemonization failed : setsid"); } (void) chdir("/"); (void) closedesc_all(1); #else if (daemon(0, 0)) { errp("Daemonization failed"); } #endif } } static void setgroup(void) { if (group_name == NULL) { return; } struct group *g; errno = 0; if ((g = getgrnam(group_name)) == NULL) { if(errno == 0) { err("Failed to set group: group '%s' not found", group_name); } else { errp("Failed to set group"); } } if (setgid(g->gr_gid) == -1) { errp("Failed to set group"); } } __attribute__ ((noreturn)) static void help(void) { const struct option *options = long_options; puts(PACKAGE " version " VERSION "\n"); puts("Options:"); do { printf(" -%c, --%s%s\n", options->val, options->name, options->has_arg ? " " : ""); options++; } while (options->name != NULL); exit(EXIT_SUCCESS); } static void parseOptions(int argc, char *argv[]) { int fodder; int option_index = 0; while ((fodder = getopt_long(argc, argv, GETOPT_OPTIONS, long_options, &option_index)) != -1) { switch (fodder) { case 'a' : synchronous = (sig_atomic_t) 0; break; case 'B' : daemonize = 1; break; #ifdef HAVE_KLOGCTL case 'c' : console_level = atoi(optarg); if (console_level < MIN_CONSOLE_LEVEL || console_level > MAX_CONSOLE_LEVEL) err("Invalid console level"); break; #endif case 'C' : config_file = xstrdup(optarg); break; case 'g' : group_name = xstrdup(optarg); break; case 'v' : ++verbose; break; case 'N' : do_kernel_log = false; break; case 'V' : puts(PACKAGE " version " VERSION); exit(EXIT_SUCCESS); case 'h' : help(); case 'p' : pid_file = xstrdup(optarg); break; case 's' : break; case 't' : test_config = 1; break; case ':' : err("Option '%c' is missing parameter", optopt); case '?': err("Unknown option '%c' or argument missing", optopt); default : err("Unknown option '%c'", optopt); } } } static void checkRoot(void) { if (geteuid() != (uid_t) 0) { err("Sorry, you must be root to launch this program"); } } static void free_resources(void) { free_remote_hosts(remote_hosts); free_data_sources(&data_sources); } static void compile_regexes(void) { pcre_matches = pcre2_match_data_create(1, NULL); re_compressed = wpcre2_compile(COMPRESSED_REGEX, 0); if (!pcre_matches || !re_compressed) { err("Compiling regexes"); } } static void free_regexes(void) { if (pcre_matches) { pcre2_match_data_free(pcre_matches); } if (re_compressed) { pcre2_code_free(re_compressed); } } int main(int argc, char *argv[]) { int ret; int num_sockets; compile_regexes(); parseOptions(argc, argv); if (do_kernel_log) { add_data_source(LOGLINETYPE_KLOG, NULL, false); } add_data_source(LOGLINETYPE_SYSLOG, SOCKNAME, true); ret = configParser(config_file); if (test_config) { return ret; } if (ret < 0) { free_resources(); err("Bad configuration file"); } checkRoot(); setgroup(); dodaemonize(); setsignals(); if (update_pid_file(pid_file)) { free_resources(); return -1; } clearargs(argc, argv); setprogname(PROGNAME_MASTER); if ((num_sockets = getDataSources()) < 0) { free_resources(); err("Unable to bind sockets"); } ret = process(num_sockets); free_resources(); free_regexes(); return ret; } hvisage-metalog-8e511b7/src/metalog.h000066400000000000000000000151571512715635700175410ustar00rootroot00000000000000#ifndef __METALOG_H__ #define __METALOG_H__ 1 #ifndef __GNUC__ # ifdef __attribute__ # undef __attribute__ # endif # define __attribute__(a) #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifndef HAVE_SYSLOG_NAMES # include "syslognames.h" #endif #ifdef HAVE_SYS_KLOG_H # include #endif #define PCRE2_CODE_UNIT_WIDTH 8 #include #include "helpers.h" #ifdef _PATH_LOG # define SOCKNAME _PATH_LOG #else # define SOCKNAME "/dev/log" #endif #ifdef _PATH_KLOG # define KLOG_FILE _PATH_KLOG #else # define KLOG_FILE "/dev/klog" #endif #ifdef WITH_COMPRESS #include #include #endif typedef struct DuplicateTracker_ { char *previous_prg; char *previous_info; size_t sizeof_previous_prg; size_t sizeof_previous_info; size_t previous_sizeof_prg; size_t previous_sizeof_info; unsigned int same_counter; } DuplicateTracker; typedef enum FlushMode_ { FLUSH_DEFAULT, FLUSH_ALWAYS, FLUSH_NEVER } FlushMode; typedef enum LogFormat_ { LEGACY, LEGACY_TIMESTAMP, RFC3164, RFC5424 } LogFormat; typedef struct { const char *name; LogFormat format; } LogFormatMapping; typedef struct { const char *name; int severity; } SeverityMapping; typedef struct RateLimiter_ { int64_t usec_between_msgs; int bucket_size; int token_bucket; int64_t last_tick; } RateLimiter; /* describing a remote syslog server */ typedef struct RemoteHost_ { char *name; /* internal name */ char *hostname; /* host name of remote host */ char *port; /* UDP port */ int sock; /* UDP socket to remote server */ struct timespec last_dns; /* time stamp of last successful DNS lookup */ struct addrinfo *result; /* IP address of resolved remote server */ LogFormat format; /* format of logging */ int severity_level; /* defines from which severity logs are transmitted */ struct RemoteHost_ *next_host; } RemoteHost; typedef struct Output_ { char *directory; mode_t perms; FILE *fp; off_t size; off_t maxsize; int maxfiles; time_t maxtime; time_t creatime; DuplicateTracker dt; struct Output_ *next_output; char *postrotate_cmd; int showrepeats; const char *stamp_fmt; FlushMode flush; RateLimiter rate; bool compress; int compress_delay; } Output; typedef enum LogLineType_ { LOGLINETYPE_SYSLOG, LOGLINETYPE_KLOG } LogLineType; typedef struct DataSource_ { LogLineType type; char *path; struct DataSource_ *next_source; bool required; int fd; int semantics; /* SOCK_DGRAM or SOCK_STREAM */ int bpos; /* write pointer for stream sources */ } DataSource; typedef enum RegexSign_ { REGEX_SIGN_POSITIVE, REGEX_SIGN_NEGATIVE } RegexSign; typedef struct RegexWithSign_ { pcre2_code *regex; RegexSign sign; } RegexWithSign; typedef struct ConfigBlock_ { int minimum; int maximum; int *facilities; int nb_facilities; RegexWithSign *regexeswithsign; int nb_regexes; off_t maxsize; int maxfiles; time_t maxtime; mode_t perms; Output *output; const char *command; const char *program; /* * If output or command match, and brk is set, * do output and/or command then break out of * match loop, i.e. don't consider any more * sections below this one in the config file. */ int brk; RegexWithSign *program_regexeswithsign; int program_nb_regexes; struct ConfigBlock_ *next_block; char *postrotate_cmd; int showrepeats; const char *stamp_fmt; FlushMode flush; int64_t usec_between_msgs; int burst_length; RemoteHost **hosts; /* remote_hosts which should receive logs of this block */ int num_hosts; /* number of remote_hosts */ LogFormat log_format; /* format of logging */ bool log_severity; /* log severity level in format legacy or legacy_timestamp */ DataSource *source; bool compress; /* whether to compress rotated logs */ int compress_delay; /* how many recently rotated logs to keep uncompressed */ } ConfigBlock; #define DEFAULT_MINIMUM LOG_DEBUG #define DEFAULT_MAXIMUM INT_MAX #define DEFAULT_MAXSIZE ((off_t) 1000000) #define DEFAULT_MAXFILES 5 #define DEFAULT_MAXTIME ((time_t) 60 * 60 * 24) #define DEFAULT_CONSOLE_LEVEL 7 #define MIN_CONSOLE_LEVEL 0 #define MAX_CONSOLE_LEVEL 7 #define CF_PROGNAME_KERNEL "kernel" #define OUTPUT_DIR_TIMESTAMP ".timestamp" #define OUTPUT_DIR_CURRENT "current" #define DEFAULT_PERMS 0700 #define OUTPUT_DIR_LOGFILES_PREFIX "log-" #define OUTPUT_DIR_LOGFILES_SUFFIX "%Y-%m-%d-%H:%M:%S" #define COMPRESS_SUFFIX ".gz" #define COMPRESSED_REGEX "\\.(?:Z|gz|bz2|xz)$" #define DEFAULT_COMPRESS_DELAY 0 #define DEFAULT_CONFIG_FILE CONFDIR "/metalog.conf" #define DEFAULT_PID_FILE "/var/run/metalog.pid" #define NONPRINTABLE_SUSTITUTE_CHAR '_' #define PROGNAME_MASTER "metalog [MASTER]" #define PROGNAME_KERNEL "metalog [KERNEL]" #define LAST_OUTPUT " - Last output repeated %u times -\n" #define LAST_OUTPUT_TWICE " - Last output repeated twice -\n" #define MAX_SIGNIFICANT_LENGTH 512U #define MAX_LOG_LENGTH 8192U /* must be < (INT_MAX / 2) */ #define DEFAULT_STAMP_FMT "%b %d %T" #define DEFAULT_UPD_PORT "514" /* UDP port of the remote syslog server */ #define DEFAULT_DNS_LOOKUP_INTERVERVAL 120 /* seconds, after that a DNS lookup should be repeated */ #define DEFAULT_REMOTE_HOST_NAME "default" #define DEFAULT_LOG_FORMAT 1 /* LEGACY_TIMESTAMP */ #define DEFAULT_REMOTE_LOG_FORMAT 0 /* LEGACY */ #define DEFAULT_SEVERITY_LEVEL 7 /* LOG_DEBUG */ #define NILVALUE "-" #define BOM_UTF8 "\xEF\xBB\xBF" #ifdef ACCEPT_UNICODE_CONTROL_CHARS /* "DEL" (0x7f) character or all characters < "SPACE" (0x20) */ # define ISCTRLCODE(X) ((X) == 0x7f || ((unsigned char) (X)) < 0x20) #else /* "DEL" (0x7f) character or all characters in (extended) ASCII character control groups C0 and C1 */ # define ISCTRLCODE(X) ((X) == 0x7f || !(((unsigned char) (X)) & 0x60)) #endif #endif hvisage-metalog-8e511b7/src/metalog_p.h000066400000000000000000000027431512715635700200550ustar00rootroot00000000000000#ifndef __METALOG_P_H__ #define __METALOG_P_H__ 1 #ifdef HAVE_KLOGCTL # define KLOGCTL_OPTIONS "c:" #else # define KLOGCTL_OPTIONS "" #endif #define GETOPT_OPTIONS KLOGCTL_OPTIONS "aBC:g:hp:stVvN" static struct option long_options[] = { { "async", 0, NULL, 'a' }, { "daemonize", 0, NULL, 'B' }, #ifdef HAVE_KLOGCTL { "consolelevel", 1, NULL, 'c' }, #endif { "configfile", 1, NULL, 'C' }, { "group", 1, NULL, 'g' }, { "help", 0, NULL, 'h' }, { "no-kernel", 0, NULL, 'N' }, { "pidfile", 1, NULL, 'p' }, { "synchronous", 0, NULL, 's' }, { "sync", 0, NULL, 's' }, { "test-config", 0, NULL, 't' }, { "verbose", 0, NULL, 'v' }, { "version", 0, NULL, 'V' }, { NULL, 0, NULL, 0 } }; #if defined(__linux__) && !defined(HAVE_SETPROCTITLE) static char **argv0 = NULL; static int argv_lth; #endif static ConfigBlock *config_blocks = NULL; static Output *outputs = NULL; static RemoteHost *remote_hosts = NULL; #ifdef HAVE_KLOGCTL static int console_level = DEFAULT_CONSOLE_LEVEL; #endif static pid_t child; static sig_atomic_t synchronous = (sig_atomic_t) 1; static int verbose; static int test_config; static bool do_kernel_log = true; static signed char daemonize; static const char *pid_file = DEFAULT_PID_FILE; static const char *config_file = DEFAULT_CONFIG_FILE; static const char *config_dir = NULL; static const char *group_name = NULL; static DataSource *data_sources = NULL; #endif hvisage-metalog-8e511b7/src/syslognames.h000066400000000000000000000031361512715635700204470ustar00rootroot00000000000000#ifndef __SYSLOGNAMES_H__ #define __SYSLOGNAMES_H__ 1 #ifdef SYSLOG_NAMES struct { const char *c_name; int c_val; } facilitynames[] = { # ifdef LOG_AUTH { "auth", LOG_AUTH }, # endif # ifdef LOG_AUTHPRIV { "authpriv", LOG_AUTHPRIV }, # endif # ifdef LOG_CRON { "cron", LOG_CRON }, # endif # ifdef LOG_DAEMON { "daemon", LOG_DAEMON }, # endif # ifdef LOG_FTP { "ftp", LOG_FTP }, # endif # ifdef LOG_KERN { "kern", LOG_KERN }, # endif # ifdef LOG_LPR { "lpr", LOG_LPR }, # endif # ifdef LOG_MAIL { "mail", LOG_MAIL }, # endif # ifdef INTERNAL_MARK { "mark", INTERNAL_MARK }, /* INTERNAL */ # endif # ifdef LOG_NEWS { "news", LOG_NEWS }, # endif # ifdef LOG_AUTH { "security", LOG_AUTH }, /* DEPRECATED */ # endif # ifdef LOG_SYSLOG { "syslog", LOG_SYSLOG }, # endif # ifdef LOG_USER { "user", LOG_USER }, # endif # ifdef LOG_UUCP { "uucp", LOG_UUCP }, # endif # ifdef LOG_LOCAL0 { "local0", LOG_LOCAL0 }, # endif # ifdef LOG_LOCAL1 { "local1", LOG_LOCAL1 }, # endif # ifdef LOG_LOCAL2 { "local2", LOG_LOCAL2 }, # endif # ifdef LOG_LOCAL3 { "local3", LOG_LOCAL3 }, # endif # ifdef LOG_LOCAL4 { "local4", LOG_LOCAL4 }, # endif # ifdef LOG_LOCAL5 { "local5", LOG_LOCAL5 }, # endif # ifdef LOG_LOCAL6 { "local6", LOG_LOCAL6 }, # endif # ifdef LOG_LOCAL7 { "local7", LOG_LOCAL7 }, # endif # ifdef LOG_LOCAL8 { "local8", LOG_LOCAL8 }, # endif # ifdef LOG_LOCAL9 { "local9", LOG_LOCAL9 }, # endif { NULL, -1 } }; #else extern struct { const char *c_name; int c_val; } facilitynames[]; #endif #endif