pax_global_header00006660000000000000000000000064134442103620014511gustar00rootroot0000000000000052 comment=f8a39f554d636baaeb1f6725790589b70859bf86 nsca-ng-1.6/000077500000000000000000000000001344421036200127055ustar00rootroot00000000000000nsca-ng-1.6/.coverity.yml000066400000000000000000000001031344421036200153440ustar00rootroot00000000000000configurationVersion: 1 filters: - filePath: /tests/test_nsca.c nsca-ng-1.6/.gitignore000066400000000000000000000010731344421036200146760ustar00rootroot00000000000000*.a *.o *.plist *~ .*.swp .deps/ /ChangeLog /INSTALL /aclocal.in /aclocal.m4 /autom4te.cache/ /build-aux/ar-lib /build-aux/compile /build-aux/depcomp /build-aux/install-sh /build-aux/missing /config.h /config.h.in /config.log /config.status /configure /confuse-* /lib/confuse/ /lib/ssl/ /man/*.man /man/*.pdf /man/*.ps /nsca-ng-*.tar.gz /openssl-* /python/build/ /src/client/send_nsca /src/server/nsca-ng /stamp-h1 /tests/atconfig /tests/atlocal /tests/package.m4 /tests/test_nsca /tests/testsuite /tests/testsuite.dir/ /tests/testsuite.log Makefile Makefile.in gmon.out nsca-ng-1.6/.travis.yml000066400000000000000000000020311344421036200150120ustar00rootroot00000000000000language: c before_install: - sudo add-apt-repository -y "deb ftp://ftp.fu-berlin.de/linux/ubuntu/ trusty main" - sudo apt-get -qq update install: - sudo apt-get -qq install libconfuse-dev libsystemd-daemon-dev before_script: - ./autogen.sh script: - ./configure --enable-server && make check # # Trigger Coverity Scan whenever we push into the "coverity" branch. # env: global: # This is the encrypted COVERITY_SCAN_TOKEN, created via the "travis # encrypt" command using the project repository's public key. - secure: "exX2eoF7QqazwvGrY+NoG/Q3xuMQORX0SB8buWYBIkGm3g/2BOYOWcP0f0TvMySW7Jnop+YIukJCxlrn8qlxyBhHD+TL+Lp5ehVECxsGT5Ls+fYW+35CQoHt/92i8ELiKeMrWghzLq5tstFjdQa6XEv8bKi35XwMHQlX8XuRFvU=" addons: coverity_scan: project: name: "weiss/nsca-ng" description: "An add-on for transferring monitoring data" notification_email: holger@weiss.in-berlin.de build_command_prepend: ./autogen.sh && ./configure --enable-server build_command: make branch_pattern: coverity # vim:set nowrap: nsca-ng-1.6/AUTHORS000066400000000000000000000005221344421036200137540ustar00rootroot00000000000000Holger Weiss wrote most of the NSCA-ng client and server code. Alexander Golovko wrote the (technically separate) Python client module distributed with NSCA-ng. Matthias Bethke wrote the (technically separate) Perl client module distributed with NSCA-ng. nsca-ng-1.6/COPYING000066400000000000000000000052521344421036200137440ustar00rootroot00000000000000Unless otherwise noted, all files distributed as part of NSCA-ng are covered by the copyright and license statement below. Some files (outside the `src' directory) are subject to different copyright and/or license terms, as specified at the top of those files. However, all NSCA-ng code is believed to be covered by terms which are at least as permissive as the following license. | Copyright (c) 2013 Holger Weiss | All rights reserved. | | Redistribution and use in source and binary forms, with or without | modification, are permitted provided that the following conditions are | met: | | 1. Redistributions of source code must retain the above copyright notice, | this list of conditions and the following disclaimer. | | 2. Redistributions in binary form must reproduce the above copyright | notice, this list of conditions and the following disclaimer in the | documentation and/or other materials provided with the distribution. | | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS | IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR | PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR | CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, | EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, | PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR | PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF | LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING | NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. In addition to these copyright and license terms, binary redistributions may be required to reproduce the following copyright notices, depending on which source files are compiled. The above license statement applies to all of them. If any files in the `lib/ev' directory are used during compilation: | Copyright (c) 2007-2018 Marc Alexander Lehmann | Copyright (c) 2011 Emanuele Giaquinta If any files in the `lib/pidfile' directory are used during compilation: | Copyright (c) 2005 Pawel Jakub Dawidek | Copyright (c) 2007 Dag-Erling Coidan Smoergrav If the file `lib/pidfile/flock.c' is used during compilation: | Copyright (c) 2001 The NetBSD Foundation, Inc. If any files in the `python' directory (except for `uthash.h') are used: | Copyright (c) 2014 Alexander Golovko If any files in the `perl' directory are used: | Copyright (c) 2015 Matthias Bethke Additional requirements may be imposed by external libraries. nsca-ng-1.6/Makefile.am000066400000000000000000000034361344421036200147470ustar00rootroot00000000000000## Process this file with automake(1) to produce Makefile.in. ## Copyright (c) 2013 Holger Weiss ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1. Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## ## 2. Redistributions in binary form must reproduce the above copyright notice, ## this list of conditions and the following disclaimer in the documentation ## and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE ## LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ## CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF ## SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ## INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ## CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ## ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ## POSSIBILITY OF SUCH DAMAGE. ACLOCAL_AMFLAGS = -I m4 EXTRA_DIST = ChangeLog PROTOCOL autogen.sh SUBDIRS = lib src man etc build-aux contrib perl python tests # # The ChangeLog file is auto-generated from the Git history. We let it depend # on configure.ac, as we bump our version number in that file. # ChangeLog: configure.ac $(AM_V_GEN)$(top_srcdir)/build-aux/generate-change-log > $@ nsca-ng-1.6/NEWS000066400000000000000000000126001344421036200134030ustar00rootroot00000000000000NSCA-ng Release History ======================= Changes in Release 1.6 (2019-03-19) ----------------------------------- - Work around TLSv1.3 PSK bug in (at least) OpenSSL 1.1.1b. - Update our copy of libev from version 4.22 to version 4.25. The new release provides a few platform compatibilty fixes and small enhancements. - Apply a few minor improvements. Changes in Release 1.5 (2016-11-15) ----------------------------------- - Include an experimental NSCA-ng client module for Perl. - Link against libsystemd instead of libsystemd-daemon when using systemd version 210 or newer, where the latter library has been merged into the former. - Include the systemd.service(5) and systemd.socket(5) files with the release tarball. - Update our copy of libev from version 4.15 to version 4.22. The new release provides a number of bug fixes and small enhancements. Changes in Release 1.4 (2014-10-14) ----------------------------------- - Fix NSCA-ng's systemd support: Actually send the keep-alive packets expected by the watchdog. - Include an experimental NSCA-ng client module for Python. Changes in Release 1.3 (2014-07-15) ----------------------------------- - Make the server play nicely with systemd by providing a systemd.service(5) file and adding optional support for socket activation as well as other systemd features, such as watchdog supervision. When compiled with systemd support, the server enables these features automatically if it was socket activated. - Fix an issue that prevented compilation on (at least) Solaris and FreeBSD and caused a fatal startup error on (at least) NetBSD and OpenBSD. - Make sure our copy of FreeBSD's pidfile(3) code isn't used if the system provides it. The Autoconf test got this wrong in certain cases. - Don't buffer log output written to the standard error output. - Accept CRLF-terminated client configuration files. - Apply a few minor fixes. Changes in Release 1.2 (2013-11-06) ----------------------------------- - Let nsca-ng.cfg(5)'s `include` directive and nsca-ng(8)'s `-c` flag accept directory path names. If a directory is specified, read the server configuration from all `*.cfg` and `*.conf` files in the specified directory and all subdirectories. - Let the client's `-d` and `-e` flags accept C-style escape sequences, so that e.g. `-e '\n'` can be specified. Octal and hexadecimal numbers are also accepted. - Allow for specifying authorization settings outside of the `authorize` sections in nsca-ng.cfg(5) files. They will then serve as a fallback for `authorize` sections that don't define these settings. - Fix a race condition in the case where the command file is recreated after the NSCA-ng server had opened it. - Fix a crash of the client on 32-bit platforms that use 64-bit timestamps. - Don't use half-broken POSIX AIO implementations such as the one provided by Debian GNU/kFreeBSD 7. - Apply test suite fixes for GNU Hurd. - Update our copy of libev from version 4.11 to version 4.15. The new release provides a number of bug fixes and minor enhancements. - Apply some minor cleanups. Changes in Release 1.1 (2013-04-12) ----------------------------------- - Add chroot(2) support to the server. - Let the server accept `hosts` patterns in `authorize` sections. They're syntactic sugar for allowing host checks to be submitted (analogous to the `services` patterns for service check submissions). - Let the client ignore empty input lines. This fixes some corner cases where NSCA-ng's client didn't accept the same input as the client provided with the original NSCA package. - Add the `-e` client option, which allows for specifying a delimiter to use instead of the ASCII ETB character for separating check results. - Let the `invoke_check` script (provided in the `contrib` directory of the source tarball) survive plugin return codes other than zero. This should make the script slightly more useful :-) - Apply a few minor improvements. Changes in Release 1.0 (2013-03-06) ----------------------------------- - Actually use the POSIX AIO API if it's provided by the target system. The corresponding Autoconf test was broken since version 0.2. - When opening the command file, check whether it's a named pipe. If it's not, log a warning message and retry opening it later on. - Use the PSK-AES256-CBC-SHA cipher suite (instead of PSK-RC4-SHA) by default. - Apply various minor fixes and improvements. Changes in Release 0.3 (2013-02-25) ----------------------------------- - First public release. - Fix the server's `-s` and `-S` options. They were effectively ignored. - Mention the session ID in all log messages related to the TLS communication in order to ease debugging. - Apply a few minor cleanups. Changes in Release 0.2 (2013-02-19, Unpublished) ------------------------------------------------ - Accept non-numeric service check result status when matching against service patterns. - Don't accept spurious service check results. This could have happened when service patterns without host name part were specified. - Mention the session ID when refusing data. - Fix the client's `-s` option. It was effectively ignored. - Don't link the client against the libraries used only by the server. - Apply various minor cleanups. Changes in Release 0.1 (2013-02-08, Unpublished) ------------------------------------------------ - Initial release. nsca-ng-1.6/PROTOCOL000066400000000000000000000175101344421036200140750ustar00rootroot00000000000000The NSCA-ng Protocol, Version 1 =============================== > [Holger Weiss](mailto:holger@weiss.in-berlin.de) > February 2013 This is an informal description of the NSCA-ng Protocol, Version 1, used for transmitting "monitoring commands" from NSCA-ng clients to NSCA-ng servers. The keywords "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC 2119][1]. Connection Initiation --------------------- The NSCA-ng server listens on TCP port 5668. As soon as an NSCA-ng client connects, a TLS handshake is initiated in order to establish a secure connection. Implementations MUST support TLS v1.0 as per [RFC 2246][2]. Also, the pre-shared key cipher suite `TLS_PSK_WITH_AES_256_CBC_SHA` as defined in [RFC 4279][3] MUST be offered by clients and accepted by servers. However, implementations MAY attempt to negotiate newer versions of the TLS protocol and/or other TLS cipher suites during the TLS handshake. When the TLS connection is established successfully, the client can initiate the first NSCA-ng request. All NSCA-ng data MUST be transmitted as TLS "application data". NSCA-ng Session --------------- Let's begin with an example where the client successfully transmits the `ENABLE_NOTIFICATIONS` command to the server (`C:` and `S:` indicate lines sent by the client and server, respectively): C: MOIN 1 Zm9vYmFy S: MOIN 1 C: PUSH 34 S: OKAY C: [1358980254] ENABLE_NOTIFICATIONS S: OKAY C: QUIT S: OKAY An NSCA-ng session is a sequence of one or more request-response pairs and zero or more "monitoring command" submissions. Requests and responses are CRLF-terminated lines (though implementations SHOULD also accept LF-terminated lines). The length of such a line MUST NOT exceed 1024 octets, including the CRLF-termination. Requests can only be issued by clients. A request consists of a case-insensitive four-character keyword followed by zero or more arguments. Keywords and arguments consist of printable US-ASCII characters, and are each separated by a single space character. Responses are emitted by servers and consist of a four-character keyword, which MUST be sent in all uppercase letters. The first request issued by the client (after establishing the TLS session) MUST be a `MOIN`, `PING`, or `BAIL` request. If the first request is a `MOIN` request, the last request issued by the client MUST be a `QUIT` or `BAIL` request. The remaining part of this document describes the possible client requests and server responses. "Monitoring command" submissions are described in the context of the `PUSH` request. MOIN Request ------------ Synopsis: MOIN Example: MOIN 1 Zm9vYmFy The client issues a `MOIN` request in order to negotiate the protocol `` and to specify a ``. The protocol `` is a positive decimal number, currently always `1`. The `` is an arbitrary string consisting of 2--64 printable US-ASCII characters. Clients SHOULD strive for uniqueness when generating the ``, though it's currently not referenced anywhere else in the NSCA-ng protocol. Implementations might mention the `` when logging connection data. If a `MOIN` request is sent, it MUST be the first request of an NSCA-ng session; except that the `MOIN` request MAY be retried with different parameters after the server replied to a `MOIN` request with a `FAIL` response. On success, the server replies with a `MOIN` response. See also: PING Request ------------ Synopsis: PING Example: PING 1 The protocol `` is a positive decimal number, currently always `1`. If a `PING` request is sent, it MUST be the first request of an NSCA-ng session; except that the `PING` request MAY be retried with different parameters after the server replied to a `PING` request with a `FAIL` response. On success, the server replies with a `PONG` response. The TLS connection is then shut down (cleanly) by both sides. PUSH Request ------------ Synopsis: PUSH Example: PUSH 42 The client issues a `PUSH` request in order to initiate a "monitoring command" submission. The "monitoring command" is expected to be in the format described in the Nagios documentation. The trailing newline character MUST be included, and the submitted "monitoring command" MUST NOT be CRLF-terminated. Newline characters within the "monitoring command" (except for the trailing newline) MUST be replaced with the literal string `\n`, and backslash characters MUST be escaped with another backslash. The `` parameter specifies the size of the "monitoring command" in octets, including the trailing newline character. On success, the server replies with an `OKAY` response. The client then transmits the "monitoring command". On success, the server replies with another `OKAY` response. The client MUST NOT submit multiple "monitoring commands" via a single `PUSH` request. The client MAY issue multiple `PUSH` requests per NSCA-ng session, though. NOOP Request ------------ Synopsis: NOOP Example: NOOP A `NOOP` request has no effect, with the exception that any connection timeout timers on the server SHOULD be reset. On success, the server replies with an `OKAY` response. QUIT Request ------------ Synopsis: QUIT Example: QUIT The client issues a `QUIT` request in order to close the NSCA-ng session. On success, the server replies with an `OKAY` response. The TLS connection is then shut down (cleanly) by both sides. BAIL Request ------------ Synopsis: BAIL ... Example: BAIL I'm feeling bad The client may transmit a `BAIL` request for any reason at any time. An arbitrary, human-readable `` MUST be specified. The TLS connection is then shut down immediately and unconditionally (but cleanly) by both sides. MOIN Response ------------- Synopsis: MOIN Example: MOIN 1 The server accepts a `MOIN` request by sending a `MOIN` response. If the server doesn't support the protocol `` suggested in the client's `MOIN` request, the server MUST either specify a supported protocol `` in the `MOIN` response or generate a `BAIL` response. In the former case, the client MUST either accept the protocol `` suggested in the server's `MOIN` response or generate a `BAIL` request. The protocol `` is a positive decimal number, currently always `1`. PONG Response ------------- Synopsis: PONG Example: PONG 1 The server replies to a `PING` request with a `PONG` response. The protocol `` is a positive decimal number, currently always `1`. The TLS connection is then shut down (cleanly) by both sides. OKAY Response ------------- Synopsis: OKAY Example: OKAY The server acknowledges the current client request or "monitoring command" submission by sending an `OKAY` response. FAIL Response ------------- Synopsis: FAIL ... Example: FAIL You're not authorized to submit this command The server sends a `FAIL` response to reject the current client request or "monitoring command" submission. An arbitrary, human-readable `` MUST be specified. The client then sends a new request. BAIL Response ------------- Synopsis: BAIL ... Example: BAIL I'm feeling horrible The server may transmit a `BAIL` response for any reason at any time. An arbitrary, human-readable `` MUST be specified. The TLS connection is then shut down immediately and unconditionally (but cleanly) by both sides. [1]: http://tools.ietf.org/html/rfc2119 "RFC 2119" [2]: http://tools.ietf.org/html/rfc2246 "RFC 2246" [3]: http://tools.ietf.org/html/rfc4279 "RFC 4279" nsca-ng-1.6/README000066400000000000000000000140031344421036200135630ustar00rootroot00000000000000Welcome to NSCA-ng! =================== The NSCA-ng package provides a client-server pair which makes the "Nagios command file" accessible to remote systems. This allows for submitting passive check results, downtimes, and many other [commands][1] to Nagios (or compatible monitoring solutions). NSCA-ng supports TLS encryption and shared-secret authentication with client-specific passwords (based on [RFC 4279][2]), as well as fine-grained authorization control. Prerequisites ------------- 1. [OpenSSL][3] 1.0.0 or newer is required for building NSCA-ng (as older releases don't support pre-shared key authentication). This is the only hard dependency of the NSCA-ng client. If the OpenSSL version provided by your operating system vendor is too old, you might want to build a private copy of OpenSSL and embed it into NSCA-ng. This could be done by running the `./build-aux/make-openssl` script, which downloads the most recent OpenSSL version and installs it into the NSCA-ng source tree. The `./configure` script (see below) will then pick that up automatically. 2. The NSCA-ng *server* also requires [libConfuse][4] 2.6 or newer. In order to embed a private copy of libConfuse into NSCA-ng, the `./build-aux/make-confuse` script could be run before calling `./configure`. 3. If [libev][5] 4.00 or newer is available and found by the `./configure` script, NSCA-ng will (by default) use it. Otherwise, a bundled copy of libev is embedded into NSCA-ng, so this dependency is optional. 4. Optional [systemd][6] integration code is added to the NSCA-ng *server* if systemd's `sd-daemon(3)` library is found. This can be disabled by specifying the `--without-systemd` option on the `./configure` command line. Installation ------------ If only the client should be built, issuing the following three commands in NSCA-ng's source directory should do the trick: $ ./configure $ make $ su root -c 'make install' This installs the NSCA-ng client into appropriate subdirectories of `/usr/local`. The installation process can be customized by setting environment variables and/or passing options to the `./configure` script. Some of the more frequently used `./configure` options include: * `--enable-server` Build and install the NSCA-ng server (in addition to the client, unless `--disable-client` is specified). * `--disable-client` Don't build and install the NSCA-ng client. * `--disable-posix-aio` Don't use the POSIX AIO API. By default, the NSCA-ng server will use the POSIX AIO API if available. * `--prefix=PATH` Install NSCA-ng into subdirectories of `PATH` instead of `/usr/local`. * `--with-confuse=PATH` Search for the libConfuse header files in `PATH/include`, and search for the libConfuse library files in `PATH/lib`. If this option isn't specified, `./configure` will look for libConfuse in a few typical locations. * `--with-ev=PATH` Search for the libev header files in `PATH/include`, and search for the libev library files in `PATH/lib`. If this option isn't specified, `./configure` will look for libev in a few typical locations; and if no usable version is found, a bundled copy of libev will be embedded into NSCA-ng. In order to force usage of the included copy, `--with-ev=embedded` can be specified; while `--with-ev=external` would disallow falling back to the bundled libev code. * `--with-openssl=PATH` Search for the OpenSSL header files in `PATH/include`, and search for the OpenSSL library files in `PATH/lib`. If this option isn't specified, `./configure` will look for OpenSSL in a few typical locations. For a full list of available options and environment variables, run `./configure --help`. See the file `INSTALL` for detailed installation instructions. Configuration ------------- The NSCA-ng client is configured using the `send_nsca.cfg(5)` file, the NSCA-ng server uses the `nsca-ng.cfg(5)` file. Examples of these files are installed if they don't already exist. > **Important:** Please set the permissions of the configuration files > appropriately to make sure that only authorized users can access them. A script such as `nsca-ng.init` (as provided in the `contrib` directory of this package) could be used to start and stop the NSCA-ng server. Usage ----- Please see the scripts in the `contrib` directory for various usage examples. NSCA Compatibility ------------------ The NSCA-ng client (`send_nsca`) is a drop-in replacement for the `send_nsca` binary provided with the original NSCA 2.x package in the sense that NSCA-ng's `send_nsca` accepts all input, command line arguments, and configuration files accepted by the original `send_nsca`. NSCA-ng clients cannot talk to NSCA servers (nor vice versa), but NSCA and NSCA-ng servers can happily run side by side, and they use different ports by default. Documentation ------------- Detailed information regarding the build and installation process can be found in the file `INSTALL`. The NSCA-ng usage and configuration is documented in the `nsca-ng(8)`, `send_nsca(8)`, `nsca-ng.cfg(5)`, and `send_nsca.cfg(5)` manual pages. The commands `send_nsca -h` and `nsca-ng -h` spit out short summaries of the available command line options. For each release, noteworthy changes are listed in the file `NEWS`. Feature additions which are planned for future releases are added to the `TODO` file. For copyright and license information, see the file `COPYING`. Support ------- Bug reports and patches can be sent to the list (no subscription required). For usage support, please subscribe to the list. See the [NSCA-ng][7] website for details. [1]: http://www.nagios.org/developerinfo/externalcommands/ [2]: http://tools.ietf.org/html/rfc4279 [3]: http://www.openssl.org/ [4]: http://www.nongnu.org/confuse/ [5]: http://libev.schmorp.de/ [6]: http://www.freedesktop.org/wiki/Software/systemd/ [7]: http://www.nsca-ng.org/ nsca-ng-1.6/README.md000077700000000000000000000000001344421036200150372READMEustar00rootroot00000000000000nsca-ng-1.6/THANKS000066400000000000000000000003131344421036200136150ustar00rootroot00000000000000Many thanks go to my employer, Zentraleinrichtung fuer Datenverarbeitung (ZEDAT) at Freie Universitaet Berlin, and especially to Heiko Schlichting, who contributed most of the good ideas behind NSCA-ng. nsca-ng-1.6/TODO000066400000000000000000000050061344421036200133760ustar00rootroot00000000000000NSCA-ng Task List ================= The to-do items are listed in no particular order. Wish List Items for NSCA-ng --------------------------- - Let the server support command authorization based on host and service groups. This requires the server to actually parse the submitted commands, as oppposed to simply matching them against the user-supplied regular expressions. - Let the server support a `clients` or `sources` directive that allows the user to specify one or more subnets (globally and/or per-client). Connections from source addresses outside these subnets should be rejected. - Let the server support proxying of (selected or all) data (with `forward` blocks in the configuration, for example). - Support requests for status and configuration data in order to provide a full-blown remote API. - Let the client execute standard Nagios plugins directly (as an alternative to using a script such as `contrib/invoke_check`), and maybe provide a daemon mode with poor man's check scheduling (i.e., add `check_interval` and `retry_interval` directives to the client configuration). - If the server is not available, let the client queue commands and results using local storage and submit them as soon as the server comes up again. - Let the client talk to multiple servers. - Port the client to Microsoft Windows. - Create a client library with Perl (and maybe Python) bindings. Wish List Items for OpenSSL --------------------------- - Add IPv6 support to OpenSSL's `BIO_s_connect(3)` API, so that the client can use IPv6. (The server supports IPv6 already.) There's a [ticket][1] with a patch in OpenSSL's tracker, and a related [discussion][2] on the OpenSSL development mailing list. - Support NULL encryption TLS-PSK cipher suites as defined in [RFC 4785][3]. This should make it easier to use tools such as `tcpdump(8)` for debugging NSCA-ng sessions. There's an [older][4] and a [newer][5] patch in OpenSSL's tracker. - Support SHA-256/384 (and GCM) TLS-PSK cipher suites as per [RFC 5487][6]. Someone [played around with this][7] already. [1]: http://rt.openssl.org/Ticket/Display.html?id=1365 [2]: http://thread.gmane.org/gmane.comp.encryption.openssl.devel/11207 [3]: http://tools.ietf.org/html/rfc4785 [4]: http://rt.openssl.org/Ticket/Display.html?id=1886 [5]: http://rt.openssl.org/Ticket/Display.html?id=2299 [6]: http://tools.ietf.org/html/rfc5487 [7]: http://permalink.gmane.org/gmane.comp.encryption.openssl.user/44388 nsca-ng-1.6/autogen.sh000077500000000000000000000000551344421036200147060ustar00rootroot00000000000000#!/bin/sh exec autoreconf --force --install nsca-ng-1.6/build-aux/000077500000000000000000000000001344421036200145775ustar00rootroot00000000000000nsca-ng-1.6/build-aux/Makefile.am000066400000000000000000000030041344421036200166300ustar00rootroot00000000000000## Process this file with automake(1) to produce Makefile.in. ## Copyright (c) 2013 Holger Weiss ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1. Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## ## 2. Redistributions in binary form must reproduce the above copyright notice, ## this list of conditions and the following disclaimer in the documentation ## and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE ## LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ## CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF ## SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ## INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ## CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ## ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ## POSSIBILITY OF SUCH DAMAGE. EXTRA_DIST = clang-analyze generate-change-log make-confuse make-openssl man2ps nsca-ng-1.6/build-aux/clang-analyze000077500000000000000000000014111344421036200172470ustar00rootroot00000000000000#!/bin/sh set -e set -u myself=`echo "$0" | sed 's,.*/,,'` say() { echo "$myself: $@." } die() { echo >&2 "$myself: $@." exit 1 } general_args='--analyze' include_args=' -I. -Ilib -Ilib/ev -Ilib/pidfile -Isrc/common -I/usr/local/include -I/usr/pkg/include' definition_args=' -DHAVE_CONFIG_H -DNSCA_VERSION=PACKAGE_VERSION -DSYSCONFDIR="/foo" -DLOCALSTATEDIR="/bar"' test -f 'lib/system.h' \ || die 'Please call me from the NSCA-ng source directory' test -f 'config.h' \ || die "Please run ./configure before calling $0" files=`find 'src' -type 'f' -name '*.c' -print` echo "Letting Clang analyze the following list of files:" echo echo "$files" echo exec clang $general_args $include_args $definition_args $files nsca-ng-1.6/build-aux/generate-change-log000077500000000000000000000043251344421036200203250ustar00rootroot00000000000000#!/usr/bin/env perl use warnings; use strict; use open ':encoding(UTF-8)'; use Encode; use Text::Wrap; # # We'd like to minimize the number of dependencies, otherwise we'd probably use # the Text::Unidecode module instead. # sub asciify { my $text = shift; my %charmap = ( ord "\N{LATIN CAPITAL LETTER A WITH DIAERESIS}" => 'Ae', ord "\N{LATIN CAPITAL LETTER O WITH DIAERESIS}" => 'Oe', ord "\N{LATIN CAPITAL LETTER U WITH DIAERESIS}" => 'Ue', ord "\N{LATIN SMALL LETTER A WITH DIAERESIS}" => 'ae', ord "\N{LATIN SMALL LETTER O WITH DIAERESIS}" => 'oe', ord "\N{LATIN SMALL LETTER U WITH DIAERESIS}" => 'ue', ord "\N{LATIN SMALL LETTER SHARP S}" => 'ss' ); return encode('ascii', $text, sub { my $char = shift; foreach my $key (keys %charmap) { return $charmap{$key} if $key == $char; } return sprintf('', $char); }); } # The lines will have a length of no more than $columns - 1. $Text::Wrap::columns = 81; if (system('git rev-parse --git-dir >/dev/null 2>&1') != 0) { print "Not a Git repository, so I won't update the ChangeLog.\n"; exit 0; } my $regex = '^commit [0-9a-f]+\n' . '^Author: (?.+) <(?.*)>\n' . '^Date: (?\d{4}-\d{2}-\d{2})\n' . '^\n' . '(?(^ .*\n)+)' . '^\n' . '(?(^.+\n)+)'; my $git_log = qx'git log -M -C --stat --name-only --date=short'; die "Cannot get `git log' output\n" if $? != 0; my ($prev_date, $prev_name, $prev_email); while ($git_log =~ /$regex/gm) { my %commit = %+; if (not defined $prev_date or $commit{date} ne $prev_date or $commit{name} ne $prev_name or $commit{email} ne $prev_email) { print $commit{date}, ' '; print asciify($commit{name}), ' '; print '<', $commit{email}, '>', "\n\n"; } $prev_date = $commit{date}; $prev_name = $commit{name}; $prev_email = $commit{email}; my @files = split(/\n/, $commit{files}); my @message = map { s/^ {4}//r } split(/\n/, asciify($commit{message})); my $first_line = shift(@message) =~ s/^$files[-1]: //r; my $intro = sprintf('* %s: %s', join(', ', @files), $first_line); print fill("\t", "\t", $intro), "\n"; foreach my $line (@message) { print "\t$line" if length($line) > 0; print "\n"; } print "\n"; } nsca-ng-1.6/build-aux/make-confuse000077500000000000000000000017571344421036200171140ustar00rootroot00000000000000#!/bin/sh set -e set -u myself=`echo "$0" | sed 's,.*/,,'` say() { echo "$myself: $@." } die() { echo >&2 "$myself: $@." exit 1 } if [ $# -eq 1 ] then version=$1 else version=3.2.2 fi if [ ! -f lib/system.h ] then if [ -f ../lib/system.h ] then cd .. else die 'Please call me from the NSCA-ng source directory' fi fi install_dir=`pwd`/lib/confuse tarball="confuse-$version.tar.gz" if [ ! -f "$tarball" ] then if type curl >/dev/null 2>&1 then get="curl -L -o $tarball" elif type wget >/dev/null 2>&1 then get=wget else say 'Cannot find an HTTP client' die "Please download '$tarball' into `pwd`" fi $get "https://github.com/martinh/libconfuse/releases/download/v$version/$tarball" test -f "$tarball" || die "Downloading '$tarball' failed" fi gzip -c -d "$tarball" | tar xf - cd `expr "$tarball" : '\(.*\)\.tar\.gz$'` ./configure --prefix="$install_dir" --enable-static --disable-shared make make install say 'Success' # vim:set joinspaces noexpandtab textwidth=80: nsca-ng-1.6/build-aux/make-openssl000077500000000000000000000025111344421036200171220ustar00rootroot00000000000000#!/bin/sh set -e set -u myself=`echo "$0" | sed 's,.*/,,'` say() { echo "$myself: $@." } die() { echo >&2 "$myself: $@." exit 1 } found_browser=no if [ ! -f lib/system.h ] then if [ -f ../lib/system.h ] then cd .. else die 'Please call me from the NSCA-ng source directory' fi fi for browser in 'lynx' 'elinks' 'links' do if type `expr "$browser" : '\([^ ]*\)'` >/dev/null 2>&1 && $browser -dump 'https://www.openssl.org/' >/dev/null 2>&1 then found_browser=yes break fi done test "$found_browser" = yes || die 'Cannot find a usable text web browser, please install lynx(1)' install_dir=`pwd`/lib/ssl tarball=`$browser -dump 'https://www.openssl.org/source/' | sed -n 's/.*\(openssl-[1-9].*\.tar\.gz\).*/\1/p' | head -1` tarball='openssl-1.1.1b.tar.gz' if [ ! -f "$tarball" ] then if type curl >/dev/null 2>&1 then get="curl -L -o $tarball" elif type wget >/dev/null 2>&1 then get=wget else say 'Cannot find an HTTP client' die "Please download '$tarball' into `pwd`" fi $get "https://www.openssl.org/source/$tarball" test -f "$tarball" || die "Downloading '$tarball' failed" fi gzip -c -d "$tarball" | tar xf - cd `expr "$tarball" : '\(.*\)\.tar\.gz$'` ./config --prefix="$install_dir" no-shared no-threads make make install say 'Success' # vim:set joinspaces noexpandtab textwidth=80: nsca-ng-1.6/build-aux/man2ps000077500000000000000000000023251344421036200157270ustar00rootroot00000000000000#!/bin/sh set -e set -u heirloom_settings='.\\" Heirloom Settings\ .\ .do xflag 3\ .\ .fp 1 R utrg____ pfb\ .fp 2 I uti_____ pfb\ .fp 3 B utb_____ pfb\ .fp 4 BI utbi____ pfb\ .\ .fp 101 ER uerg____ pfb\ .fp 102 EI uei_____ pfb\ .fp 103 EB ueb_____ pfb\ .fp 104 EBI uebi____ pfb\ .\ .fp 5 CW l047013t pfa\ .fzoom CW .92\ .\ .fallback R ER\ .hidechar R 0123456789\ .flig R ff \\(ff ffi \\(Fi ffl \\(Fl\ .\ .fallback I EI\ .hidechar I 0123456789\ .flig I ff \\(ff ffi \\(Fi ffl \\(Fl\ .\ .fallback B EB\ .hidechar B 0123456789\ .flig B ff \\(ff ffi \\(Fi ffl \\(Fl\ .\ .fallback BI EBI\ .hidechar BI 0123456789\ .flig BI ff \\(ff ffi \\(Fi ffl \\(Fl\ .\ .padj\ .minss 9\ .letadj 95 98 18 105 102\ .\ ' if [ $# -ne 2 ] then echo >&2 "Usage: $0 " exit 2 fi man_file=$1 ps_file=$2 tmp_file='man.tmp' if [ ! -r "$HOME/.fonts/type1/uerg____.pfb" ] then groff -Tps -fN -man "$man_file" >"$ps_file" else # We're probably on Holger's box. PATH="$HOME/opt/heirloom/bin:$PATH" TROFFONTS="$HOME/.fonts/type1" export PATH TROFFONTS sed "s,^\.TH.*,$heirloom_settings&," "$man_file" >"$tmp_file" troff -mg -msafe -man "$tmp_file" | dpost >"$ps_file" rm -f "$tmp_file" fi # vim:set joinspaces noexpandtab textwidth=80: nsca-ng-1.6/configure.ac000066400000000000000000000130621344421036200151750ustar00rootroot00000000000000# Process this file with autoconf(1) to produce a configure script. # Copyright (c) 2013 Holger Weiss # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # Autotools initialization. AC_PREREQ([2.60]) dnl But Autoconf 2.63 is required for AC_INIT's URL parameter. AC_INIT([NSCA-ng], [1.6], [developers@nsca-ng.org], [nsca-ng], [http://www.nsca-ng.org/]) AC_CONFIG_SRCDIR([src/server/nsca-ng.c]) AC_CONFIG_MACRO_DIR([m4]) AC_CONFIG_LIBOBJ_DIR([lib]) AC_CONFIG_AUX_DIR([build-aux]) AC_CONFIG_TESTDIR([tests], [tests:src/client:src/server]) AM_INIT_AUTOMAKE([1.10 -Wall -Werror check-news]) AM_MAINTAINER_MODE([enable]) m4_ifdef([AM_SILENT_RULES], [AM_SILENT_RULES]) dnl Automake 1.11 added this. # Set the release date. RELEASE_DATE='March 19, 2019' AC_SUBST([RELEASE_DATE]) # Check whether to build the client. AC_ARG_ENABLE([client], [AS_HELP_STRING([--enable-client], [build the NSCA-ng client [default: yes]])], [nsca_enable_client=$enable_client], [nsca_enable_client=yes]) AC_MSG_CHECKING([whether the NSCA-ng client should be built]) AS_IF([test "x$nsca_enable_client" = xyes], [AC_MSG_RESULT([yes])], [AC_MSG_RESULT([no])]) # Check whether to build the server. AC_ARG_ENABLE([server], [AS_HELP_STRING([--enable-server], [build the NSCA-ng server [default: no]])], [nsca_enable_server=$enable_server], [nsca_enable_server=no]) AC_MSG_CHECKING([whether the NSCA-ng server should be built]) AS_IF([test "x$nsca_enable_server" = xyes], [AC_MSG_RESULT([yes])], [AC_MSG_RESULT([no])]) # Check whether to use the POSIX AIO API. AC_ARG_ENABLE([posix-aio], [AS_HELP_STRING([--disable-posix-aio], [do not use the POSIX AIO API [default: auto-detect]])], [nsca_enable_posix_aio=$enable_posix_aio], [nsca_enable_posix_aio=yes]) # Bail out if neither the client nor the server should be built. AS_IF([test "x$nsca_enable_client" = xno && test "x$nsca_enable_server" = xno], [AC_MSG_ERROR([Please specify --enable-client and/or --enable-server])]) # Tell Automake whether to build the client and/or server. AM_CONDITIONAL([BUILD_CLIENT], [test "x$nsca_enable_client" = xyes]) AM_CONDITIONAL([BUILD_SERVER], [test "x$nsca_enable_server" = xyes]) # Check for programs. AC_USE_SYSTEM_EXTENSIONS AC_PROG_CC AM_PROG_CC_C_O AC_PROG_CC_STDC AC_PROG_INSTALL AC_PROG_MKDIR_P AC_PROG_RANLIB m4_ifdef([AM_PROG_AR], [AM_PROG_AR]) dnl Automake 1.11.2 added this. AM_CONDITIONAL([GCC], [test "x$GCC" = xyes]) # Check for libraries. NSCA_LIB_NETWORKING NSCA_LIB_EV NSCA_LIB_OPENSSL AS_IF([test "x$nsca_enable_server" = xyes], [NSCA_LIB_CONFUSE NSCA_LIB_SYSTEMD NSCA_LIB_PIDFILE AS_IF([test "x$nsca_enable_posix_aio" = xyes], [NSCA_LIB_AIO])]) # Tell Automake about some of our check results. AM_CONDITIONAL([USE_EMBEDDED_EV], [test "x$nsca_lib_ev_embedded" = xyes]) AM_CONDITIONAL([USE_EMBEDDED_PIDFILE], [test "x$nsca_lib_pidfile_embedded" = xyes]) AM_CONDITIONAL([HAVE_FLOCK], [test "x$nsca_func_flock" = xyes]) # Check for header files. AC_HEADER_STDBOOL AC_CHECK_HEADERS([inttypes.h]) # Check for typedefs, structures, and compiler characteristics. AC_C_INLINE AC_C_RESTRICT AC_TYPE_SIZE_T AS_IF([test "x$nsca_enable_server" = xyes], [AC_TYPE_SSIZE_T AC_TYPE_INTMAX_T AC_TYPE_PID_T]) # Check for library functions. HW_FUNC_VSNPRINTF HW_FUNC_SNPRINTF HW_FUNC_VASPRINTF HW_FUNC_ASPRINTF NSCA_FUNC_PROGNAME AC_REPLACE_FUNCS([strdup strcasecmp strncasecmp]) AS_IF([test "x$nsca_enable_client" = xyes], [AC_CHECK_FUNCS([nanosleep])]) AS_IF([test "x$nsca_enable_server" = xyes], [AC_CHECK_FUNCS([closefrom]) NSCA_FUNC_DAEMON]) # Communicate the PIPE_BUF value to Autotest. AC_COMPUTE_INT([nsca_pipe_buf], [PIPE_BUF], [[#include ]], [nsca_pipe_buf=512]) AC_SUBST([nsca_pipe_buf]) # Spit out the results. AC_CONFIG_HEADERS([config.h]) AC_CONFIG_FILES([ Makefile build-aux/Makefile contrib/Makefile etc/Makefile lib/Makefile lib/ev/Makefile lib/pidfile/Makefile man/Makefile perl/Makefile python/Makefile src/Makefile src/client/Makefile src/common/Makefile src/server/Makefile tests/Makefile tests/atlocal]) AC_OUTPUT AC_MSG_NOTICE([summary of build options: Build NSCA-ng client: $nsca_enable_client Build NSCA-ng server: $nsca_enable_server Use embedded libev: $nsca_lib_ev_embedded Compiler: $CC ]) dnl vim:set joinspaces textwidth=80 filetype=m4: nsca-ng-1.6/contrib/000077500000000000000000000000001344421036200143455ustar00rootroot00000000000000nsca-ng-1.6/contrib/Makefile.am000066400000000000000000000030671344421036200164070ustar00rootroot00000000000000## Process this file with automake(1) to produce Makefile.in. ## Copyright (c) 2013 Holger Weiss ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1. Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## ## 2. Redistributions in binary form must reproduce the above copyright notice, ## this list of conditions and the following disclaimer in the documentation ## and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE ## LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ## CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF ## SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ## INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ## CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ## ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ## POSSIBILITY OF SUCH DAMAGE. EXTRA_DIST = acknowledge debug_server disable_notifications downtime \ enable_notifications invoke_check nsca-ng.init nsca-ng-1.6/contrib/README000066400000000000000000000043411344421036200152270ustar00rootroot00000000000000NSCA-ng's "contrib" Directory ============================= This directory contains a collection of scripts that may be useful. All scripts except for `nsca-ng.init` allow for specifying the path to the `send_nsca.cfg(5)` file via `-c `. Other `send_nsca(8)` options can be specified by setting the environment variable `SEND_NSCA_ARGS`. All scripts print usage information when called with the `-h` option. * `acknowledge` Acknowledges a problem using `send_nsca(8)`. If the `-S` option is specified, a service problem is acknowledged; otherwise, a host problem is acknowledged. Example invocation: $ acknowledge -H www -S HTTP * `debug_server` Opens a raw TLS connection to the `nsca-ng(8)` server, sends any lines read from the standard input, and prints any server responses to the standard output. Requires `s_client(1)` from OpenSSL 1.0.0 or newer, and `xxd(1)`. Example invocation: $ debug_server -c /etc/send_nsca.cfg * `disable_notifications` Globally disables host and service notifications using `send_nsca(8)`. Example invocation: $ disable_notifications * `downtime` Schedules a host or service downtime using `send_nsca(8)`. If the `-S` option is used, a service downtime is scheduled; otherwise, a host downtime is scheduled. The start and end times are specified with the `-s` and `-e` options, respectively. They accept the same date string format as GNU `date(1)'s` `-d` option. Requires GNU `date(1)` or BSD `date(1)`. Example invocation (the `-s` and `-e` options could be omitted here, as these are their default values): $ downtime -H mail -S IMAP -s now -e +2hours * `enable_notifications` Globally enables host and service notifications using `send_nsca(8)`. Example invocation: $ enable_notifications * `invoke_check` Executes standard plugins and transmits their results using `send_nsca(8)`. Example invocation: $ invoke_check check_disk -w 20% -c 10% * `nsca-ng.init` Starts, stops, restarts, or reloads the `nsca-ng(8)` server running on the local system. Example invocation: $ nsca-ng.init start nsca-ng-1.6/contrib/acknowledge000077500000000000000000000026711344421036200165640ustar00rootroot00000000000000#!/bin/sh # # Copyright (c) 2013 Holger Weiss # # This file is free software; Holger Weiss gives unlimited permission to copy # and/or distribute it, with or without modifications, as long as this notice is # preserved. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY, to the extent permitted by law; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. set -e set -u send_nsca_args=${SEND_NSCA_ARGS:+$SEND_NSCA_ARGS} die() { echo >&2 "$@" exit 1 } usage() { die "Usage: $0 [-C ] [-c ] [-H ] [-S ]" } while getopts C:c:H:hS: option do case $option in C) comment=$OPTARG ;; c) send_nsca_args="${send_nsca_args:+$send_nsca_args }-c $OPTARG" ;; H) host=$OPTARG ;; S) service=$OPTARG ;; h|\?) usage ;; esac done shift `expr $OPTIND - 1` test $# -eq 0 || usage host=${host:-`hostname -s`} service=${service:+$service} author=`getent passwd "$USER" | cut -d: -f5` comment=${comment:-"Submitted by send_nsca@`hostname -s`"} if [ -z "$service" ] then # Host acknowledgement. printf '%b' "ACKNOWLEDGE_HOST_PROBLEM;$host;1;0;1;$author;$comment\n" \ | send_nsca -C $send_nsca_args else # Service acknowledgement. printf '%b' "ACKNOWLEDGE_SVC_PROBLEM;$host;$service;1;0;1;$author;$comment\n" \ | send_nsca -C $send_nsca_args fi # vim:set joinspaces noexpandtab textwidth=80: nsca-ng-1.6/contrib/debug_server000077500000000000000000000034511344421036200167520ustar00rootroot00000000000000#!/bin/sh # # Copyright (c) 2013 Holger Weiss # # This file is free software; Holger Weiss gives unlimited permission to copy # and/or distribute it, with or without modifications, as long as this notice is # preserved. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY, to the extent permitted by law; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. set -e set -u default_config_file='/etc/send_nsca.cfg' default_port='5668' die() { echo >&2 "$@" exit 1 } usage() { die "Usage: $0 [-c ] [-H ] [-p ]" } xxd /dev/null 2>&1 || die "$0: xxd(1) is required" while getopts c:H:hp: option do case $option in c) config_file=$OPTARG ;; H) opt_server=$OPTARG ;; h|\?) usage ;; p) opt_port=$OPTARG ;; esac done shift `expr $OPTIND - 1` test $# -eq 0 || usage config_file=${config_file:-$default_config_file} if [ -r "$config_file" ] then eval "`sed 's/[[:space:]]*=[[:space:]]*/=/' "$config_file"`" else echo >&2 "Cannot read $config_file (continuing anyway)" fi server=${server:-'localhost'} server=${opt_server:-$server} port=${port:-$default_port} port=${opt_port:-$port} identity=${identity:-`hostname -s`} password=${password:-'change-me'} ciphers=${tls_ciphers:-'PSK-AES256-CBC-SHA:PSK-AES128-CBC-SHA:PSK-3DES-EDE-CBC-SHA:PSK-RC4-SHA'} exec openssl s_client \ -crlf \ -cipher "$ciphers" \ -psk_identity "$identity" \ -psk `printf '%s' "$password" | xxd -p | tr -d '\n'` \ -connect "$server:$port" # vim:set joinspaces noexpandtab textwidth=80: nsca-ng-1.6/contrib/disable_notifications000077500000000000000000000016471344421036200206370ustar00rootroot00000000000000#!/bin/sh # # Copyright (c) 2013 Holger Weiss # # This file is free software; Holger Weiss gives unlimited permission to copy # and/or distribute it, with or without modifications, as long as this notice is # preserved. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY, to the extent permitted by law; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. set -e set -u send_nsca_args=${SEND_NSCA_ARGS:+$SEND_NSCA_ARGS} die() { echo >&2 "$@" exit 1 } usage() { die "Usage: $0 [-c ]" } while getopts c:h option do case $option in c) send_nsca_args="${send_nsca_args:+$send_nsca_args }-c $OPTARG" ;; h|\?) usage ;; esac done shift `expr $OPTIND - 1` test $# -eq 0 || usage printf '%b' 'DISABLE_NOTIFICATIONS\n' | send_nsca -C $send_nsca_args # vim:set joinspaces noexpandtab textwidth=80: nsca-ng-1.6/contrib/downtime000077500000000000000000000035401344421036200161230ustar00rootroot00000000000000#!/bin/sh # # Copyright (c) 2013 Holger Weiss # # This file is free software; Holger Weiss gives unlimited permission to copy # and/or distribute it, with or without modifications, as long as this notice is # preserved. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY, to the extent permitted by law; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # Note that this script uses non-standard date(1) extensions which aren't # available on all systems. GNU date(1) provides them: # # http://www.gnu.org/software/coreutils/ set -e set -u send_nsca_args=${SEND_NSCA_ARGS:+$SEND_NSCA_ARGS} die() { echo >&2 "$@" exit 1 } usage() { die "Usage: $0 [-C ] [-c ] [-H ] [-S ]" } date -d 'now' '+%s' 2>&1 | grep '^[[:digit:]]*$' >/dev/null \ || die "$0: GNU date(1) or BSD date(1) is required" while getopts C:c:e:H:hS:s: option do case $option in C) comment=$OPTARG ;; c) send_nsca_args="${send_nsca_args:+$send_nsca_args }-c $OPTARG" ;; e) end=$OPTARG ;; H) host=$OPTARG ;; S) service=$OPTARG ;; s) start=$OPTARG ;; h|\?) usage ;; esac done shift `expr $OPTIND - 1` test $# -eq 0 || usage host=${host:-`hostname -s`} service=${service:+$service} start=`date -d ${start:-'now'} '+%s'` end=`date -d ${end:-'+2 hours'} '+%s'` author=`getent passwd "$USER" | cut -d: -f5` comment=${comment:-"Submitted by send_nsca@`hostname -s`"} if [ -z "$service" ] then # Host check. printf '%b' "SCHEDULE_HOST_DOWNTIME;$host;$start;$end;1;0;0;$author;$comment\n" \ | send_nsca -C $send_nsca_args else # Service check. printf '%b' "SCHEDULE_SVC_DOWNTIME;$host;$service;$start;$end;1;0;0;$author;$comment\n" \ | send_nsca -C $send_nsca_args fi # vim:set joinspaces noexpandtab textwidth=80: nsca-ng-1.6/contrib/enable_notifications000077500000000000000000000016461344421036200204610ustar00rootroot00000000000000#!/bin/sh # # Copyright (c) 2013 Holger Weiss # # This file is free software; Holger Weiss gives unlimited permission to copy # and/or distribute it, with or without modifications, as long as this notice is # preserved. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY, to the extent permitted by law; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. set -e set -u send_nsca_args=${SEND_NSCA_ARGS:+$SEND_NSCA_ARGS} die() { echo >&2 "$@" exit 1 } usage() { die "Usage: $0 [-c ]" } while getopts c:h option do case $option in c) send_nsca_args="${send_nsca_args:+$send_nsca_args }-c $OPTARG" ;; h|\?) usage ;; esac done shift `expr $OPTIND - 1` test $# -eq 0 || usage printf '%b' 'ENABLE_NOTIFICATIONS\n' | send_nsca -C $send_nsca_args # vim:set joinspaces noexpandtab textwidth=80: nsca-ng-1.6/contrib/invoke_check000077500000000000000000000025461344421036200167320ustar00rootroot00000000000000#!/bin/sh # # Copyright (c) 2013 Holger Weiss # # This file is free software; Holger Weiss gives unlimited permission to copy # and/or distribute it, with or without modifications, as long as this notice is # preserved. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY, to the extent permitted by law; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. set -u send_nsca_args=${SEND_NSCA_ARGS:+$SEND_NSCA_ARGS} PATH="$PATH:/usr/local/nagios/libexec:/usr/lib/nagios/plugins" export PATH die() { echo >&2 "$@" exit 1 } usage() { die "Usage: $0 [-c ] [-H ] [-S ]" \ " [ ...]" } while getopts c:H:hS: option do case $option in c) send_nsca_args="${send_nsca_args:+$send_nsca_args }-c $OPTARG" ;; H) host=$OPTARG ;; S) service=$OPTARG ;; h|\?) usage ;; esac done shift `expr $OPTIND - 1` test $# -ge 1 || usage host=${host:-`hostname | sed 's+\..*++' | tr '[:upper:]' '[:lower:]'`} service=${service:-`echo "$1" | sed 's+.*[_/]++' | tr '[:lower:]' '[:upper:]'`} output=`"$@"` state=$? test $state -le 3 || die "$0: '$@' yields invalid plugin return code $state" printf '%b' "$host\t$service\t$state\t$output\n" | send_nsca $send_nsca_args # vim:set joinspaces noexpandtab textwidth=80: nsca-ng-1.6/contrib/nsca-ng.init000077500000000000000000000034611344421036200165670ustar00rootroot00000000000000#!/bin/sh ### BEGIN INIT INFO # Provides: nsca-ng # Required-Start: $local_fs $network $remote_fs $syslog # Required-Stop: $local_fs $network $remote_fs $syslog # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: Receive monitoring commands # Description: The NSCA-ng server makes the Nagios command file accessible # from remote systems. ### END INIT INFO PATH='/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin' export PATH name='NSCA-ng' pid_file="$HOME/.nsca-ng.pid" get_pid() { pid=`cat "$pid_file" 2>/dev/null` if expr "X$pid" : 'X[0-9]\{1,\}$' >/dev/null && kill -0 $pid 2>/dev/null then echo "$pid" else rm -f "$pid_file" # In case it was left over. echo 0 fi } pid=`get_pid` case $1 in start) if [ $pid -eq 0 ] then printf 'Starting %s daemon ... ' "$name" nsca-ng -P "$pid_file" && echo 'done.' || echo 'failed.' else echo "$name daemon is already running" fi ;; stop) if [ $pid -ne 0 ] then printf 'Stopping %s daemon ... ' "$name" kill $pid 2>/dev/null && echo 'done.' || echo 'failed.' else echo "$name daemon is already stopped." fi ;; restart) "$0" stop && sleep 1 && "$0" start ;; try-restart) if [ $pid -ne 0 ] then "$0" restart else echo "$name daemon doesn't appear to be running." fi ;; reload|force-reload) if [ $pid -ne 0 ] then printf 'Reloading %s daemon ... ' "$name" kill -1 $pid 2>/dev/null && echo 'done.' || echo 'failed.' else echo "$name daemon is already stopped." fi ;; status) if [ $pid -ne 0 ] then echo "$name daemon appears to be running." else echo "$name daemon does NOT appear to be running." exit 3 fi ;; *) echo >&2 "Usage: $0 {start|stop|restart|try-restart|reload|status}" exit 2 ;; esac exit 0 # vim:set joinspaces noexpandtab textwidth=80: nsca-ng-1.6/etc/000077500000000000000000000000001344421036200134605ustar00rootroot00000000000000nsca-ng-1.6/etc/Makefile.am000066400000000000000000000056031344421036200155200ustar00rootroot00000000000000## Process this file with automake(1) to produce Makefile.in. ## Copyright (c) 2013 Holger Weiss ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1. Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## ## 2. Redistributions in binary form must reproduce the above copyright notice, ## this list of conditions and the following disclaimer in the documentation ## and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE ## LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ## CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF ## SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ## INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ## CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ## ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ## POSSIBILITY OF SUCH DAMAGE. EXTRA_DIST = nsca-ng.cfg nsca-ng.service nsca-ng.socket send_nsca.cfg \ valgrind.supp if BUILD_CLIENT install-data-local: install-nsca-client-conf uninstall-local: uninstall-nsca-client-conf endif if BUILD_SERVER install-data-local: install-nsca-server-conf uninstall-local: uninstall-nsca-server-conf endif # We use "test -r" because Solaris 10 doesn't provide "test -e". install-nsca-client-conf: $(AM_V_at)$(MKDIR_P) '$(DESTDIR)$(sysconfdir)' $(AM_V_at)if [ -r '$(DESTDIR)$(sysconfdir)/send_nsca.cfg' ]; then \ echo 'Preserving the installed send_nsca.cfg file.'; \ else \ $(INSTALL_DATA) '$(srcdir)/send_nsca.cfg' \ '$(DESTDIR)$(sysconfdir)'; \ fi install-nsca-server-conf: $(AM_V_at)$(MKDIR_P) '$(DESTDIR)$(sysconfdir)' $(AM_V_at)if [ -r '$(DESTDIR)$(sysconfdir)/nsca-ng.cfg' ]; then \ echo 'Preserving the installed nsca-ng.cfg file.'; \ else \ $(INSTALL_DATA) '$(srcdir)/nsca-ng.cfg' \ '$(DESTDIR)$(sysconfdir)'; \ fi uninstall-nsca-client-conf: $(AM_V_at)if cmp -s '$(srcdir)/send_nsca.cfg' \ '$(DESTDIR)$(sysconfdir)/send_nsca.cfg'; then \ rm -f '$(DESTDIR)$(sysconfdir)/send_nsca.cfg'; \ else \ echo 'Preserving the installed send_nsca.cfg file.'; \ fi uninstall-nsca-server-conf: $(AM_V_at)if cmp -s '$(srcdir)/nsca-ng.cfg' \ '$(DESTDIR)$(sysconfdir)/nsca-ng.cfg'; then \ rm -f '$(DESTDIR)$(sysconfdir)/nsca-ng.cfg'; \ else \ echo 'Preserving the installed nsca-ng.cfg file.'; \ fi nsca-ng-1.6/etc/nsca-ng.cfg000066400000000000000000000076641344421036200155040ustar00rootroot00000000000000# # Sample configuration for nsca-ng(8). See the nsca-ng.cfg(5) man page. # # PLEASE SET THE PERMISSIONS OF THIS FILE APPROPRIATELY TO MAKE SURE THAT ONLY # AUTHORIZED USERS CAN ACCESS IT! # # # Most probably, you'll have to specify the path to the Nagios command file. # command_file = "/usr/local/nagios/var/rw/nagios.cmd" # # These configuration settings are optional. # # listen = "monitoring.example.com:5668" # Default: "*". # pid_file = "/var/run/nsca-ng.pid" # Default: create no PID file. # temp_directory = "/dev/shm" # Default: "/tmp". # tls_ciphers = "PSK-AES256-CBC-SHA" # Default: see nsca-ng.cfg(5). # chroot = "/usr/local/nagios/var" # Default: don't chroot(2). # user = "nagios" # Default: don't switch user. # log_level = 2 # Default: 3. # max_command_size = 65536 # Default: 16384. # max_queue_size = 128 # Default: 1024. # timeout = 15.0 # Default: 60.0. # # # Clients provide a client ID (think: user name) and a password. The same # ID/password combination may be used by multiple clients. In order to # authorize clients to submit check results and/or other external commands, at # least one "authorize" section must be specified. The client ID (which follows # the "authorize" keyword) may be "*". In this case, the block will be used as # fallback if no section is defined for a given client ID. No other wildcard # characters are available, and "*" has no special meaning unless the client ID # is exactly "*". # # Authorizations are specified using the "commands", "hosts, and/or "services" # variables within an "authorize" section. These variables are (lists of) # extended POSIX regular expressions (see the regex(7) man page), but with an # implicit leading "^" and trailing "$". The "commands" patterns are matched # against the full command string transmitted by the client, except for the # leading bracketed timestamp. The "hosts" and "services" variables are # syntactic sugar, e.g.: # # services = { # "http@web-server", # "disk" # } # # is equivalent to # # commands = { # "PROCESS_SERVICE_CHECK_RESULT;web-server;http;.+;.+", # "PROCESS_SERVICE_CHECK_RESULT;[^;]+;disk;.+;.+" # } # # Some examples: # # Authenticated "root" clients may submit arbitrary check results and any other # monitoring commands. # # authorize "root" { # password = "cM5vBM9CtCWTH1SwnxFEOfp8VAmQq2vd" # commands = ".*" # } # # Authenticated "checker" clients may submit arbitrary check results, but no # other commands. # # authorize "checker" { # password = "s2LDCy4CiK6yrlcHhTXT6agFh067XYE3" # hosts = ".*" # services = ".*" # } # # Authenticated "mail-checker" clients may submit check results for arbitrary # services on hosts whose names begin with "pop", "imap", or "smtp". # # authorize "mail-checker" { # password = "1HOiwYonRoLByCaX6lfY5KDhP484THzV" # services = { # ".+@pop.*", # ".+@imap.*", # ".+@smtp.*" # } # } # # Authenticated "system-checker" clients may submit check results for the # "disk", "swap", and "load" services on arbitrary hosts. # # authorize "system-checker" { # password = "rDCnSMFaM9wb5Yzjd6JwRcvHEwmC9ZlQ" # services = { # "disk", # "swap", # "load" # } # } # # # The "*" section applies when no other section matches the client's identity. # In order to authorize clients to actually submit check results (or other # commands), at least one "commands", "hosts", and/or "services" expression must # be specified. # authorize "*" { password = "change-me" # # The original NSCA server permits all authenticated clients to submit # arbitrary check results. To get this behaviour, enable the following # lines: # # hosts = ".*" # services = ".*" } # # Other files can be included. If a directory is specified, all "*.cfg" and # "*.conf" files within this directory and all subdirectories are included. # # include(nsca-ng.d/included.cfg) # nsca-ng-1.6/etc/nsca-ng.service000066400000000000000000000005341344421036200163720ustar00rootroot00000000000000[Unit] Description=Monitoring Command Acceptor Documentation=man:nsca-ng(8) man:nsca-ng.cfg(5) Requires=nsca-ng.socket [Service] ExecStart=/usr/sbin/nsca-ng Type=notify User=nagios StandardError=syslog NonBlocking=true Restart=on-failure # Don't use this with systemd < 207 (see Red Hat bug #982379): WatchdogSec=30 [Install] Also=nsca-ng.socket nsca-ng-1.6/etc/nsca-ng.socket000066400000000000000000000002431344421036200162170ustar00rootroot00000000000000[Unit] Description=NSCA-ng Socket Documentation=man:nsca-ng(8) man:nsca-ng.cfg(5) [Socket] ListenStream=5668 BindIPv6Only=both [Install] WantedBy=sockets.target nsca-ng-1.6/etc/send_nsca.cfg000066400000000000000000000012671344421036200161040ustar00rootroot00000000000000# # Sample configuration for send_nsca(8). See the send_nsca.cfg(5) man page. # # PLEASE SET THE PERMISSIONS OF THIS FILE APPROPRIATELY TO MAKE SURE THAT ONLY # AUTHORIZED USERS CAN ACCESS IT! # # identity = "web-checker" # Default: `hostname`. # password = "8a5UMsMzZhu6sSPkSmSaqC3HjMGCLwdt" # Default: "change-me". # server = "monitoring.example.com" # Default: "localhost". # tls_ciphers = "PSK-AES256-CBC-SHA" # See send_nsca.cfg(5). # delay = 2 # Default: 0. # port = 5668 # Default: 5668. # timeout = 10 # Default: 15. nsca-ng-1.6/etc/valgrind.supp000066400000000000000000000016101344421036200161750ustar00rootroot00000000000000# CRYPTO_malloc is a malloc(3)-like function. { CRYPTO_malloc Memcheck:Leak fun:malloc fun:CRYPTO_malloc } # Ignore an SSL_accept issue. { SSL_accept Memcheck:Param write(buf) fun:__write_nocancel fun:sock_write fun:BIO_write fun:buffer_ctrl fun:ssl3_accept fun:ssl23_get_client_hello fun:ssl23_accept fun:accept_ssl_cb fun:ev_invoke_pending fun:ev_run fun:main } # Ignore an SSL_write issue. { SSL_write Memcheck:Param write(buf) fun:__write_nocancel fun:sock_write fun:BIO_write fun:ssl3_write_pending fun:ssl3_write_bytes fun:write_cb fun:ev_invoke_pending fun:ev_run fun:main } # We base64-encode random data. See: # # https://groups.google.com/group/comp.unix.programmer/msg/d62a0baba3c78b02 { RAND_pseudo_bytes Memcheck:Value8 fun:EVP_EncodeBlock fun:b64_write fun:BIO_write fun:main } nsca-ng-1.6/lib/000077500000000000000000000000001344421036200134535ustar00rootroot00000000000000nsca-ng-1.6/lib/Makefile.am000066400000000000000000000033531344421036200155130ustar00rootroot00000000000000## Process this file with automake(1) to produce Makefile.in. ## Copyright (c) 2013 Holger Weiss ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1. Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## ## 2. Redistributions in binary form must reproduce the above copyright notice, ## this list of conditions and the following disclaimer in the documentation ## and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE ## LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ## CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF ## SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ## INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ## CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ## ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ## POSSIBILITY OF SUCH DAMAGE. if USE_EMBEDDED_EV MAYBE_EV = ev endif if USE_EMBEDDED_PIDFILE MAYBE_PIDFILE = pidfile endif SUBDIRS = $(MAYBE_EV) $(MAYBE_PIDFILE) AM_CPPFLAGS = -I$(top_srcdir)/src/common # For wrappers.c. noinst_LIBRARIES = libcompat.a libcompat_a_SOURCES = wrappers.c wrappers.h system.h libcompat_a_LIBADD = $(LIBOBJS) nsca-ng-1.6/lib/daemon.c000066400000000000000000000043101344421036200150600ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #if HAVE_CONFIG_H # include #endif #include #include #include #if HAVE_PATHS_H # include #endif #include #include #include "system.h" static int become_child(void) { switch (fork()) { case -1: return -1; case 0: return 0; default: _exit(EXIT_SUCCESS); } } int daemon(int nochdir, int noclose) { int fd; if (become_child() == -1) return -1; if (setsid() == -1) return -1; if (become_child() == -1) return -1; if (!nochdir) (void)chdir("/"); if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) { (void)dup2(fd, STDIN_FILENO); (void)dup2(fd, STDOUT_FILENO); (void)dup2(fd, STDERR_FILENO); if (fd > STDERR_FILENO) (void)close(fd); } return 0; } /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/lib/ev/000077500000000000000000000000001344421036200140655ustar00rootroot00000000000000nsca-ng-1.6/lib/ev/Makefile.am000066400000000000000000000033471344421036200161300ustar00rootroot00000000000000## Process this file with automake(1) to produce Makefile.in. ## Copyright (c) 2013 Holger Weiss ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1. Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## ## 2. Redistributions in binary form must reproduce the above copyright notice, ## this list of conditions and the following disclaimer in the documentation ## and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE ## LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ## CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF ## SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ## INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ## CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ## ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ## POSSIBILITY OF SUCH DAMAGE. # We don't maintain the libev code, so lets ignore any warnings. if GCC AM_CFLAGS = -w endif noinst_LIBRARIES = libev.a libev_a_SOURCES = ev.c ev.h ev_vars.h ev_wrap.h EXTRA_libev_a_SOURCES = ev_epoll.c ev_kqueue.c ev_poll.c ev_port.c ev_select.c \ ev_win32.c EXTRA_DIST = libev.m4 nsca-ng-1.6/lib/ev/ev.c000066400000000000000000003761221344421036200146560ustar00rootroot00000000000000/* * libev event processing core, watcher management * * Copyright (c) 2007-2018 Marc Alexander Lehmann * All rights reserved. * * Redistribution and use in source and binary forms, with or without modifica- * tion, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER- * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH- * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License ("GPL") version 2 or any later version, * in which case the provisions of the GPL are applicable instead of * the above. If you wish to allow the use of your version of this file * only under the terms of the GPL and not to allow others to use your * version of this file under the BSD license, indicate your decision * by deleting the provisions above and replace them with the notice * and other provisions required by the GPL. If you do not delete the * provisions above, a recipient may use your version of this file under * either the BSD or the GPL. */ /* this big block deduces configuration from config.h */ #ifndef EV_STANDALONE # ifdef EV_CONFIG_H # include EV_CONFIG_H # else # include "config.h" # endif # if HAVE_FLOOR # ifndef EV_USE_FLOOR # define EV_USE_FLOOR 1 # endif # endif # if HAVE_CLOCK_SYSCALL # ifndef EV_USE_CLOCK_SYSCALL # define EV_USE_CLOCK_SYSCALL 1 # ifndef EV_USE_REALTIME # define EV_USE_REALTIME 0 # endif # ifndef EV_USE_MONOTONIC # define EV_USE_MONOTONIC 1 # endif # endif # elif !defined EV_USE_CLOCK_SYSCALL # define EV_USE_CLOCK_SYSCALL 0 # endif # if HAVE_CLOCK_GETTIME # ifndef EV_USE_MONOTONIC # define EV_USE_MONOTONIC 1 # endif # ifndef EV_USE_REALTIME # define EV_USE_REALTIME 0 # endif # else # ifndef EV_USE_MONOTONIC # define EV_USE_MONOTONIC 0 # endif # ifndef EV_USE_REALTIME # define EV_USE_REALTIME 0 # endif # endif # if HAVE_NANOSLEEP # ifndef EV_USE_NANOSLEEP # define EV_USE_NANOSLEEP EV_FEATURE_OS # endif # else # undef EV_USE_NANOSLEEP # define EV_USE_NANOSLEEP 0 # endif # if HAVE_SELECT && HAVE_SYS_SELECT_H # ifndef EV_USE_SELECT # define EV_USE_SELECT EV_FEATURE_BACKENDS # endif # else # undef EV_USE_SELECT # define EV_USE_SELECT 0 # endif # if HAVE_POLL && HAVE_POLL_H # ifndef EV_USE_POLL # define EV_USE_POLL EV_FEATURE_BACKENDS # endif # else # undef EV_USE_POLL # define EV_USE_POLL 0 # endif # if HAVE_EPOLL_CTL && HAVE_SYS_EPOLL_H # ifndef EV_USE_EPOLL # define EV_USE_EPOLL EV_FEATURE_BACKENDS # endif # else # undef EV_USE_EPOLL # define EV_USE_EPOLL 0 # endif # if HAVE_KQUEUE && HAVE_SYS_EVENT_H # ifndef EV_USE_KQUEUE # define EV_USE_KQUEUE EV_FEATURE_BACKENDS # endif # else # undef EV_USE_KQUEUE # define EV_USE_KQUEUE 0 # endif # if HAVE_PORT_H && HAVE_PORT_CREATE # ifndef EV_USE_PORT # define EV_USE_PORT EV_FEATURE_BACKENDS # endif # else # undef EV_USE_PORT # define EV_USE_PORT 0 # endif # if HAVE_INOTIFY_INIT && HAVE_SYS_INOTIFY_H # ifndef EV_USE_INOTIFY # define EV_USE_INOTIFY EV_FEATURE_OS # endif # else # undef EV_USE_INOTIFY # define EV_USE_INOTIFY 0 # endif # if HAVE_SIGNALFD && HAVE_SYS_SIGNALFD_H # ifndef EV_USE_SIGNALFD # define EV_USE_SIGNALFD EV_FEATURE_OS # endif # else # undef EV_USE_SIGNALFD # define EV_USE_SIGNALFD 0 # endif # if HAVE_EVENTFD # ifndef EV_USE_EVENTFD # define EV_USE_EVENTFD EV_FEATURE_OS # endif # else # undef EV_USE_EVENTFD # define EV_USE_EVENTFD 0 # endif #endif /* OS X, in its infinite idiocy, actually HARDCODES * a limit of 1024 into their select. Where people have brains, * OS X engineers apparently have a vacuum. Or maybe they were * ordered to have a vacuum, or they do anything for money. * This might help. Or not. * Note that this must be defined early, as other include files * will rely on this define as well. */ #define _DARWIN_UNLIMITED_SELECT 1 #include #include #include #include #include #include #include #include #include #include #include #ifdef EV_H # include EV_H #else # include "ev.h" #endif #if EV_NO_THREADS # undef EV_NO_SMP # define EV_NO_SMP 1 # undef ECB_NO_THREADS # define ECB_NO_THREADS 1 #endif #if EV_NO_SMP # undef EV_NO_SMP # define ECB_NO_SMP 1 #endif #ifndef _WIN32 # include # include # include #else # include # define WIN32_LEAN_AND_MEAN # include # include # ifndef EV_SELECT_IS_WINSOCKET # define EV_SELECT_IS_WINSOCKET 1 # endif # undef EV_AVOID_STDIO #endif /* this block tries to deduce configuration from header-defined symbols and defaults */ /* try to deduce the maximum number of signals on this platform */ #if defined EV_NSIG /* use what's provided */ #elif defined NSIG # define EV_NSIG (NSIG) #elif defined _NSIG # define EV_NSIG (_NSIG) #elif defined SIGMAX # define EV_NSIG (SIGMAX+1) #elif defined SIG_MAX # define EV_NSIG (SIG_MAX+1) #elif defined _SIG_MAX # define EV_NSIG (_SIG_MAX+1) #elif defined MAXSIG # define EV_NSIG (MAXSIG+1) #elif defined MAX_SIG # define EV_NSIG (MAX_SIG+1) #elif defined SIGARRAYSIZE # define EV_NSIG (SIGARRAYSIZE) /* Assume ary[SIGARRAYSIZE] */ #elif defined _sys_nsig # define EV_NSIG (_sys_nsig) /* Solaris 2.5 */ #else # define EV_NSIG (8 * sizeof (sigset_t) + 1) #endif #ifndef EV_USE_FLOOR # define EV_USE_FLOOR 0 #endif #ifndef EV_USE_CLOCK_SYSCALL # if __linux && __GLIBC__ == 2 && __GLIBC_MINOR__ < 17 # define EV_USE_CLOCK_SYSCALL EV_FEATURE_OS # else # define EV_USE_CLOCK_SYSCALL 0 # endif #endif #if !(_POSIX_TIMERS > 0) # ifndef EV_USE_MONOTONIC # define EV_USE_MONOTONIC 0 # endif # ifndef EV_USE_REALTIME # define EV_USE_REALTIME 0 # endif #endif #ifndef EV_USE_MONOTONIC # if defined _POSIX_MONOTONIC_CLOCK && _POSIX_MONOTONIC_CLOCK >= 0 # define EV_USE_MONOTONIC EV_FEATURE_OS # else # define EV_USE_MONOTONIC 0 # endif #endif #ifndef EV_USE_REALTIME # define EV_USE_REALTIME !EV_USE_CLOCK_SYSCALL #endif #ifndef EV_USE_NANOSLEEP # if _POSIX_C_SOURCE >= 199309L # define EV_USE_NANOSLEEP EV_FEATURE_OS # else # define EV_USE_NANOSLEEP 0 # endif #endif #ifndef EV_USE_SELECT # define EV_USE_SELECT EV_FEATURE_BACKENDS #endif #ifndef EV_USE_POLL # ifdef _WIN32 # define EV_USE_POLL 0 # else # define EV_USE_POLL EV_FEATURE_BACKENDS # endif #endif #ifndef EV_USE_EPOLL # if __linux && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 4)) # define EV_USE_EPOLL EV_FEATURE_BACKENDS # else # define EV_USE_EPOLL 0 # endif #endif #ifndef EV_USE_KQUEUE # define EV_USE_KQUEUE 0 #endif #ifndef EV_USE_PORT # define EV_USE_PORT 0 #endif #ifndef EV_USE_INOTIFY # if __linux && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 4)) # define EV_USE_INOTIFY EV_FEATURE_OS # else # define EV_USE_INOTIFY 0 # endif #endif #ifndef EV_PID_HASHSIZE # define EV_PID_HASHSIZE EV_FEATURE_DATA ? 16 : 1 #endif #ifndef EV_INOTIFY_HASHSIZE # define EV_INOTIFY_HASHSIZE EV_FEATURE_DATA ? 16 : 1 #endif #ifndef EV_USE_EVENTFD # if __linux && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 7)) # define EV_USE_EVENTFD EV_FEATURE_OS # else # define EV_USE_EVENTFD 0 # endif #endif #ifndef EV_USE_SIGNALFD # if __linux && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 7)) # define EV_USE_SIGNALFD EV_FEATURE_OS # else # define EV_USE_SIGNALFD 0 # endif #endif #if 0 /* debugging */ # define EV_VERIFY 3 # define EV_USE_4HEAP 1 # define EV_HEAP_CACHE_AT 1 #endif #ifndef EV_VERIFY # define EV_VERIFY (EV_FEATURE_API ? 1 : 0) #endif #ifndef EV_USE_4HEAP # define EV_USE_4HEAP EV_FEATURE_DATA #endif #ifndef EV_HEAP_CACHE_AT # define EV_HEAP_CACHE_AT EV_FEATURE_DATA #endif #ifdef __ANDROID__ /* supposedly, android doesn't typedef fd_mask */ # undef EV_USE_SELECT # define EV_USE_SELECT 0 /* supposedly, we need to include syscall.h, not sys/syscall.h, so just disable */ # undef EV_USE_CLOCK_SYSCALL # define EV_USE_CLOCK_SYSCALL 0 #endif /* aix's poll.h seems to cause lots of trouble */ #ifdef _AIX /* AIX has a completely broken poll.h header */ # undef EV_USE_POLL # define EV_USE_POLL 0 #endif /* on linux, we can use a (slow) syscall to avoid a dependency on pthread, */ /* which makes programs even slower. might work on other unices, too. */ #if EV_USE_CLOCK_SYSCALL # include # ifdef SYS_clock_gettime # define clock_gettime(id, ts) syscall (SYS_clock_gettime, (id), (ts)) # undef EV_USE_MONOTONIC # define EV_USE_MONOTONIC 1 # else # undef EV_USE_CLOCK_SYSCALL # define EV_USE_CLOCK_SYSCALL 0 # endif #endif /* this block fixes any misconfiguration where we know we run into trouble otherwise */ #ifndef CLOCK_MONOTONIC # undef EV_USE_MONOTONIC # define EV_USE_MONOTONIC 0 #endif #ifndef CLOCK_REALTIME # undef EV_USE_REALTIME # define EV_USE_REALTIME 0 #endif #if !EV_STAT_ENABLE # undef EV_USE_INOTIFY # define EV_USE_INOTIFY 0 #endif #if !EV_USE_NANOSLEEP /* hp-ux has it in sys/time.h, which we unconditionally include above */ # if !defined _WIN32 && !defined __hpux # include # endif #endif #if EV_USE_INOTIFY # include # include /* some very old inotify.h headers don't have IN_DONT_FOLLOW */ # ifndef IN_DONT_FOLLOW # undef EV_USE_INOTIFY # define EV_USE_INOTIFY 0 # endif #endif #if EV_USE_EVENTFD /* our minimum requirement is glibc 2.7 which has the stub, but not the header */ # include # ifndef EFD_NONBLOCK # define EFD_NONBLOCK O_NONBLOCK # endif # ifndef EFD_CLOEXEC # ifdef O_CLOEXEC # define EFD_CLOEXEC O_CLOEXEC # else # define EFD_CLOEXEC 02000000 # endif # endif EV_CPP(extern "C") int (eventfd) (unsigned int initval, int flags); #endif #if EV_USE_SIGNALFD /* our minimum requirement is glibc 2.7 which has the stub, but not the header */ # include # ifndef SFD_NONBLOCK # define SFD_NONBLOCK O_NONBLOCK # endif # ifndef SFD_CLOEXEC # ifdef O_CLOEXEC # define SFD_CLOEXEC O_CLOEXEC # else # define SFD_CLOEXEC 02000000 # endif # endif EV_CPP (extern "C") int signalfd (int fd, const sigset_t *mask, int flags); struct signalfd_siginfo { uint32_t ssi_signo; char pad[128 - sizeof (uint32_t)]; }; #endif /**/ #if EV_VERIFY >= 3 # define EV_FREQUENT_CHECK ev_verify (EV_A) #else # define EV_FREQUENT_CHECK do { } while (0) #endif /* * This is used to work around floating point rounding problems. * This value is good at least till the year 4000. */ #define MIN_INTERVAL 0.0001220703125 /* 1/2**13, good till 4000 */ /*#define MIN_INTERVAL 0.00000095367431640625 /* 1/2**20, good till 2200 */ #define MIN_TIMEJUMP 1. /* minimum timejump that gets detected (if monotonic clock available) */ #define MAX_BLOCKTIME 59.743 /* never wait longer than this time (to detect time jumps) */ #define EV_TV_SET(tv,t) do { tv.tv_sec = (long)t; tv.tv_usec = (long)((t - tv.tv_sec) * 1e6); } while (0) #define EV_TS_SET(ts,t) do { ts.tv_sec = (long)t; ts.tv_nsec = (long)((t - ts.tv_sec) * 1e9); } while (0) /* the following is ecb.h embedded into libev - use update_ev_c to update from an external copy */ /* ECB.H BEGIN */ /* * libecb - http://software.schmorp.de/pkg/libecb * * Copyright (©) 2009-2015 Marc Alexander Lehmann * Copyright (©) 2011 Emanuele Giaquinta * All rights reserved. * * Redistribution and use in source and binary forms, with or without modifica- * tion, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER- * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH- * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License ("GPL") version 2 or any later version, * in which case the provisions of the GPL are applicable instead of * the above. If you wish to allow the use of your version of this file * only under the terms of the GPL and not to allow others to use your * version of this file under the BSD license, indicate your decision * by deleting the provisions above and replace them with the notice * and other provisions required by the GPL. If you do not delete the * provisions above, a recipient may use your version of this file under * either the BSD or the GPL. */ #ifndef ECB_H #define ECB_H /* 16 bits major, 16 bits minor */ #define ECB_VERSION 0x00010005 #ifdef _WIN32 typedef signed char int8_t; typedef unsigned char uint8_t; typedef signed short int16_t; typedef unsigned short uint16_t; typedef signed int int32_t; typedef unsigned int uint32_t; #if __GNUC__ typedef signed long long int64_t; typedef unsigned long long uint64_t; #else /* _MSC_VER || __BORLANDC__ */ typedef signed __int64 int64_t; typedef unsigned __int64 uint64_t; #endif #ifdef _WIN64 #define ECB_PTRSIZE 8 typedef uint64_t uintptr_t; typedef int64_t intptr_t; #else #define ECB_PTRSIZE 4 typedef uint32_t uintptr_t; typedef int32_t intptr_t; #endif #else #include #if (defined INTPTR_MAX ? INTPTR_MAX : ULONG_MAX) > 0xffffffffU #define ECB_PTRSIZE 8 #else #define ECB_PTRSIZE 4 #endif #endif #define ECB_GCC_AMD64 (__amd64 || __amd64__ || __x86_64 || __x86_64__) #define ECB_MSVC_AMD64 (_M_AMD64 || _M_X64) /* work around x32 idiocy by defining proper macros */ #if ECB_GCC_AMD64 || ECB_MSVC_AMD64 #if _ILP32 #define ECB_AMD64_X32 1 #else #define ECB_AMD64 1 #endif #endif /* many compilers define _GNUC_ to some versions but then only implement * what their idiot authors think are the "more important" extensions, * causing enormous grief in return for some better fake benchmark numbers. * or so. * we try to detect these and simply assume they are not gcc - if they have * an issue with that they should have done it right in the first place. */ #if !defined __GNUC_MINOR__ || defined __INTEL_COMPILER || defined __SUNPRO_C || defined __SUNPRO_CC || defined __llvm__ || defined __clang__ #define ECB_GCC_VERSION(major,minor) 0 #else #define ECB_GCC_VERSION(major,minor) (__GNUC__ > (major) || (__GNUC__ == (major) && __GNUC_MINOR__ >= (minor))) #endif #define ECB_CLANG_VERSION(major,minor) (__clang_major__ > (major) || (__clang_major__ == (major) && __clang_minor__ >= (minor))) #if __clang__ && defined __has_builtin #define ECB_CLANG_BUILTIN(x) __has_builtin (x) #else #define ECB_CLANG_BUILTIN(x) 0 #endif #if __clang__ && defined __has_extension #define ECB_CLANG_EXTENSION(x) __has_extension (x) #else #define ECB_CLANG_EXTENSION(x) 0 #endif #define ECB_CPP (__cplusplus+0) #define ECB_CPP11 (__cplusplus >= 201103L) #define ECB_CPP14 (__cplusplus >= 201402L) #define ECB_CPP17 (__cplusplus >= 201703L) #if ECB_CPP #define ECB_C 0 #define ECB_STDC_VERSION 0 #else #define ECB_C 1 #define ECB_STDC_VERSION __STDC_VERSION__ #endif #define ECB_C99 (ECB_STDC_VERSION >= 199901L) #define ECB_C11 (ECB_STDC_VERSION >= 201112L) #define ECB_C17 (ECB_STDC_VERSION >= 201710L) #if ECB_CPP #define ECB_EXTERN_C extern "C" #define ECB_EXTERN_C_BEG ECB_EXTERN_C { #define ECB_EXTERN_C_END } #else #define ECB_EXTERN_C extern #define ECB_EXTERN_C_BEG #define ECB_EXTERN_C_END #endif /*****************************************************************************/ /* ECB_NO_THREADS - ecb is not used by multiple threads, ever */ /* ECB_NO_SMP - ecb might be used in multiple threads, but only on a single cpu */ #if ECB_NO_THREADS #define ECB_NO_SMP 1 #endif #if ECB_NO_SMP #define ECB_MEMORY_FENCE do { } while (0) #endif /* http://www-01.ibm.com/support/knowledgecenter/SSGH3R_13.1.0/com.ibm.xlcpp131.aix.doc/compiler_ref/compiler_builtins.html */ #if __xlC__ && ECB_CPP #include #endif #if 1400 <= _MSC_VER #include /* fence functions _ReadBarrier, also bit search functions _BitScanReverse */ #endif #ifndef ECB_MEMORY_FENCE #if ECB_GCC_VERSION(2,5) || defined __INTEL_COMPILER || (__llvm__ && __GNUC__) || __SUNPRO_C >= 0x5110 || __SUNPRO_CC >= 0x5110 #if __i386 || __i386__ #define ECB_MEMORY_FENCE __asm__ __volatile__ ("lock; orb $0, -1(%%esp)" : : : "memory") #define ECB_MEMORY_FENCE_ACQUIRE __asm__ __volatile__ ("" : : : "memory") #define ECB_MEMORY_FENCE_RELEASE __asm__ __volatile__ ("" : : : "memory") #elif ECB_GCC_AMD64 #define ECB_MEMORY_FENCE __asm__ __volatile__ ("mfence" : : : "memory") #define ECB_MEMORY_FENCE_ACQUIRE __asm__ __volatile__ ("" : : : "memory") #define ECB_MEMORY_FENCE_RELEASE __asm__ __volatile__ ("" : : : "memory") #elif __powerpc__ || __ppc__ || __powerpc64__ || __ppc64__ #define ECB_MEMORY_FENCE __asm__ __volatile__ ("sync" : : : "memory") #elif defined __ARM_ARCH_2__ \ || defined __ARM_ARCH_3__ || defined __ARM_ARCH_3M__ \ || defined __ARM_ARCH_4__ || defined __ARM_ARCH_4T__ \ || defined __ARM_ARCH_5__ || defined __ARM_ARCH_5E__ \ || defined __ARM_ARCH_5T__ || defined __ARM_ARCH_5TE__ \ || defined __ARM_ARCH_5TEJ__ /* should not need any, unless running old code on newer cpu - arm doesn't support that */ #elif defined __ARM_ARCH_6__ || defined __ARM_ARCH_6J__ \ || defined __ARM_ARCH_6K__ || defined __ARM_ARCH_6ZK__ \ || defined __ARM_ARCH_6T2__ #define ECB_MEMORY_FENCE __asm__ __volatile__ ("mcr p15,0,%0,c7,c10,5" : : "r" (0) : "memory") #elif defined __ARM_ARCH_7__ || defined __ARM_ARCH_7A__ \ || defined __ARM_ARCH_7R__ || defined __ARM_ARCH_7M__ #define ECB_MEMORY_FENCE __asm__ __volatile__ ("dmb" : : : "memory") #elif __aarch64__ #define ECB_MEMORY_FENCE __asm__ __volatile__ ("dmb ish" : : : "memory") #elif (__sparc || __sparc__) && !(__sparc_v8__ || defined __sparcv8) #define ECB_MEMORY_FENCE __asm__ __volatile__ ("membar #LoadStore | #LoadLoad | #StoreStore | #StoreLoad" : : : "memory") #define ECB_MEMORY_FENCE_ACQUIRE __asm__ __volatile__ ("membar #LoadStore | #LoadLoad" : : : "memory") #define ECB_MEMORY_FENCE_RELEASE __asm__ __volatile__ ("membar #LoadStore | #StoreStore") #elif defined __s390__ || defined __s390x__ #define ECB_MEMORY_FENCE __asm__ __volatile__ ("bcr 15,0" : : : "memory") #elif defined __mips__ /* GNU/Linux emulates sync on mips1 architectures, so we force its use */ /* anybody else who still uses mips1 is supposed to send in their version, with detection code. */ #define ECB_MEMORY_FENCE __asm__ __volatile__ (".set mips2; sync; .set mips0" : : : "memory") #elif defined __alpha__ #define ECB_MEMORY_FENCE __asm__ __volatile__ ("mb" : : : "memory") #elif defined __hppa__ #define ECB_MEMORY_FENCE __asm__ __volatile__ ("" : : : "memory") #define ECB_MEMORY_FENCE_RELEASE __asm__ __volatile__ ("") #elif defined __ia64__ #define ECB_MEMORY_FENCE __asm__ __volatile__ ("mf" : : : "memory") #elif defined __m68k__ #define ECB_MEMORY_FENCE __asm__ __volatile__ ("" : : : "memory") #elif defined __m88k__ #define ECB_MEMORY_FENCE __asm__ __volatile__ ("tb1 0,%%r0,128" : : : "memory") #elif defined __sh__ #define ECB_MEMORY_FENCE __asm__ __volatile__ ("" : : : "memory") #endif #endif #endif #ifndef ECB_MEMORY_FENCE #if ECB_GCC_VERSION(4,7) /* see comment below (stdatomic.h) about the C11 memory model. */ #define ECB_MEMORY_FENCE __atomic_thread_fence (__ATOMIC_SEQ_CST) #define ECB_MEMORY_FENCE_ACQUIRE __atomic_thread_fence (__ATOMIC_ACQUIRE) #define ECB_MEMORY_FENCE_RELEASE __atomic_thread_fence (__ATOMIC_RELEASE) #elif ECB_CLANG_EXTENSION(c_atomic) /* see comment below (stdatomic.h) about the C11 memory model. */ #define ECB_MEMORY_FENCE __c11_atomic_thread_fence (__ATOMIC_SEQ_CST) #define ECB_MEMORY_FENCE_ACQUIRE __c11_atomic_thread_fence (__ATOMIC_ACQUIRE) #define ECB_MEMORY_FENCE_RELEASE __c11_atomic_thread_fence (__ATOMIC_RELEASE) #elif ECB_GCC_VERSION(4,4) || defined __INTEL_COMPILER || defined __clang__ #define ECB_MEMORY_FENCE __sync_synchronize () #elif _MSC_VER >= 1500 /* VC++ 2008 */ /* apparently, microsoft broke all the memory barrier stuff in Visual Studio 2008... */ #pragma intrinsic(_ReadBarrier,_WriteBarrier,_ReadWriteBarrier) #define ECB_MEMORY_FENCE _ReadWriteBarrier (); MemoryBarrier() #define ECB_MEMORY_FENCE_ACQUIRE _ReadWriteBarrier (); MemoryBarrier() /* according to msdn, _ReadBarrier is not a load fence */ #define ECB_MEMORY_FENCE_RELEASE _WriteBarrier (); MemoryBarrier() #elif _MSC_VER >= 1400 /* VC++ 2005 */ #pragma intrinsic(_ReadBarrier,_WriteBarrier,_ReadWriteBarrier) #define ECB_MEMORY_FENCE _ReadWriteBarrier () #define ECB_MEMORY_FENCE_ACQUIRE _ReadWriteBarrier () /* according to msdn, _ReadBarrier is not a load fence */ #define ECB_MEMORY_FENCE_RELEASE _WriteBarrier () #elif defined _WIN32 #include #define ECB_MEMORY_FENCE MemoryBarrier () /* actually just xchg on x86... scary */ #elif __SUNPRO_C >= 0x5110 || __SUNPRO_CC >= 0x5110 #include #define ECB_MEMORY_FENCE __machine_rw_barrier () #define ECB_MEMORY_FENCE_ACQUIRE __machine_r_barrier () #define ECB_MEMORY_FENCE_RELEASE __machine_w_barrier () #elif __xlC__ #define ECB_MEMORY_FENCE __sync () #endif #endif #ifndef ECB_MEMORY_FENCE #if ECB_C11 && !defined __STDC_NO_ATOMICS__ /* we assume that these memory fences work on all variables/all memory accesses, */ /* not just C11 atomics and atomic accesses */ #include /* Unfortunately, neither gcc 4.7 nor clang 3.1 generate any instructions for */ /* any fence other than seq_cst, which isn't very efficient for us. */ /* Why that is, we don't know - either the C11 memory model is quite useless */ /* for most usages, or gcc and clang have a bug */ /* I *currently* lean towards the latter, and inefficiently implement */ /* all three of ecb's fences as a seq_cst fence */ /* Update, gcc-4.8 generates mfence for all c++ fences, but nothing */ /* for all __atomic_thread_fence's except seq_cst */ #define ECB_MEMORY_FENCE atomic_thread_fence (memory_order_seq_cst) #endif #endif #ifndef ECB_MEMORY_FENCE #if !ECB_AVOID_PTHREADS /* * if you get undefined symbol references to pthread_mutex_lock, * or failure to find pthread.h, then you should implement * the ECB_MEMORY_FENCE operations for your cpu/compiler * OR provide pthread.h and link against the posix thread library * of your system. */ #include #define ECB_NEEDS_PTHREADS 1 #define ECB_MEMORY_FENCE_NEEDS_PTHREADS 1 static pthread_mutex_t ecb_mf_lock = PTHREAD_MUTEX_INITIALIZER; #define ECB_MEMORY_FENCE do { pthread_mutex_lock (&ecb_mf_lock); pthread_mutex_unlock (&ecb_mf_lock); } while (0) #endif #endif #if !defined ECB_MEMORY_FENCE_ACQUIRE && defined ECB_MEMORY_FENCE #define ECB_MEMORY_FENCE_ACQUIRE ECB_MEMORY_FENCE #endif #if !defined ECB_MEMORY_FENCE_RELEASE && defined ECB_MEMORY_FENCE #define ECB_MEMORY_FENCE_RELEASE ECB_MEMORY_FENCE #endif /*****************************************************************************/ #if ECB_CPP #define ecb_inline static inline #elif ECB_GCC_VERSION(2,5) #define ecb_inline static __inline__ #elif ECB_C99 #define ecb_inline static inline #else #define ecb_inline static #endif #if ECB_GCC_VERSION(3,3) #define ecb_restrict __restrict__ #elif ECB_C99 #define ecb_restrict restrict #else #define ecb_restrict #endif typedef int ecb_bool; #define ECB_CONCAT_(a, b) a ## b #define ECB_CONCAT(a, b) ECB_CONCAT_(a, b) #define ECB_STRINGIFY_(a) # a #define ECB_STRINGIFY(a) ECB_STRINGIFY_(a) #define ECB_STRINGIFY_EXPR(expr) ((expr), ECB_STRINGIFY_ (expr)) #define ecb_function_ ecb_inline #if ECB_GCC_VERSION(3,1) || ECB_CLANG_VERSION(2,8) #define ecb_attribute(attrlist) __attribute__ (attrlist) #else #define ecb_attribute(attrlist) #endif #if ECB_GCC_VERSION(3,1) || ECB_CLANG_BUILTIN(__builtin_constant_p) #define ecb_is_constant(expr) __builtin_constant_p (expr) #else /* possible C11 impl for integral types typedef struct ecb_is_constant_struct ecb_is_constant_struct; #define ecb_is_constant(expr) _Generic ((1 ? (struct ecb_is_constant_struct *)0 : (void *)((expr) - (expr)), ecb_is_constant_struct *: 0, default: 1)) */ #define ecb_is_constant(expr) 0 #endif #if ECB_GCC_VERSION(3,1) || ECB_CLANG_BUILTIN(__builtin_expect) #define ecb_expect(expr,value) __builtin_expect ((expr),(value)) #else #define ecb_expect(expr,value) (expr) #endif #if ECB_GCC_VERSION(3,1) || ECB_CLANG_BUILTIN(__builtin_prefetch) #define ecb_prefetch(addr,rw,locality) __builtin_prefetch (addr, rw, locality) #else #define ecb_prefetch(addr,rw,locality) #endif /* no emulation for ecb_decltype */ #if ECB_CPP11 // older implementations might have problems with decltype(x)::type, work around it template struct ecb_decltype_t { typedef T type; }; #define ecb_decltype(x) ecb_decltype_t::type #elif ECB_GCC_VERSION(3,0) || ECB_CLANG_VERSION(2,8) #define ecb_decltype(x) __typeof__ (x) #endif #if _MSC_VER >= 1300 #define ecb_deprecated __declspec (deprecated) #else #define ecb_deprecated ecb_attribute ((__deprecated__)) #endif #if _MSC_VER >= 1500 #define ecb_deprecated_message(msg) __declspec (deprecated (msg)) #elif ECB_GCC_VERSION(4,5) #define ecb_deprecated_message(msg) ecb_attribute ((__deprecated__ (msg)) #else #define ecb_deprecated_message(msg) ecb_deprecated #endif #if _MSC_VER >= 1400 #define ecb_noinline __declspec (noinline) #else #define ecb_noinline ecb_attribute ((__noinline__)) #endif #define ecb_unused ecb_attribute ((__unused__)) #define ecb_const ecb_attribute ((__const__)) #define ecb_pure ecb_attribute ((__pure__)) #if ECB_C11 || __IBMC_NORETURN /* http://www-01.ibm.com/support/knowledgecenter/SSGH3R_13.1.0/com.ibm.xlcpp131.aix.doc/language_ref/noreturn.html */ #define ecb_noreturn _Noreturn #elif ECB_CPP11 #define ecb_noreturn [[noreturn]] #elif _MSC_VER >= 1200 /* http://msdn.microsoft.com/en-us/library/k6ktzx3s.aspx */ #define ecb_noreturn __declspec (noreturn) #else #define ecb_noreturn ecb_attribute ((__noreturn__)) #endif #if ECB_GCC_VERSION(4,3) #define ecb_artificial ecb_attribute ((__artificial__)) #define ecb_hot ecb_attribute ((__hot__)) #define ecb_cold ecb_attribute ((__cold__)) #else #define ecb_artificial #define ecb_hot #define ecb_cold #endif /* put around conditional expressions if you are very sure that the */ /* expression is mostly true or mostly false. note that these return */ /* booleans, not the expression. */ #define ecb_expect_false(expr) ecb_expect (!!(expr), 0) #define ecb_expect_true(expr) ecb_expect (!!(expr), 1) /* for compatibility to the rest of the world */ #define ecb_likely(expr) ecb_expect_true (expr) #define ecb_unlikely(expr) ecb_expect_false (expr) /* count trailing zero bits and count # of one bits */ #if ECB_GCC_VERSION(3,4) \ || (ECB_CLANG_BUILTIN(__builtin_clz) && ECB_CLANG_BUILTIN(__builtin_clzll) \ && ECB_CLANG_BUILTIN(__builtin_ctz) && ECB_CLANG_BUILTIN(__builtin_ctzll) \ && ECB_CLANG_BUILTIN(__builtin_popcount)) /* we assume int == 32 bit, long == 32 or 64 bit and long long == 64 bit */ #define ecb_ld32(x) (__builtin_clz (x) ^ 31) #define ecb_ld64(x) (__builtin_clzll (x) ^ 63) #define ecb_ctz32(x) __builtin_ctz (x) #define ecb_ctz64(x) __builtin_ctzll (x) #define ecb_popcount32(x) __builtin_popcount (x) /* no popcountll */ #else ecb_function_ ecb_const int ecb_ctz32 (uint32_t x); ecb_function_ ecb_const int ecb_ctz32 (uint32_t x) { #if 1400 <= _MSC_VER && (_M_IX86 || _M_X64 || _M_IA64 || _M_ARM) unsigned long r; _BitScanForward (&r, x); return (int)r; #else int r = 0; x &= ~x + 1; /* this isolates the lowest bit */ #if ECB_branchless_on_i386 r += !!(x & 0xaaaaaaaa) << 0; r += !!(x & 0xcccccccc) << 1; r += !!(x & 0xf0f0f0f0) << 2; r += !!(x & 0xff00ff00) << 3; r += !!(x & 0xffff0000) << 4; #else if (x & 0xaaaaaaaa) r += 1; if (x & 0xcccccccc) r += 2; if (x & 0xf0f0f0f0) r += 4; if (x & 0xff00ff00) r += 8; if (x & 0xffff0000) r += 16; #endif return r; #endif } ecb_function_ ecb_const int ecb_ctz64 (uint64_t x); ecb_function_ ecb_const int ecb_ctz64 (uint64_t x) { #if 1400 <= _MSC_VER && (_M_X64 || _M_IA64 || _M_ARM) unsigned long r; _BitScanForward64 (&r, x); return (int)r; #else int shift = x & 0xffffffff ? 0 : 32; return ecb_ctz32 (x >> shift) + shift; #endif } ecb_function_ ecb_const int ecb_popcount32 (uint32_t x); ecb_function_ ecb_const int ecb_popcount32 (uint32_t x) { x -= (x >> 1) & 0x55555555; x = ((x >> 2) & 0x33333333) + (x & 0x33333333); x = ((x >> 4) + x) & 0x0f0f0f0f; x *= 0x01010101; return x >> 24; } ecb_function_ ecb_const int ecb_ld32 (uint32_t x); ecb_function_ ecb_const int ecb_ld32 (uint32_t x) { #if 1400 <= _MSC_VER && (_M_IX86 || _M_X64 || _M_IA64 || _M_ARM) unsigned long r; _BitScanReverse (&r, x); return (int)r; #else int r = 0; if (x >> 16) { x >>= 16; r += 16; } if (x >> 8) { x >>= 8; r += 8; } if (x >> 4) { x >>= 4; r += 4; } if (x >> 2) { x >>= 2; r += 2; } if (x >> 1) { r += 1; } return r; #endif } ecb_function_ ecb_const int ecb_ld64 (uint64_t x); ecb_function_ ecb_const int ecb_ld64 (uint64_t x) { #if 1400 <= _MSC_VER && (_M_X64 || _M_IA64 || _M_ARM) unsigned long r; _BitScanReverse64 (&r, x); return (int)r; #else int r = 0; if (x >> 32) { x >>= 32; r += 32; } return r + ecb_ld32 (x); #endif } #endif ecb_function_ ecb_const ecb_bool ecb_is_pot32 (uint32_t x); ecb_function_ ecb_const ecb_bool ecb_is_pot32 (uint32_t x) { return !(x & (x - 1)); } ecb_function_ ecb_const ecb_bool ecb_is_pot64 (uint64_t x); ecb_function_ ecb_const ecb_bool ecb_is_pot64 (uint64_t x) { return !(x & (x - 1)); } ecb_function_ ecb_const uint8_t ecb_bitrev8 (uint8_t x); ecb_function_ ecb_const uint8_t ecb_bitrev8 (uint8_t x) { return ( (x * 0x0802U & 0x22110U) | (x * 0x8020U & 0x88440U)) * 0x10101U >> 16; } ecb_function_ ecb_const uint16_t ecb_bitrev16 (uint16_t x); ecb_function_ ecb_const uint16_t ecb_bitrev16 (uint16_t x) { x = ((x >> 1) & 0x5555) | ((x & 0x5555) << 1); x = ((x >> 2) & 0x3333) | ((x & 0x3333) << 2); x = ((x >> 4) & 0x0f0f) | ((x & 0x0f0f) << 4); x = ( x >> 8 ) | ( x << 8); return x; } ecb_function_ ecb_const uint32_t ecb_bitrev32 (uint32_t x); ecb_function_ ecb_const uint32_t ecb_bitrev32 (uint32_t x) { x = ((x >> 1) & 0x55555555) | ((x & 0x55555555) << 1); x = ((x >> 2) & 0x33333333) | ((x & 0x33333333) << 2); x = ((x >> 4) & 0x0f0f0f0f) | ((x & 0x0f0f0f0f) << 4); x = ((x >> 8) & 0x00ff00ff) | ((x & 0x00ff00ff) << 8); x = ( x >> 16 ) | ( x << 16); return x; } /* popcount64 is only available on 64 bit cpus as gcc builtin */ /* so for this version we are lazy */ ecb_function_ ecb_const int ecb_popcount64 (uint64_t x); ecb_function_ ecb_const int ecb_popcount64 (uint64_t x) { return ecb_popcount32 (x) + ecb_popcount32 (x >> 32); } ecb_inline ecb_const uint8_t ecb_rotl8 (uint8_t x, unsigned int count); ecb_inline ecb_const uint8_t ecb_rotr8 (uint8_t x, unsigned int count); ecb_inline ecb_const uint16_t ecb_rotl16 (uint16_t x, unsigned int count); ecb_inline ecb_const uint16_t ecb_rotr16 (uint16_t x, unsigned int count); ecb_inline ecb_const uint32_t ecb_rotl32 (uint32_t x, unsigned int count); ecb_inline ecb_const uint32_t ecb_rotr32 (uint32_t x, unsigned int count); ecb_inline ecb_const uint64_t ecb_rotl64 (uint64_t x, unsigned int count); ecb_inline ecb_const uint64_t ecb_rotr64 (uint64_t x, unsigned int count); ecb_inline ecb_const uint8_t ecb_rotl8 (uint8_t x, unsigned int count) { return (x >> ( 8 - count)) | (x << count); } ecb_inline ecb_const uint8_t ecb_rotr8 (uint8_t x, unsigned int count) { return (x << ( 8 - count)) | (x >> count); } ecb_inline ecb_const uint16_t ecb_rotl16 (uint16_t x, unsigned int count) { return (x >> (16 - count)) | (x << count); } ecb_inline ecb_const uint16_t ecb_rotr16 (uint16_t x, unsigned int count) { return (x << (16 - count)) | (x >> count); } ecb_inline ecb_const uint32_t ecb_rotl32 (uint32_t x, unsigned int count) { return (x >> (32 - count)) | (x << count); } ecb_inline ecb_const uint32_t ecb_rotr32 (uint32_t x, unsigned int count) { return (x << (32 - count)) | (x >> count); } ecb_inline ecb_const uint64_t ecb_rotl64 (uint64_t x, unsigned int count) { return (x >> (64 - count)) | (x << count); } ecb_inline ecb_const uint64_t ecb_rotr64 (uint64_t x, unsigned int count) { return (x << (64 - count)) | (x >> count); } #if ECB_GCC_VERSION(4,3) || (ECB_CLANG_BUILTIN(__builtin_bswap32) && ECB_CLANG_BUILTIN(__builtin_bswap64)) #if ECB_GCC_VERSION(4,8) || ECB_CLANG_BUILTIN(__builtin_bswap16) #define ecb_bswap16(x) __builtin_bswap16 (x) #else #define ecb_bswap16(x) (__builtin_bswap32 (x) >> 16) #endif #define ecb_bswap32(x) __builtin_bswap32 (x) #define ecb_bswap64(x) __builtin_bswap64 (x) #elif _MSC_VER #include #define ecb_bswap16(x) ((uint16_t)_byteswap_ushort ((uint16_t)(x))) #define ecb_bswap32(x) ((uint32_t)_byteswap_ulong ((uint32_t)(x))) #define ecb_bswap64(x) ((uint64_t)_byteswap_uint64 ((uint64_t)(x))) #else ecb_function_ ecb_const uint16_t ecb_bswap16 (uint16_t x); ecb_function_ ecb_const uint16_t ecb_bswap16 (uint16_t x) { return ecb_rotl16 (x, 8); } ecb_function_ ecb_const uint32_t ecb_bswap32 (uint32_t x); ecb_function_ ecb_const uint32_t ecb_bswap32 (uint32_t x) { return (((uint32_t)ecb_bswap16 (x)) << 16) | ecb_bswap16 (x >> 16); } ecb_function_ ecb_const uint64_t ecb_bswap64 (uint64_t x); ecb_function_ ecb_const uint64_t ecb_bswap64 (uint64_t x) { return (((uint64_t)ecb_bswap32 (x)) << 32) | ecb_bswap32 (x >> 32); } #endif #if ECB_GCC_VERSION(4,5) || ECB_CLANG_BUILTIN(__builtin_unreachable) #define ecb_unreachable() __builtin_unreachable () #else /* this seems to work fine, but gcc always emits a warning for it :/ */ ecb_inline ecb_noreturn void ecb_unreachable (void); ecb_inline ecb_noreturn void ecb_unreachable (void) { } #endif /* try to tell the compiler that some condition is definitely true */ #define ecb_assume(cond) if (!(cond)) ecb_unreachable (); else 0 ecb_inline ecb_const uint32_t ecb_byteorder_helper (void); ecb_inline ecb_const uint32_t ecb_byteorder_helper (void) { /* the union code still generates code under pressure in gcc, */ /* but less than using pointers, and always seems to */ /* successfully return a constant. */ /* the reason why we have this horrible preprocessor mess */ /* is to avoid it in all cases, at least on common architectures */ /* or when using a recent enough gcc version (>= 4.6) */ #if (defined __BYTE_ORDER__ && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) \ || ((__i386 || __i386__ || _M_IX86 || ECB_GCC_AMD64 || ECB_MSVC_AMD64) && !__VOS__) #define ECB_LITTLE_ENDIAN 1 return 0x44332211; #elif (defined __BYTE_ORDER__ && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) \ || ((__AARCH64EB__ || __MIPSEB__ || __ARMEB__) && !__VOS__) #define ECB_BIG_ENDIAN 1 return 0x11223344; #else union { uint8_t c[4]; uint32_t u; } u = { 0x11, 0x22, 0x33, 0x44 }; return u.u; #endif } ecb_inline ecb_const ecb_bool ecb_big_endian (void); ecb_inline ecb_const ecb_bool ecb_big_endian (void) { return ecb_byteorder_helper () == 0x11223344; } ecb_inline ecb_const ecb_bool ecb_little_endian (void); ecb_inline ecb_const ecb_bool ecb_little_endian (void) { return ecb_byteorder_helper () == 0x44332211; } #if ECB_GCC_VERSION(3,0) || ECB_C99 #define ecb_mod(m,n) ((m) % (n) + ((m) % (n) < 0 ? (n) : 0)) #else #define ecb_mod(m,n) ((m) < 0 ? ((n) - 1 - ((-1 - (m)) % (n))) : ((m) % (n))) #endif #if ECB_CPP template static inline T ecb_div_rd (T val, T div) { return val < 0 ? - ((-val + div - 1) / div) : (val ) / div; } template static inline T ecb_div_ru (T val, T div) { return val < 0 ? - ((-val ) / div) : (val + div - 1) / div; } #else #define ecb_div_rd(val,div) ((val) < 0 ? - ((-(val) + (div) - 1) / (div)) : ((val) ) / (div)) #define ecb_div_ru(val,div) ((val) < 0 ? - ((-(val) ) / (div)) : ((val) + (div) - 1) / (div)) #endif #if ecb_cplusplus_does_not_suck /* does not work for local types (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2657.htm) */ template static inline int ecb_array_length (const T (&arr)[N]) { return N; } #else #define ecb_array_length(name) (sizeof (name) / sizeof (name [0])) #endif ecb_function_ ecb_const uint32_t ecb_binary16_to_binary32 (uint32_t x); ecb_function_ ecb_const uint32_t ecb_binary16_to_binary32 (uint32_t x) { unsigned int s = (x & 0x8000) << (31 - 15); int e = (x >> 10) & 0x001f; unsigned int m = x & 0x03ff; if (ecb_expect_false (e == 31)) /* infinity or NaN */ e = 255 - (127 - 15); else if (ecb_expect_false (!e)) { if (ecb_expect_true (!m)) /* zero, handled by code below by forcing e to 0 */ e = 0 - (127 - 15); else { /* subnormal, renormalise */ unsigned int s = 10 - ecb_ld32 (m); m = (m << s) & 0x3ff; /* mask implicit bit */ e -= s - 1; } } /* e and m now are normalised, or zero, (or inf or nan) */ e += 127 - 15; return s | (e << 23) | (m << (23 - 10)); } ecb_function_ ecb_const uint16_t ecb_binary32_to_binary16 (uint32_t x); ecb_function_ ecb_const uint16_t ecb_binary32_to_binary16 (uint32_t x) { unsigned int s = (x >> 16) & 0x00008000; /* sign bit, the easy part */ unsigned int e = ((x >> 23) & 0x000000ff) - (127 - 15); /* the desired exponent */ unsigned int m = x & 0x007fffff; x &= 0x7fffffff; /* if it's within range of binary16 normals, use fast path */ if (ecb_expect_true (0x38800000 <= x && x <= 0x477fefff)) { /* mantissa round-to-even */ m += 0x00000fff + ((m >> (23 - 10)) & 1); /* handle overflow */ if (ecb_expect_false (m >= 0x00800000)) { m >>= 1; e += 1; } return s | (e << 10) | (m >> (23 - 10)); } /* handle large numbers and infinity */ if (ecb_expect_true (0x477fefff < x && x <= 0x7f800000)) return s | 0x7c00; /* handle zero, subnormals and small numbers */ if (ecb_expect_true (x < 0x38800000)) { /* zero */ if (ecb_expect_true (!x)) return s; /* handle subnormals */ /* too small, will be zero */ if (e < (14 - 24)) /* might not be sharp, but is good enough */ return s; m |= 0x00800000; /* make implicit bit explicit */ /* very tricky - we need to round to the nearest e (+10) bit value */ { unsigned int bits = 14 - e; unsigned int half = (1 << (bits - 1)) - 1; unsigned int even = (m >> bits) & 1; /* if this overflows, we will end up with a normalised number */ m = (m + half + even) >> bits; } return s | m; } /* handle NaNs, preserve leftmost nan bits, but make sure we don't turn them into infinities */ m >>= 13; return s | 0x7c00 | m | !m; } /*******************************************************************************/ /* floating point stuff, can be disabled by defining ECB_NO_LIBM */ /* basically, everything uses "ieee pure-endian" floating point numbers */ /* the only noteworthy exception is ancient armle, which uses order 43218765 */ #if 0 \ || __i386 || __i386__ \ || ECB_GCC_AMD64 \ || __powerpc__ || __ppc__ || __powerpc64__ || __ppc64__ \ || defined __s390__ || defined __s390x__ \ || defined __mips__ \ || defined __alpha__ \ || defined __hppa__ \ || defined __ia64__ \ || defined __m68k__ \ || defined __m88k__ \ || defined __sh__ \ || defined _M_IX86 || defined ECB_MSVC_AMD64 || defined _M_IA64 \ || (defined __arm__ && (defined __ARM_EABI__ || defined __EABI__ || defined __VFP_FP__ || defined _WIN32_WCE || defined __ANDROID__)) \ || defined __aarch64__ #define ECB_STDFP 1 #include /* for memcpy */ #else #define ECB_STDFP 0 #endif #ifndef ECB_NO_LIBM #include /* for frexp*, ldexp*, INFINITY, NAN */ /* only the oldest of old doesn't have this one. solaris. */ #ifdef INFINITY #define ECB_INFINITY INFINITY #else #define ECB_INFINITY HUGE_VAL #endif #ifdef NAN #define ECB_NAN NAN #else #define ECB_NAN ECB_INFINITY #endif #if ECB_C99 || _XOPEN_VERSION >= 600 || _POSIX_VERSION >= 200112L #define ecb_ldexpf(x,e) ldexpf ((x), (e)) #define ecb_frexpf(x,e) frexpf ((x), (e)) #else #define ecb_ldexpf(x,e) (float) ldexp ((double) (x), (e)) #define ecb_frexpf(x,e) (float) frexp ((double) (x), (e)) #endif /* convert a float to ieee single/binary32 */ ecb_function_ ecb_const uint32_t ecb_float_to_binary32 (float x); ecb_function_ ecb_const uint32_t ecb_float_to_binary32 (float x) { uint32_t r; #if ECB_STDFP memcpy (&r, &x, 4); #else /* slow emulation, works for anything but -0 */ uint32_t m; int e; if (x == 0e0f ) return 0x00000000U; if (x > +3.40282346638528860e+38f) return 0x7f800000U; if (x < -3.40282346638528860e+38f) return 0xff800000U; if (x != x ) return 0x7fbfffffU; m = ecb_frexpf (x, &e) * 0x1000000U; r = m & 0x80000000U; if (r) m = -m; if (e <= -126) { m &= 0xffffffU; m >>= (-125 - e); e = -126; } r |= (e + 126) << 23; r |= m & 0x7fffffU; #endif return r; } /* converts an ieee single/binary32 to a float */ ecb_function_ ecb_const float ecb_binary32_to_float (uint32_t x); ecb_function_ ecb_const float ecb_binary32_to_float (uint32_t x) { float r; #if ECB_STDFP memcpy (&r, &x, 4); #else /* emulation, only works for normals and subnormals and +0 */ int neg = x >> 31; int e = (x >> 23) & 0xffU; x &= 0x7fffffU; if (e) x |= 0x800000U; else e = 1; /* we distrust ldexpf a bit and do the 2**-24 scaling by an extra multiply */ r = ecb_ldexpf (x * (0.5f / 0x800000U), e - 126); r = neg ? -r : r; #endif return r; } /* convert a double to ieee double/binary64 */ ecb_function_ ecb_const uint64_t ecb_double_to_binary64 (double x); ecb_function_ ecb_const uint64_t ecb_double_to_binary64 (double x) { uint64_t r; #if ECB_STDFP memcpy (&r, &x, 8); #else /* slow emulation, works for anything but -0 */ uint64_t m; int e; if (x == 0e0 ) return 0x0000000000000000U; if (x > +1.79769313486231470e+308) return 0x7ff0000000000000U; if (x < -1.79769313486231470e+308) return 0xfff0000000000000U; if (x != x ) return 0X7ff7ffffffffffffU; m = frexp (x, &e) * 0x20000000000000U; r = m & 0x8000000000000000;; if (r) m = -m; if (e <= -1022) { m &= 0x1fffffffffffffU; m >>= (-1021 - e); e = -1022; } r |= ((uint64_t)(e + 1022)) << 52; r |= m & 0xfffffffffffffU; #endif return r; } /* converts an ieee double/binary64 to a double */ ecb_function_ ecb_const double ecb_binary64_to_double (uint64_t x); ecb_function_ ecb_const double ecb_binary64_to_double (uint64_t x) { double r; #if ECB_STDFP memcpy (&r, &x, 8); #else /* emulation, only works for normals and subnormals and +0 */ int neg = x >> 63; int e = (x >> 52) & 0x7ffU; x &= 0xfffffffffffffU; if (e) x |= 0x10000000000000U; else e = 1; /* we distrust ldexp a bit and do the 2**-53 scaling by an extra multiply */ r = ldexp (x * (0.5 / 0x10000000000000U), e - 1022); r = neg ? -r : r; #endif return r; } /* convert a float to ieee half/binary16 */ ecb_function_ ecb_const uint16_t ecb_float_to_binary16 (float x); ecb_function_ ecb_const uint16_t ecb_float_to_binary16 (float x) { return ecb_binary32_to_binary16 (ecb_float_to_binary32 (x)); } /* convert an ieee half/binary16 to float */ ecb_function_ ecb_const float ecb_binary16_to_float (uint16_t x); ecb_function_ ecb_const float ecb_binary16_to_float (uint16_t x) { return ecb_binary32_to_float (ecb_binary16_to_binary32 (x)); } #endif #endif /* ECB.H END */ #if ECB_MEMORY_FENCE_NEEDS_PTHREADS /* if your architecture doesn't need memory fences, e.g. because it is * single-cpu/core, or if you use libev in a project that doesn't use libev * from multiple threads, then you can define ECB_AVOID_PTHREADS when compiling * libev, in which cases the memory fences become nops. * alternatively, you can remove this #error and link against libpthread, * which will then provide the memory fences. */ # error "memory fences not defined for your architecture, please report" #endif #ifndef ECB_MEMORY_FENCE # define ECB_MEMORY_FENCE do { } while (0) # define ECB_MEMORY_FENCE_ACQUIRE ECB_MEMORY_FENCE # define ECB_MEMORY_FENCE_RELEASE ECB_MEMORY_FENCE #endif #define expect_false(cond) ecb_expect_false (cond) #define expect_true(cond) ecb_expect_true (cond) #define noinline ecb_noinline #define inline_size ecb_inline #if EV_FEATURE_CODE # define inline_speed ecb_inline #else # define inline_speed noinline static #endif #define NUMPRI (EV_MAXPRI - EV_MINPRI + 1) #if EV_MINPRI == EV_MAXPRI # define ABSPRI(w) (((W)w), 0) #else # define ABSPRI(w) (((W)w)->priority - EV_MINPRI) #endif #define EMPTY /* required for microsofts broken pseudo-c compiler */ #define EMPTY2(a,b) /* used to suppress some warnings */ typedef ev_watcher *W; typedef ev_watcher_list *WL; typedef ev_watcher_time *WT; #define ev_active(w) ((W)(w))->active #define ev_at(w) ((WT)(w))->at #if EV_USE_REALTIME /* sig_atomic_t is used to avoid per-thread variables or locking but still */ /* giving it a reasonably high chance of working on typical architectures */ static EV_ATOMIC_T have_realtime; /* did clock_gettime (CLOCK_REALTIME) work? */ #endif #if EV_USE_MONOTONIC static EV_ATOMIC_T have_monotonic; /* did clock_gettime (CLOCK_MONOTONIC) work? */ #endif #ifndef EV_FD_TO_WIN32_HANDLE # define EV_FD_TO_WIN32_HANDLE(fd) _get_osfhandle (fd) #endif #ifndef EV_WIN32_HANDLE_TO_FD # define EV_WIN32_HANDLE_TO_FD(handle) _open_osfhandle (handle, 0) #endif #ifndef EV_WIN32_CLOSE_FD # define EV_WIN32_CLOSE_FD(fd) close (fd) #endif #ifdef _WIN32 # include "ev_win32.c" #endif /*****************************************************************************/ /* define a suitable floor function (only used by periodics atm) */ #if EV_USE_FLOOR # include # define ev_floor(v) floor (v) #else #include /* a floor() replacement function, should be independent of ev_tstamp type */ noinline static ev_tstamp ev_floor (ev_tstamp v) { /* the choice of shift factor is not terribly important */ #if FLT_RADIX != 2 /* assume FLT_RADIX == 10 */ const ev_tstamp shift = sizeof (unsigned long) >= 8 ? 10000000000000000000. : 1000000000.; #else const ev_tstamp shift = sizeof (unsigned long) >= 8 ? 18446744073709551616. : 4294967296.; #endif /* argument too large for an unsigned long? */ if (expect_false (v >= shift)) { ev_tstamp f; if (v == v - 1.) return v; /* very large number */ f = shift * ev_floor (v * (1. / shift)); return f + ev_floor (v - f); } /* special treatment for negative args? */ if (expect_false (v < 0.)) { ev_tstamp f = -ev_floor (-v); return f - (f == v ? 0 : 1); } /* fits into an unsigned long */ return (unsigned long)v; } #endif /*****************************************************************************/ #ifdef __linux # include #endif noinline ecb_cold static unsigned int ev_linux_version (void) { #ifdef __linux unsigned int v = 0; struct utsname buf; int i; char *p = buf.release; if (uname (&buf)) return 0; for (i = 3+1; --i; ) { unsigned int c = 0; for (;;) { if (*p >= '0' && *p <= '9') c = c * 10 + *p++ - '0'; else { p += *p == '.'; break; } } v = (v << 8) | c; } return v; #else return 0; #endif } /*****************************************************************************/ #if EV_AVOID_STDIO noinline ecb_cold static void ev_printerr (const char *msg) { write (STDERR_FILENO, msg, strlen (msg)); } #endif static void (*syserr_cb)(const char *msg) EV_NOEXCEPT; ecb_cold void ev_set_syserr_cb (void (*cb)(const char *msg) EV_NOEXCEPT) EV_NOEXCEPT { syserr_cb = cb; } noinline ecb_cold static void ev_syserr (const char *msg) { if (!msg) msg = "(libev) system error"; if (syserr_cb) syserr_cb (msg); else { #if EV_AVOID_STDIO ev_printerr (msg); ev_printerr (": "); ev_printerr (strerror (errno)); ev_printerr ("\n"); #else perror (msg); #endif abort (); } } static void * ev_realloc_emul (void *ptr, long size) EV_NOEXCEPT { /* some systems, notably openbsd and darwin, fail to properly * implement realloc (x, 0) (as required by both ansi c-89 and * the single unix specification, so work around them here. * recently, also (at least) fedora and debian started breaking it, * despite documenting it otherwise. */ if (size) return realloc (ptr, size); free (ptr); return 0; } static void *(*alloc)(void *ptr, long size) EV_NOEXCEPT = ev_realloc_emul; ecb_cold void ev_set_allocator (void *(*cb)(void *ptr, long size) EV_NOEXCEPT) EV_NOEXCEPT { alloc = cb; } inline_speed void * ev_realloc (void *ptr, long size) { ptr = alloc (ptr, size); if (!ptr && size) { #if EV_AVOID_STDIO ev_printerr ("(libev) memory allocation failed, aborting.\n"); #else fprintf (stderr, "(libev) cannot allocate %ld bytes, aborting.", size); #endif abort (); } return ptr; } #define ev_malloc(size) ev_realloc (0, (size)) #define ev_free(ptr) ev_realloc ((ptr), 0) /*****************************************************************************/ /* set in reify when reification needed */ #define EV_ANFD_REIFY 1 /* file descriptor info structure */ typedef struct { WL head; unsigned char events; /* the events watched for */ unsigned char reify; /* flag set when this ANFD needs reification (EV_ANFD_REIFY, EV__IOFDSET) */ unsigned char emask; /* the epoll backend stores the actual kernel mask in here */ unsigned char unused; #if EV_USE_EPOLL unsigned int egen; /* generation counter to counter epoll bugs */ #endif #if EV_SELECT_IS_WINSOCKET || EV_USE_IOCP SOCKET handle; #endif #if EV_USE_IOCP OVERLAPPED or, ow; #endif } ANFD; /* stores the pending event set for a given watcher */ typedef struct { W w; int events; /* the pending event set for the given watcher */ } ANPENDING; #if EV_USE_INOTIFY /* hash table entry per inotify-id */ typedef struct { WL head; } ANFS; #endif /* Heap Entry */ #if EV_HEAP_CACHE_AT /* a heap element */ typedef struct { ev_tstamp at; WT w; } ANHE; #define ANHE_w(he) (he).w /* access watcher, read-write */ #define ANHE_at(he) (he).at /* access cached at, read-only */ #define ANHE_at_cache(he) (he).at = (he).w->at /* update at from watcher */ #else /* a heap element */ typedef WT ANHE; #define ANHE_w(he) (he) #define ANHE_at(he) (he)->at #define ANHE_at_cache(he) #endif #if EV_MULTIPLICITY struct ev_loop { ev_tstamp ev_rt_now; #define ev_rt_now ((loop)->ev_rt_now) #define VAR(name,decl) decl; #include "ev_vars.h" #undef VAR }; #include "ev_wrap.h" static struct ev_loop default_loop_struct; EV_API_DECL struct ev_loop *ev_default_loop_ptr = 0; /* needs to be initialised to make it a definition despite extern */ #else EV_API_DECL ev_tstamp ev_rt_now = 0; /* needs to be initialised to make it a definition despite extern */ #define VAR(name,decl) static decl; #include "ev_vars.h" #undef VAR static int ev_default_loop_ptr; #endif #if EV_FEATURE_API # define EV_RELEASE_CB if (expect_false (release_cb)) release_cb (EV_A) # define EV_ACQUIRE_CB if (expect_false (acquire_cb)) acquire_cb (EV_A) # define EV_INVOKE_PENDING invoke_cb (EV_A) #else # define EV_RELEASE_CB (void)0 # define EV_ACQUIRE_CB (void)0 # define EV_INVOKE_PENDING ev_invoke_pending (EV_A) #endif #define EVBREAK_RECURSE 0x80 /*****************************************************************************/ #ifndef EV_HAVE_EV_TIME ev_tstamp ev_time (void) EV_NOEXCEPT { #if EV_USE_REALTIME if (expect_true (have_realtime)) { struct timespec ts; clock_gettime (CLOCK_REALTIME, &ts); return ts.tv_sec + ts.tv_nsec * 1e-9; } #endif struct timeval tv; gettimeofday (&tv, 0); return tv.tv_sec + tv.tv_usec * 1e-6; } #endif inline_size ev_tstamp get_clock (void) { #if EV_USE_MONOTONIC if (expect_true (have_monotonic)) { struct timespec ts; clock_gettime (CLOCK_MONOTONIC, &ts); return ts.tv_sec + ts.tv_nsec * 1e-9; } #endif return ev_time (); } #if EV_MULTIPLICITY ev_tstamp ev_now (EV_P) EV_NOEXCEPT { return ev_rt_now; } #endif void ev_sleep (ev_tstamp delay) EV_NOEXCEPT { if (delay > 0.) { #if EV_USE_NANOSLEEP struct timespec ts; EV_TS_SET (ts, delay); nanosleep (&ts, 0); #elif defined _WIN32 /* maybe this should round up, as ms is very low resolution */ /* compared to select (µs) or nanosleep (ns) */ Sleep ((unsigned long)(delay * 1e3)); #else struct timeval tv; /* here we rely on sys/time.h + sys/types.h + unistd.h providing select */ /* something not guaranteed by newer posix versions, but guaranteed */ /* by older ones */ EV_TV_SET (tv, delay); select (0, 0, 0, 0, &tv); #endif } } /*****************************************************************************/ #define MALLOC_ROUND 4096 /* prefer to allocate in chunks of this size, must be 2**n and >> 4 longs */ /* find a suitable new size for the given array, */ /* hopefully by rounding to a nice-to-malloc size */ inline_size int array_nextsize (int elem, int cur, int cnt) { int ncur = cur + 1; do ncur <<= 1; while (cnt > ncur); /* if size is large, round to MALLOC_ROUND - 4 * longs to accommodate malloc overhead */ if (elem * ncur > MALLOC_ROUND - sizeof (void *) * 4) { ncur *= elem; ncur = (ncur + elem + (MALLOC_ROUND - 1) + sizeof (void *) * 4) & ~(MALLOC_ROUND - 1); ncur = ncur - sizeof (void *) * 4; ncur /= elem; } return ncur; } noinline ecb_cold static void * array_realloc (int elem, void *base, int *cur, int cnt) { *cur = array_nextsize (elem, *cur, cnt); return ev_realloc (base, elem * *cur); } #define array_init_zero(base,count) \ memset ((void *)(base), 0, sizeof (*(base)) * (count)) #define array_needsize(type,base,cur,cnt,init) \ if (expect_false ((cnt) > (cur))) \ { \ ecb_unused int ocur_ = (cur); \ (base) = (type *)array_realloc \ (sizeof (type), (base), &(cur), (cnt)); \ init ((base) + (ocur_), (cur) - ocur_); \ } #if 0 #define array_slim(type,stem) \ if (stem ## max < array_roundsize (stem ## cnt >> 2)) \ { \ stem ## max = array_roundsize (stem ## cnt >> 1); \ base = (type *)ev_realloc (base, sizeof (type) * (stem ## max));\ fprintf (stderr, "slimmed down " # stem " to %d\n", stem ## max);/*D*/\ } #endif #define array_free(stem, idx) \ ev_free (stem ## s idx); stem ## cnt idx = stem ## max idx = 0; stem ## s idx = 0 /*****************************************************************************/ /* dummy callback for pending events */ noinline static void pendingcb (EV_P_ ev_prepare *w, int revents) { } noinline void ev_feed_event (EV_P_ void *w, int revents) EV_NOEXCEPT { W w_ = (W)w; int pri = ABSPRI (w_); if (expect_false (w_->pending)) pendings [pri][w_->pending - 1].events |= revents; else { w_->pending = ++pendingcnt [pri]; array_needsize (ANPENDING, pendings [pri], pendingmax [pri], w_->pending, EMPTY2); pendings [pri][w_->pending - 1].w = w_; pendings [pri][w_->pending - 1].events = revents; } pendingpri = NUMPRI - 1; } inline_speed void feed_reverse (EV_P_ W w) { array_needsize (W, rfeeds, rfeedmax, rfeedcnt + 1, EMPTY2); rfeeds [rfeedcnt++] = w; } inline_size void feed_reverse_done (EV_P_ int revents) { do ev_feed_event (EV_A_ rfeeds [--rfeedcnt], revents); while (rfeedcnt); } inline_speed void queue_events (EV_P_ W *events, int eventcnt, int type) { int i; for (i = 0; i < eventcnt; ++i) ev_feed_event (EV_A_ events [i], type); } /*****************************************************************************/ inline_speed void fd_event_nocheck (EV_P_ int fd, int revents) { ANFD *anfd = anfds + fd; ev_io *w; for (w = (ev_io *)anfd->head; w; w = (ev_io *)((WL)w)->next) { int ev = w->events & revents; if (ev) ev_feed_event (EV_A_ (W)w, ev); } } /* do not submit kernel events for fds that have reify set */ /* because that means they changed while we were polling for new events */ inline_speed void fd_event (EV_P_ int fd, int revents) { ANFD *anfd = anfds + fd; if (expect_true (!anfd->reify)) fd_event_nocheck (EV_A_ fd, revents); } void ev_feed_fd_event (EV_P_ int fd, int revents) EV_NOEXCEPT { if (fd >= 0 && fd < anfdmax) fd_event_nocheck (EV_A_ fd, revents); } /* make sure the external fd watch events are in-sync */ /* with the kernel/libev internal state */ inline_size void fd_reify (EV_P) { int i; #if EV_SELECT_IS_WINSOCKET || EV_USE_IOCP for (i = 0; i < fdchangecnt; ++i) { int fd = fdchanges [i]; ANFD *anfd = anfds + fd; if (anfd->reify & EV__IOFDSET && anfd->head) { SOCKET handle = EV_FD_TO_WIN32_HANDLE (fd); if (handle != anfd->handle) { unsigned long arg; assert (("libev: only socket fds supported in this configuration", ioctlsocket (handle, FIONREAD, &arg) == 0)); /* handle changed, but fd didn't - we need to do it in two steps */ backend_modify (EV_A_ fd, anfd->events, 0); anfd->events = 0; anfd->handle = handle; } } } #endif for (i = 0; i < fdchangecnt; ++i) { int fd = fdchanges [i]; ANFD *anfd = anfds + fd; ev_io *w; unsigned char o_events = anfd->events; unsigned char o_reify = anfd->reify; anfd->reify = 0; /*if (expect_true (o_reify & EV_ANFD_REIFY)) probably a deoptimisation */ { anfd->events = 0; for (w = (ev_io *)anfd->head; w; w = (ev_io *)((WL)w)->next) anfd->events |= (unsigned char)w->events; if (o_events != anfd->events) o_reify = EV__IOFDSET; /* actually |= */ } if (o_reify & EV__IOFDSET) backend_modify (EV_A_ fd, o_events, anfd->events); } fdchangecnt = 0; } /* something about the given fd changed */ inline_size void fd_change (EV_P_ int fd, int flags) { unsigned char reify = anfds [fd].reify; anfds [fd].reify |= flags; if (expect_true (!reify)) { ++fdchangecnt; array_needsize (int, fdchanges, fdchangemax, fdchangecnt, EMPTY2); fdchanges [fdchangecnt - 1] = fd; } } /* the given fd is invalid/unusable, so make sure it doesn't hurt us anymore */ inline_speed ecb_cold void fd_kill (EV_P_ int fd) { ev_io *w; while ((w = (ev_io *)anfds [fd].head)) { ev_io_stop (EV_A_ w); ev_feed_event (EV_A_ (W)w, EV_ERROR | EV_READ | EV_WRITE); } } /* check whether the given fd is actually valid, for error recovery */ inline_size ecb_cold int fd_valid (int fd) { #ifdef _WIN32 return EV_FD_TO_WIN32_HANDLE (fd) != -1; #else return fcntl (fd, F_GETFD) != -1; #endif } /* called on EBADF to verify fds */ noinline ecb_cold static void fd_ebadf (EV_P) { int fd; for (fd = 0; fd < anfdmax; ++fd) if (anfds [fd].events) if (!fd_valid (fd) && errno == EBADF) fd_kill (EV_A_ fd); } /* called on ENOMEM in select/poll to kill some fds and retry */ noinline ecb_cold static void fd_enomem (EV_P) { int fd; for (fd = anfdmax; fd--; ) if (anfds [fd].events) { fd_kill (EV_A_ fd); break; } } /* usually called after fork if backend needs to re-arm all fds from scratch */ noinline static void fd_rearm_all (EV_P) { int fd; for (fd = 0; fd < anfdmax; ++fd) if (anfds [fd].events) { anfds [fd].events = 0; anfds [fd].emask = 0; fd_change (EV_A_ fd, EV__IOFDSET | EV_ANFD_REIFY); } } /* used to prepare libev internal fd's */ /* this is not fork-safe */ inline_speed void fd_intern (int fd) { #ifdef _WIN32 unsigned long arg = 1; ioctlsocket (EV_FD_TO_WIN32_HANDLE (fd), FIONBIO, &arg); #else fcntl (fd, F_SETFD, FD_CLOEXEC); fcntl (fd, F_SETFL, O_NONBLOCK); #endif } /*****************************************************************************/ /* * the heap functions want a real array index. array index 0 is guaranteed to not * be in-use at any time. the first heap entry is at array [HEAP0]. DHEAP gives * the branching factor of the d-tree. */ /* * at the moment we allow libev the luxury of two heaps, * a small-code-size 2-heap one and a ~1.5kb larger 4-heap * which is more cache-efficient. * the difference is about 5% with 50000+ watchers. */ #if EV_USE_4HEAP #define DHEAP 4 #define HEAP0 (DHEAP - 1) /* index of first element in heap */ #define HPARENT(k) ((((k) - HEAP0 - 1) / DHEAP) + HEAP0) #define UPHEAP_DONE(p,k) ((p) == (k)) /* away from the root */ inline_speed void downheap (ANHE *heap, int N, int k) { ANHE he = heap [k]; ANHE *E = heap + N + HEAP0; for (;;) { ev_tstamp minat; ANHE *minpos; ANHE *pos = heap + DHEAP * (k - HEAP0) + HEAP0 + 1; /* find minimum child */ if (expect_true (pos + DHEAP - 1 < E)) { /* fast path */ (minpos = pos + 0), (minat = ANHE_at (*minpos)); if ( ANHE_at (pos [1]) < minat) (minpos = pos + 1), (minat = ANHE_at (*minpos)); if ( ANHE_at (pos [2]) < minat) (minpos = pos + 2), (minat = ANHE_at (*minpos)); if ( ANHE_at (pos [3]) < minat) (minpos = pos + 3), (minat = ANHE_at (*minpos)); } else if (pos < E) { /* slow path */ (minpos = pos + 0), (minat = ANHE_at (*minpos)); if (pos + 1 < E && ANHE_at (pos [1]) < minat) (minpos = pos + 1), (minat = ANHE_at (*minpos)); if (pos + 2 < E && ANHE_at (pos [2]) < minat) (minpos = pos + 2), (minat = ANHE_at (*minpos)); if (pos + 3 < E && ANHE_at (pos [3]) < minat) (minpos = pos + 3), (minat = ANHE_at (*minpos)); } else break; if (ANHE_at (he) <= minat) break; heap [k] = *minpos; ev_active (ANHE_w (*minpos)) = k; k = minpos - heap; } heap [k] = he; ev_active (ANHE_w (he)) = k; } #else /* 4HEAP */ #define HEAP0 1 #define HPARENT(k) ((k) >> 1) #define UPHEAP_DONE(p,k) (!(p)) /* away from the root */ inline_speed void downheap (ANHE *heap, int N, int k) { ANHE he = heap [k]; for (;;) { int c = k << 1; if (c >= N + HEAP0) break; c += c + 1 < N + HEAP0 && ANHE_at (heap [c]) > ANHE_at (heap [c + 1]) ? 1 : 0; if (ANHE_at (he) <= ANHE_at (heap [c])) break; heap [k] = heap [c]; ev_active (ANHE_w (heap [k])) = k; k = c; } heap [k] = he; ev_active (ANHE_w (he)) = k; } #endif /* towards the root */ inline_speed void upheap (ANHE *heap, int k) { ANHE he = heap [k]; for (;;) { int p = HPARENT (k); if (UPHEAP_DONE (p, k) || ANHE_at (heap [p]) <= ANHE_at (he)) break; heap [k] = heap [p]; ev_active (ANHE_w (heap [k])) = k; k = p; } heap [k] = he; ev_active (ANHE_w (he)) = k; } /* move an element suitably so it is in a correct place */ inline_size void adjustheap (ANHE *heap, int N, int k) { if (k > HEAP0 && ANHE_at (heap [k]) <= ANHE_at (heap [HPARENT (k)])) upheap (heap, k); else downheap (heap, N, k); } /* rebuild the heap: this function is used only once and executed rarely */ inline_size void reheap (ANHE *heap, int N) { int i; /* we don't use floyds algorithm, upheap is simpler and is more cache-efficient */ /* also, this is easy to implement and correct for both 2-heaps and 4-heaps */ for (i = 0; i < N; ++i) upheap (heap, i + HEAP0); } /*****************************************************************************/ /* associate signal watchers to a signal signal */ typedef struct { EV_ATOMIC_T pending; #if EV_MULTIPLICITY EV_P; #endif WL head; } ANSIG; static ANSIG signals [EV_NSIG - 1]; /*****************************************************************************/ #if EV_SIGNAL_ENABLE || EV_ASYNC_ENABLE noinline ecb_cold static void evpipe_init (EV_P) { if (!ev_is_active (&pipe_w)) { int fds [2]; # if EV_USE_EVENTFD fds [0] = -1; fds [1] = eventfd (0, EFD_NONBLOCK | EFD_CLOEXEC); if (fds [1] < 0 && errno == EINVAL) fds [1] = eventfd (0, 0); if (fds [1] < 0) # endif { while (pipe (fds)) ev_syserr ("(libev) error creating signal/async pipe"); fd_intern (fds [0]); } evpipe [0] = fds [0]; if (evpipe [1] < 0) evpipe [1] = fds [1]; /* first call, set write fd */ else { /* on subsequent calls, do not change evpipe [1] */ /* so that evpipe_write can always rely on its value. */ /* this branch does not do anything sensible on windows, */ /* so must not be executed on windows */ dup2 (fds [1], evpipe [1]); close (fds [1]); } fd_intern (evpipe [1]); ev_io_set (&pipe_w, evpipe [0] < 0 ? evpipe [1] : evpipe [0], EV_READ); ev_io_start (EV_A_ &pipe_w); ev_unref (EV_A); /* watcher should not keep loop alive */ } } inline_speed void evpipe_write (EV_P_ EV_ATOMIC_T *flag) { ECB_MEMORY_FENCE; /* push out the write before this function was called, acquire flag */ if (expect_true (*flag)) return; *flag = 1; ECB_MEMORY_FENCE_RELEASE; /* make sure flag is visible before the wakeup */ pipe_write_skipped = 1; ECB_MEMORY_FENCE; /* make sure pipe_write_skipped is visible before we check pipe_write_wanted */ if (pipe_write_wanted) { int old_errno; pipe_write_skipped = 0; ECB_MEMORY_FENCE_RELEASE; old_errno = errno; /* save errno because write will clobber it */ #if EV_USE_EVENTFD if (evpipe [0] < 0) { uint64_t counter = 1; write (evpipe [1], &counter, sizeof (uint64_t)); } else #endif { #ifdef _WIN32 WSABUF buf; DWORD sent; buf.buf = (char *)&buf; buf.len = 1; WSASend (EV_FD_TO_WIN32_HANDLE (evpipe [1]), &buf, 1, &sent, 0, 0, 0); #else write (evpipe [1], &(evpipe [1]), 1); #endif } errno = old_errno; } } /* called whenever the libev signal pipe */ /* got some events (signal, async) */ static void pipecb (EV_P_ ev_io *iow, int revents) { int i; if (revents & EV_READ) { #if EV_USE_EVENTFD if (evpipe [0] < 0) { uint64_t counter; read (evpipe [1], &counter, sizeof (uint64_t)); } else #endif { char dummy[4]; #ifdef _WIN32 WSABUF buf; DWORD recvd; DWORD flags = 0; buf.buf = dummy; buf.len = sizeof (dummy); WSARecv (EV_FD_TO_WIN32_HANDLE (evpipe [0]), &buf, 1, &recvd, &flags, 0, 0); #else read (evpipe [0], &dummy, sizeof (dummy)); #endif } } pipe_write_skipped = 0; ECB_MEMORY_FENCE; /* push out skipped, acquire flags */ #if EV_SIGNAL_ENABLE if (sig_pending) { sig_pending = 0; ECB_MEMORY_FENCE; for (i = EV_NSIG - 1; i--; ) if (expect_false (signals [i].pending)) ev_feed_signal_event (EV_A_ i + 1); } #endif #if EV_ASYNC_ENABLE if (async_pending) { async_pending = 0; ECB_MEMORY_FENCE; for (i = asynccnt; i--; ) if (asyncs [i]->sent) { asyncs [i]->sent = 0; ECB_MEMORY_FENCE_RELEASE; ev_feed_event (EV_A_ asyncs [i], EV_ASYNC); } } #endif } /*****************************************************************************/ void ev_feed_signal (int signum) EV_NOEXCEPT { #if EV_MULTIPLICITY EV_P; ECB_MEMORY_FENCE_ACQUIRE; EV_A = signals [signum - 1].loop; if (!EV_A) return; #endif signals [signum - 1].pending = 1; evpipe_write (EV_A_ &sig_pending); } static void ev_sighandler (int signum) { #ifdef _WIN32 signal (signum, ev_sighandler); #endif ev_feed_signal (signum); } noinline void ev_feed_signal_event (EV_P_ int signum) EV_NOEXCEPT { WL w; if (expect_false (signum <= 0 || signum >= EV_NSIG)) return; --signum; #if EV_MULTIPLICITY /* it is permissible to try to feed a signal to the wrong loop */ /* or, likely more useful, feeding a signal nobody is waiting for */ if (expect_false (signals [signum].loop != EV_A)) return; #endif signals [signum].pending = 0; ECB_MEMORY_FENCE_RELEASE; for (w = signals [signum].head; w; w = w->next) ev_feed_event (EV_A_ (W)w, EV_SIGNAL); } #if EV_USE_SIGNALFD static void sigfdcb (EV_P_ ev_io *iow, int revents) { struct signalfd_siginfo si[2], *sip; /* these structs are big */ for (;;) { ssize_t res = read (sigfd, si, sizeof (si)); /* not ISO-C, as res might be -1, but works with SuS */ for (sip = si; (char *)sip < (char *)si + res; ++sip) ev_feed_signal_event (EV_A_ sip->ssi_signo); if (res < (ssize_t)sizeof (si)) break; } } #endif #endif /*****************************************************************************/ #if EV_CHILD_ENABLE static WL childs [EV_PID_HASHSIZE]; static ev_signal childev; #ifndef WIFCONTINUED # define WIFCONTINUED(status) 0 #endif /* handle a single child status event */ inline_speed void child_reap (EV_P_ int chain, int pid, int status) { ev_child *w; int traced = WIFSTOPPED (status) || WIFCONTINUED (status); for (w = (ev_child *)childs [chain & ((EV_PID_HASHSIZE) - 1)]; w; w = (ev_child *)((WL)w)->next) { if ((w->pid == pid || !w->pid) && (!traced || (w->flags & 1))) { ev_set_priority (w, EV_MAXPRI); /* need to do it *now*, this *must* be the same prio as the signal watcher itself */ w->rpid = pid; w->rstatus = status; ev_feed_event (EV_A_ (W)w, EV_CHILD); } } } #ifndef WCONTINUED # define WCONTINUED 0 #endif /* called on sigchld etc., calls waitpid */ static void childcb (EV_P_ ev_signal *sw, int revents) { int pid, status; /* some systems define WCONTINUED but then fail to support it (linux 2.4) */ if (0 >= (pid = waitpid (-1, &status, WNOHANG | WUNTRACED | WCONTINUED))) if (!WCONTINUED || errno != EINVAL || 0 >= (pid = waitpid (-1, &status, WNOHANG | WUNTRACED))) return; /* make sure we are called again until all children have been reaped */ /* we need to do it this way so that the callback gets called before we continue */ ev_feed_event (EV_A_ (W)sw, EV_SIGNAL); child_reap (EV_A_ pid, pid, status); if ((EV_PID_HASHSIZE) > 1) child_reap (EV_A_ 0, pid, status); /* this might trigger a watcher twice, but feed_event catches that */ } #endif /*****************************************************************************/ #if EV_USE_IOCP # include "ev_iocp.c" #endif #if EV_USE_PORT # include "ev_port.c" #endif #if EV_USE_KQUEUE # include "ev_kqueue.c" #endif #if EV_USE_EPOLL # include "ev_epoll.c" #endif #if EV_USE_POLL # include "ev_poll.c" #endif #if EV_USE_SELECT # include "ev_select.c" #endif ecb_cold int ev_version_major (void) EV_NOEXCEPT { return EV_VERSION_MAJOR; } ecb_cold int ev_version_minor (void) EV_NOEXCEPT { return EV_VERSION_MINOR; } /* return true if we are running with elevated privileges and should ignore env variables */ inline_size ecb_cold int enable_secure (void) { #ifdef _WIN32 return 0; #else return getuid () != geteuid () || getgid () != getegid (); #endif } ecb_cold unsigned int ev_supported_backends (void) EV_NOEXCEPT { unsigned int flags = 0; if (EV_USE_PORT ) flags |= EVBACKEND_PORT; if (EV_USE_KQUEUE) flags |= EVBACKEND_KQUEUE; if (EV_USE_EPOLL ) flags |= EVBACKEND_EPOLL; if (EV_USE_POLL ) flags |= EVBACKEND_POLL; if (EV_USE_SELECT) flags |= EVBACKEND_SELECT; return flags; } ecb_cold unsigned int ev_recommended_backends (void) EV_NOEXCEPT { unsigned int flags = ev_supported_backends (); #ifndef __NetBSD__ /* kqueue is borked on everything but netbsd apparently */ /* it usually doesn't work correctly on anything but sockets and pipes */ flags &= ~EVBACKEND_KQUEUE; #endif #ifdef __APPLE__ /* only select works correctly on that "unix-certified" platform */ flags &= ~EVBACKEND_KQUEUE; /* horribly broken, even for sockets */ flags &= ~EVBACKEND_POLL; /* poll is based on kqueue from 10.5 onwards */ #endif #ifdef __FreeBSD__ flags &= ~EVBACKEND_POLL; /* poll return value is unusable (http://forums.freebsd.org/archive/index.php/t-10270.html) */ #endif return flags; } ecb_cold unsigned int ev_embeddable_backends (void) EV_NOEXCEPT { int flags = EVBACKEND_EPOLL | EVBACKEND_KQUEUE | EVBACKEND_PORT; /* epoll embeddability broken on all linux versions up to at least 2.6.23 */ if (ev_linux_version () < 0x020620) /* disable it on linux < 2.6.32 */ flags &= ~EVBACKEND_EPOLL; return flags; } unsigned int ev_backend (EV_P) EV_NOEXCEPT { return backend; } #if EV_FEATURE_API unsigned int ev_iteration (EV_P) EV_NOEXCEPT { return loop_count; } unsigned int ev_depth (EV_P) EV_NOEXCEPT { return loop_depth; } void ev_set_io_collect_interval (EV_P_ ev_tstamp interval) EV_NOEXCEPT { io_blocktime = interval; } void ev_set_timeout_collect_interval (EV_P_ ev_tstamp interval) EV_NOEXCEPT { timeout_blocktime = interval; } void ev_set_userdata (EV_P_ void *data) EV_NOEXCEPT { userdata = data; } void * ev_userdata (EV_P) EV_NOEXCEPT { return userdata; } void ev_set_invoke_pending_cb (EV_P_ ev_loop_callback invoke_pending_cb) EV_NOEXCEPT { invoke_cb = invoke_pending_cb; } void ev_set_loop_release_cb (EV_P_ void (*release)(EV_P) EV_NOEXCEPT, void (*acquire)(EV_P) EV_NOEXCEPT) EV_NOEXCEPT { release_cb = release; acquire_cb = acquire; } #endif /* initialise a loop structure, must be zero-initialised */ noinline ecb_cold static void loop_init (EV_P_ unsigned int flags) EV_NOEXCEPT { if (!backend) { origflags = flags; #if EV_USE_REALTIME if (!have_realtime) { struct timespec ts; if (!clock_gettime (CLOCK_REALTIME, &ts)) have_realtime = 1; } #endif #if EV_USE_MONOTONIC if (!have_monotonic) { struct timespec ts; if (!clock_gettime (CLOCK_MONOTONIC, &ts)) have_monotonic = 1; } #endif /* pid check not overridable via env */ #ifndef _WIN32 if (flags & EVFLAG_FORKCHECK) curpid = getpid (); #endif if (!(flags & EVFLAG_NOENV) && !enable_secure () && getenv ("LIBEV_FLAGS")) flags = atoi (getenv ("LIBEV_FLAGS")); ev_rt_now = ev_time (); mn_now = get_clock (); now_floor = mn_now; rtmn_diff = ev_rt_now - mn_now; #if EV_FEATURE_API invoke_cb = ev_invoke_pending; #endif io_blocktime = 0.; timeout_blocktime = 0.; backend = 0; backend_fd = -1; sig_pending = 0; #if EV_ASYNC_ENABLE async_pending = 0; #endif pipe_write_skipped = 0; pipe_write_wanted = 0; evpipe [0] = -1; evpipe [1] = -1; #if EV_USE_INOTIFY fs_fd = flags & EVFLAG_NOINOTIFY ? -1 : -2; #endif #if EV_USE_SIGNALFD sigfd = flags & EVFLAG_SIGNALFD ? -2 : -1; #endif if (!(flags & EVBACKEND_MASK)) flags |= ev_recommended_backends (); #if EV_USE_IOCP if (!backend && (flags & EVBACKEND_IOCP )) backend = iocp_init (EV_A_ flags); #endif #if EV_USE_PORT if (!backend && (flags & EVBACKEND_PORT )) backend = port_init (EV_A_ flags); #endif #if EV_USE_KQUEUE if (!backend && (flags & EVBACKEND_KQUEUE)) backend = kqueue_init (EV_A_ flags); #endif #if EV_USE_EPOLL if (!backend && (flags & EVBACKEND_EPOLL )) backend = epoll_init (EV_A_ flags); #endif #if EV_USE_POLL if (!backend && (flags & EVBACKEND_POLL )) backend = poll_init (EV_A_ flags); #endif #if EV_USE_SELECT if (!backend && (flags & EVBACKEND_SELECT)) backend = select_init (EV_A_ flags); #endif ev_prepare_init (&pending_w, pendingcb); #if EV_SIGNAL_ENABLE || EV_ASYNC_ENABLE ev_init (&pipe_w, pipecb); ev_set_priority (&pipe_w, EV_MAXPRI); #endif } } /* free up a loop structure */ ecb_cold void ev_loop_destroy (EV_P) { int i; #if EV_MULTIPLICITY /* mimic free (0) */ if (!EV_A) return; #endif #if EV_CLEANUP_ENABLE /* queue cleanup watchers (and execute them) */ if (expect_false (cleanupcnt)) { queue_events (EV_A_ (W *)cleanups, cleanupcnt, EV_CLEANUP); EV_INVOKE_PENDING; } #endif #if EV_CHILD_ENABLE if (ev_is_default_loop (EV_A) && ev_is_active (&childev)) { ev_ref (EV_A); /* child watcher */ ev_signal_stop (EV_A_ &childev); } #endif if (ev_is_active (&pipe_w)) { /*ev_ref (EV_A);*/ /*ev_io_stop (EV_A_ &pipe_w);*/ if (evpipe [0] >= 0) EV_WIN32_CLOSE_FD (evpipe [0]); if (evpipe [1] >= 0) EV_WIN32_CLOSE_FD (evpipe [1]); } #if EV_USE_SIGNALFD if (ev_is_active (&sigfd_w)) close (sigfd); #endif #if EV_USE_INOTIFY if (fs_fd >= 0) close (fs_fd); #endif if (backend_fd >= 0) close (backend_fd); #if EV_USE_IOCP if (backend == EVBACKEND_IOCP ) iocp_destroy (EV_A); #endif #if EV_USE_PORT if (backend == EVBACKEND_PORT ) port_destroy (EV_A); #endif #if EV_USE_KQUEUE if (backend == EVBACKEND_KQUEUE) kqueue_destroy (EV_A); #endif #if EV_USE_EPOLL if (backend == EVBACKEND_EPOLL ) epoll_destroy (EV_A); #endif #if EV_USE_POLL if (backend == EVBACKEND_POLL ) poll_destroy (EV_A); #endif #if EV_USE_SELECT if (backend == EVBACKEND_SELECT) select_destroy (EV_A); #endif for (i = NUMPRI; i--; ) { array_free (pending, [i]); #if EV_IDLE_ENABLE array_free (idle, [i]); #endif } ev_free (anfds); anfds = 0; anfdmax = 0; /* have to use the microsoft-never-gets-it-right macro */ array_free (rfeed, EMPTY); array_free (fdchange, EMPTY); array_free (timer, EMPTY); #if EV_PERIODIC_ENABLE array_free (periodic, EMPTY); #endif #if EV_FORK_ENABLE array_free (fork, EMPTY); #endif #if EV_CLEANUP_ENABLE array_free (cleanup, EMPTY); #endif array_free (prepare, EMPTY); array_free (check, EMPTY); #if EV_ASYNC_ENABLE array_free (async, EMPTY); #endif backend = 0; #if EV_MULTIPLICITY if (ev_is_default_loop (EV_A)) #endif ev_default_loop_ptr = 0; #if EV_MULTIPLICITY else ev_free (EV_A); #endif } #if EV_USE_INOTIFY inline_size void infy_fork (EV_P); #endif inline_size void loop_fork (EV_P) { #if EV_USE_PORT if (backend == EVBACKEND_PORT ) port_fork (EV_A); #endif #if EV_USE_KQUEUE if (backend == EVBACKEND_KQUEUE) kqueue_fork (EV_A); #endif #if EV_USE_EPOLL if (backend == EVBACKEND_EPOLL ) epoll_fork (EV_A); #endif #if EV_USE_INOTIFY infy_fork (EV_A); #endif #if EV_SIGNAL_ENABLE || EV_ASYNC_ENABLE if (ev_is_active (&pipe_w) && postfork != 2) { /* pipe_write_wanted must be false now, so modifying fd vars should be safe */ ev_ref (EV_A); ev_io_stop (EV_A_ &pipe_w); if (evpipe [0] >= 0) EV_WIN32_CLOSE_FD (evpipe [0]); evpipe_init (EV_A); /* iterate over everything, in case we missed something before */ ev_feed_event (EV_A_ &pipe_w, EV_CUSTOM); } #endif postfork = 0; } #if EV_MULTIPLICITY ecb_cold struct ev_loop * ev_loop_new (unsigned int flags) EV_NOEXCEPT { EV_P = (struct ev_loop *)ev_malloc (sizeof (struct ev_loop)); memset (EV_A, 0, sizeof (struct ev_loop)); loop_init (EV_A_ flags); if (ev_backend (EV_A)) return EV_A; ev_free (EV_A); return 0; } #endif /* multiplicity */ #if EV_VERIFY noinline ecb_cold static void verify_watcher (EV_P_ W w) { assert (("libev: watcher has invalid priority", ABSPRI (w) >= 0 && ABSPRI (w) < NUMPRI)); if (w->pending) assert (("libev: pending watcher not on pending queue", pendings [ABSPRI (w)][w->pending - 1].w == w)); } noinline ecb_cold static void verify_heap (EV_P_ ANHE *heap, int N) { int i; for (i = HEAP0; i < N + HEAP0; ++i) { assert (("libev: active index mismatch in heap", ev_active (ANHE_w (heap [i])) == i)); assert (("libev: heap condition violated", i == HEAP0 || ANHE_at (heap [HPARENT (i)]) <= ANHE_at (heap [i]))); assert (("libev: heap at cache mismatch", ANHE_at (heap [i]) == ev_at (ANHE_w (heap [i])))); verify_watcher (EV_A_ (W)ANHE_w (heap [i])); } } noinline ecb_cold static void array_verify (EV_P_ W *ws, int cnt) { while (cnt--) { assert (("libev: active index mismatch", ev_active (ws [cnt]) == cnt + 1)); verify_watcher (EV_A_ ws [cnt]); } } #endif #if EV_FEATURE_API void ecb_cold ev_verify (EV_P) EV_NOEXCEPT { #if EV_VERIFY int i; WL w, w2; assert (activecnt >= -1); assert (fdchangemax >= fdchangecnt); for (i = 0; i < fdchangecnt; ++i) assert (("libev: negative fd in fdchanges", fdchanges [i] >= 0)); assert (anfdmax >= 0); for (i = 0; i < anfdmax; ++i) { int j = 0; for (w = w2 = anfds [i].head; w; w = w->next) { verify_watcher (EV_A_ (W)w); if (j++ & 1) { assert (("libev: io watcher list contains a loop", w != w2)); w2 = w2->next; } assert (("libev: inactive fd watcher on anfd list", ev_active (w) == 1)); assert (("libev: fd mismatch between watcher and anfd", ((ev_io *)w)->fd == i)); } } assert (timermax >= timercnt); verify_heap (EV_A_ timers, timercnt); #if EV_PERIODIC_ENABLE assert (periodicmax >= periodiccnt); verify_heap (EV_A_ periodics, periodiccnt); #endif for (i = NUMPRI; i--; ) { assert (pendingmax [i] >= pendingcnt [i]); #if EV_IDLE_ENABLE assert (idleall >= 0); assert (idlemax [i] >= idlecnt [i]); array_verify (EV_A_ (W *)idles [i], idlecnt [i]); #endif } #if EV_FORK_ENABLE assert (forkmax >= forkcnt); array_verify (EV_A_ (W *)forks, forkcnt); #endif #if EV_CLEANUP_ENABLE assert (cleanupmax >= cleanupcnt); array_verify (EV_A_ (W *)cleanups, cleanupcnt); #endif #if EV_ASYNC_ENABLE assert (asyncmax >= asynccnt); array_verify (EV_A_ (W *)asyncs, asynccnt); #endif #if EV_PREPARE_ENABLE assert (preparemax >= preparecnt); array_verify (EV_A_ (W *)prepares, preparecnt); #endif #if EV_CHECK_ENABLE assert (checkmax >= checkcnt); array_verify (EV_A_ (W *)checks, checkcnt); #endif # if 0 #if EV_CHILD_ENABLE for (w = (ev_child *)childs [chain & ((EV_PID_HASHSIZE) - 1)]; w; w = (ev_child *)((WL)w)->next) for (signum = EV_NSIG; signum--; ) if (signals [signum].pending) #endif # endif #endif } #endif #if EV_MULTIPLICITY ecb_cold struct ev_loop * #else int #endif ev_default_loop (unsigned int flags) EV_NOEXCEPT { if (!ev_default_loop_ptr) { #if EV_MULTIPLICITY EV_P = ev_default_loop_ptr = &default_loop_struct; #else ev_default_loop_ptr = 1; #endif loop_init (EV_A_ flags); if (ev_backend (EV_A)) { #if EV_CHILD_ENABLE ev_signal_init (&childev, childcb, SIGCHLD); ev_set_priority (&childev, EV_MAXPRI); ev_signal_start (EV_A_ &childev); ev_unref (EV_A); /* child watcher should not keep loop alive */ #endif } else ev_default_loop_ptr = 0; } return ev_default_loop_ptr; } void ev_loop_fork (EV_P) EV_NOEXCEPT { postfork = 1; } /*****************************************************************************/ void ev_invoke (EV_P_ void *w, int revents) { EV_CB_INVOKE ((W)w, revents); } unsigned int ev_pending_count (EV_P) EV_NOEXCEPT { int pri; unsigned int count = 0; for (pri = NUMPRI; pri--; ) count += pendingcnt [pri]; return count; } noinline void ev_invoke_pending (EV_P) { pendingpri = NUMPRI; do { --pendingpri; /* pendingpri possibly gets modified in the inner loop */ while (pendingcnt [pendingpri]) { ANPENDING *p = pendings [pendingpri] + --pendingcnt [pendingpri]; p->w->pending = 0; EV_CB_INVOKE (p->w, p->events); EV_FREQUENT_CHECK; } } while (pendingpri); } #if EV_IDLE_ENABLE /* make idle watchers pending. this handles the "call-idle */ /* only when higher priorities are idle" logic */ inline_size void idle_reify (EV_P) { if (expect_false (idleall)) { int pri; for (pri = NUMPRI; pri--; ) { if (pendingcnt [pri]) break; if (idlecnt [pri]) { queue_events (EV_A_ (W *)idles [pri], idlecnt [pri], EV_IDLE); break; } } } } #endif /* make timers pending */ inline_size void timers_reify (EV_P) { EV_FREQUENT_CHECK; if (timercnt && ANHE_at (timers [HEAP0]) < mn_now) { do { ev_timer *w = (ev_timer *)ANHE_w (timers [HEAP0]); /*assert (("libev: inactive timer on timer heap detected", ev_is_active (w)));*/ /* first reschedule or stop timer */ if (w->repeat) { ev_at (w) += w->repeat; if (ev_at (w) < mn_now) ev_at (w) = mn_now; assert (("libev: negative ev_timer repeat value found while processing timers", w->repeat > 0.)); ANHE_at_cache (timers [HEAP0]); downheap (timers, timercnt, HEAP0); } else ev_timer_stop (EV_A_ w); /* nonrepeating: stop timer */ EV_FREQUENT_CHECK; feed_reverse (EV_A_ (W)w); } while (timercnt && ANHE_at (timers [HEAP0]) < mn_now); feed_reverse_done (EV_A_ EV_TIMER); } } #if EV_PERIODIC_ENABLE noinline static void periodic_recalc (EV_P_ ev_periodic *w) { ev_tstamp interval = w->interval > MIN_INTERVAL ? w->interval : MIN_INTERVAL; ev_tstamp at = w->offset + interval * ev_floor ((ev_rt_now - w->offset) / interval); /* the above almost always errs on the low side */ while (at <= ev_rt_now) { ev_tstamp nat = at + w->interval; /* when resolution fails us, we use ev_rt_now */ if (expect_false (nat == at)) { at = ev_rt_now; break; } at = nat; } ev_at (w) = at; } /* make periodics pending */ inline_size void periodics_reify (EV_P) { EV_FREQUENT_CHECK; while (periodiccnt && ANHE_at (periodics [HEAP0]) < ev_rt_now) { do { ev_periodic *w = (ev_periodic *)ANHE_w (periodics [HEAP0]); /*assert (("libev: inactive timer on periodic heap detected", ev_is_active (w)));*/ /* first reschedule or stop timer */ if (w->reschedule_cb) { ev_at (w) = w->reschedule_cb (w, ev_rt_now); assert (("libev: ev_periodic reschedule callback returned time in the past", ev_at (w) >= ev_rt_now)); ANHE_at_cache (periodics [HEAP0]); downheap (periodics, periodiccnt, HEAP0); } else if (w->interval) { periodic_recalc (EV_A_ w); ANHE_at_cache (periodics [HEAP0]); downheap (periodics, periodiccnt, HEAP0); } else ev_periodic_stop (EV_A_ w); /* nonrepeating: stop timer */ EV_FREQUENT_CHECK; feed_reverse (EV_A_ (W)w); } while (periodiccnt && ANHE_at (periodics [HEAP0]) < ev_rt_now); feed_reverse_done (EV_A_ EV_PERIODIC); } } /* simply recalculate all periodics */ /* TODO: maybe ensure that at least one event happens when jumping forward? */ noinline ecb_cold static void periodics_reschedule (EV_P) { int i; /* adjust periodics after time jump */ for (i = HEAP0; i < periodiccnt + HEAP0; ++i) { ev_periodic *w = (ev_periodic *)ANHE_w (periodics [i]); if (w->reschedule_cb) ev_at (w) = w->reschedule_cb (w, ev_rt_now); else if (w->interval) periodic_recalc (EV_A_ w); ANHE_at_cache (periodics [i]); } reheap (periodics, periodiccnt); } #endif /* adjust all timers by a given offset */ noinline ecb_cold static void timers_reschedule (EV_P_ ev_tstamp adjust) { int i; for (i = 0; i < timercnt; ++i) { ANHE *he = timers + i + HEAP0; ANHE_w (*he)->at += adjust; ANHE_at_cache (*he); } } /* fetch new monotonic and realtime times from the kernel */ /* also detect if there was a timejump, and act accordingly */ inline_speed void time_update (EV_P_ ev_tstamp max_block) { #if EV_USE_MONOTONIC if (expect_true (have_monotonic)) { int i; ev_tstamp odiff = rtmn_diff; mn_now = get_clock (); /* only fetch the realtime clock every 0.5*MIN_TIMEJUMP seconds */ /* interpolate in the meantime */ if (expect_true (mn_now - now_floor < MIN_TIMEJUMP * .5)) { ev_rt_now = rtmn_diff + mn_now; return; } now_floor = mn_now; ev_rt_now = ev_time (); /* loop a few times, before making important decisions. * on the choice of "4": one iteration isn't enough, * in case we get preempted during the calls to * ev_time and get_clock. a second call is almost guaranteed * to succeed in that case, though. and looping a few more times * doesn't hurt either as we only do this on time-jumps or * in the unlikely event of having been preempted here. */ for (i = 4; --i; ) { ev_tstamp diff; rtmn_diff = ev_rt_now - mn_now; diff = odiff - rtmn_diff; if (expect_true ((diff < 0. ? -diff : diff) < MIN_TIMEJUMP)) return; /* all is well */ ev_rt_now = ev_time (); mn_now = get_clock (); now_floor = mn_now; } /* no timer adjustment, as the monotonic clock doesn't jump */ /* timers_reschedule (EV_A_ rtmn_diff - odiff) */ # if EV_PERIODIC_ENABLE periodics_reschedule (EV_A); # endif } else #endif { ev_rt_now = ev_time (); if (expect_false (mn_now > ev_rt_now || ev_rt_now > mn_now + max_block + MIN_TIMEJUMP)) { /* adjust timers. this is easy, as the offset is the same for all of them */ timers_reschedule (EV_A_ ev_rt_now - mn_now); #if EV_PERIODIC_ENABLE periodics_reschedule (EV_A); #endif } mn_now = ev_rt_now; } } int ev_run (EV_P_ int flags) { #if EV_FEATURE_API ++loop_depth; #endif assert (("libev: ev_loop recursion during release detected", loop_done != EVBREAK_RECURSE)); loop_done = EVBREAK_CANCEL; EV_INVOKE_PENDING; /* in case we recurse, ensure ordering stays nice and clean */ do { #if EV_VERIFY >= 2 ev_verify (EV_A); #endif #ifndef _WIN32 if (expect_false (curpid)) /* penalise the forking check even more */ if (expect_false (getpid () != curpid)) { curpid = getpid (); postfork = 1; } #endif #if EV_FORK_ENABLE /* we might have forked, so queue fork handlers */ if (expect_false (postfork)) if (forkcnt) { queue_events (EV_A_ (W *)forks, forkcnt, EV_FORK); EV_INVOKE_PENDING; } #endif #if EV_PREPARE_ENABLE /* queue prepare watchers (and execute them) */ if (expect_false (preparecnt)) { queue_events (EV_A_ (W *)prepares, preparecnt, EV_PREPARE); EV_INVOKE_PENDING; } #endif if (expect_false (loop_done)) break; /* we might have forked, so reify kernel state if necessary */ if (expect_false (postfork)) loop_fork (EV_A); /* update fd-related kernel structures */ fd_reify (EV_A); /* calculate blocking time */ { ev_tstamp waittime = 0.; ev_tstamp sleeptime = 0.; /* remember old timestamp for io_blocktime calculation */ ev_tstamp prev_mn_now = mn_now; /* update time to cancel out callback processing overhead */ time_update (EV_A_ 1e100); /* from now on, we want a pipe-wake-up */ pipe_write_wanted = 1; ECB_MEMORY_FENCE; /* make sure pipe_write_wanted is visible before we check for potential skips */ if (expect_true (!(flags & EVRUN_NOWAIT || idleall || !activecnt || pipe_write_skipped))) { waittime = MAX_BLOCKTIME; if (timercnt) { ev_tstamp to = ANHE_at (timers [HEAP0]) - mn_now; if (waittime > to) waittime = to; } #if EV_PERIODIC_ENABLE if (periodiccnt) { ev_tstamp to = ANHE_at (periodics [HEAP0]) - ev_rt_now; if (waittime > to) waittime = to; } #endif /* don't let timeouts decrease the waittime below timeout_blocktime */ if (expect_false (waittime < timeout_blocktime)) waittime = timeout_blocktime; /* at this point, we NEED to wait, so we have to ensure */ /* to pass a minimum nonzero value to the backend */ if (expect_false (waittime < backend_mintime)) waittime = backend_mintime; /* extra check because io_blocktime is commonly 0 */ if (expect_false (io_blocktime)) { sleeptime = io_blocktime - (mn_now - prev_mn_now); if (sleeptime > waittime - backend_mintime) sleeptime = waittime - backend_mintime; if (expect_true (sleeptime > 0.)) { ev_sleep (sleeptime); waittime -= sleeptime; } } } #if EV_FEATURE_API ++loop_count; #endif assert ((loop_done = EVBREAK_RECURSE, 1)); /* assert for side effect */ backend_poll (EV_A_ waittime); assert ((loop_done = EVBREAK_CANCEL, 1)); /* assert for side effect */ pipe_write_wanted = 0; /* just an optimisation, no fence needed */ ECB_MEMORY_FENCE_ACQUIRE; if (pipe_write_skipped) { assert (("libev: pipe_w not active, but pipe not written", ev_is_active (&pipe_w))); ev_feed_event (EV_A_ &pipe_w, EV_CUSTOM); } /* update ev_rt_now, do magic */ time_update (EV_A_ waittime + sleeptime); } /* queue pending timers and reschedule them */ timers_reify (EV_A); /* relative timers called last */ #if EV_PERIODIC_ENABLE periodics_reify (EV_A); /* absolute timers called first */ #endif #if EV_IDLE_ENABLE /* queue idle watchers unless other events are pending */ idle_reify (EV_A); #endif #if EV_CHECK_ENABLE /* queue check watchers, to be executed first */ if (expect_false (checkcnt)) queue_events (EV_A_ (W *)checks, checkcnt, EV_CHECK); #endif EV_INVOKE_PENDING; } while (expect_true ( activecnt && !loop_done && !(flags & (EVRUN_ONCE | EVRUN_NOWAIT)) )); if (loop_done == EVBREAK_ONE) loop_done = EVBREAK_CANCEL; #if EV_FEATURE_API --loop_depth; #endif return activecnt; } void ev_break (EV_P_ int how) EV_NOEXCEPT { loop_done = how; } void ev_ref (EV_P) EV_NOEXCEPT { ++activecnt; } void ev_unref (EV_P) EV_NOEXCEPT { --activecnt; } void ev_now_update (EV_P) EV_NOEXCEPT { time_update (EV_A_ 1e100); } void ev_suspend (EV_P) EV_NOEXCEPT { ev_now_update (EV_A); } void ev_resume (EV_P) EV_NOEXCEPT { ev_tstamp mn_prev = mn_now; ev_now_update (EV_A); timers_reschedule (EV_A_ mn_now - mn_prev); #if EV_PERIODIC_ENABLE /* TODO: really do this? */ periodics_reschedule (EV_A); #endif } /*****************************************************************************/ /* singly-linked list management, used when the expected list length is short */ inline_size void wlist_add (WL *head, WL elem) { elem->next = *head; *head = elem; } inline_size void wlist_del (WL *head, WL elem) { while (*head) { if (expect_true (*head == elem)) { *head = elem->next; break; } head = &(*head)->next; } } /* internal, faster, version of ev_clear_pending */ inline_speed void clear_pending (EV_P_ W w) { if (w->pending) { pendings [ABSPRI (w)][w->pending - 1].w = (W)&pending_w; w->pending = 0; } } int ev_clear_pending (EV_P_ void *w) EV_NOEXCEPT { W w_ = (W)w; int pending = w_->pending; if (expect_true (pending)) { ANPENDING *p = pendings [ABSPRI (w_)] + pending - 1; p->w = (W)&pending_w; w_->pending = 0; return p->events; } else return 0; } inline_size void pri_adjust (EV_P_ W w) { int pri = ev_priority (w); pri = pri < EV_MINPRI ? EV_MINPRI : pri; pri = pri > EV_MAXPRI ? EV_MAXPRI : pri; ev_set_priority (w, pri); } inline_speed void ev_start (EV_P_ W w, int active) { pri_adjust (EV_A_ w); w->active = active; ev_ref (EV_A); } inline_size void ev_stop (EV_P_ W w) { ev_unref (EV_A); w->active = 0; } /*****************************************************************************/ noinline void ev_io_start (EV_P_ ev_io *w) EV_NOEXCEPT { int fd = w->fd; if (expect_false (ev_is_active (w))) return; assert (("libev: ev_io_start called with negative fd", fd >= 0)); assert (("libev: ev_io_start called with illegal event mask", !(w->events & ~(EV__IOFDSET | EV_READ | EV_WRITE)))); EV_FREQUENT_CHECK; ev_start (EV_A_ (W)w, 1); array_needsize (ANFD, anfds, anfdmax, fd + 1, array_init_zero); wlist_add (&anfds[fd].head, (WL)w); /* common bug, apparently */ assert (("libev: ev_io_start called with corrupted watcher", ((WL)w)->next != (WL)w)); fd_change (EV_A_ fd, w->events & EV__IOFDSET | EV_ANFD_REIFY); w->events &= ~EV__IOFDSET; EV_FREQUENT_CHECK; } noinline void ev_io_stop (EV_P_ ev_io *w) EV_NOEXCEPT { clear_pending (EV_A_ (W)w); if (expect_false (!ev_is_active (w))) return; assert (("libev: ev_io_stop called with illegal fd (must stay constant after start!)", w->fd >= 0 && w->fd < anfdmax)); EV_FREQUENT_CHECK; wlist_del (&anfds[w->fd].head, (WL)w); ev_stop (EV_A_ (W)w); fd_change (EV_A_ w->fd, EV_ANFD_REIFY); EV_FREQUENT_CHECK; } noinline void ev_timer_start (EV_P_ ev_timer *w) EV_NOEXCEPT { if (expect_false (ev_is_active (w))) return; ev_at (w) += mn_now; assert (("libev: ev_timer_start called with negative timer repeat value", w->repeat >= 0.)); EV_FREQUENT_CHECK; ++timercnt; ev_start (EV_A_ (W)w, timercnt + HEAP0 - 1); array_needsize (ANHE, timers, timermax, ev_active (w) + 1, EMPTY2); ANHE_w (timers [ev_active (w)]) = (WT)w; ANHE_at_cache (timers [ev_active (w)]); upheap (timers, ev_active (w)); EV_FREQUENT_CHECK; /*assert (("libev: internal timer heap corruption", timers [ev_active (w)] == (WT)w));*/ } noinline void ev_timer_stop (EV_P_ ev_timer *w) EV_NOEXCEPT { clear_pending (EV_A_ (W)w); if (expect_false (!ev_is_active (w))) return; EV_FREQUENT_CHECK; { int active = ev_active (w); assert (("libev: internal timer heap corruption", ANHE_w (timers [active]) == (WT)w)); --timercnt; if (expect_true (active < timercnt + HEAP0)) { timers [active] = timers [timercnt + HEAP0]; adjustheap (timers, timercnt, active); } } ev_at (w) -= mn_now; ev_stop (EV_A_ (W)w); EV_FREQUENT_CHECK; } noinline void ev_timer_again (EV_P_ ev_timer *w) EV_NOEXCEPT { EV_FREQUENT_CHECK; clear_pending (EV_A_ (W)w); if (ev_is_active (w)) { if (w->repeat) { ev_at (w) = mn_now + w->repeat; ANHE_at_cache (timers [ev_active (w)]); adjustheap (timers, timercnt, ev_active (w)); } else ev_timer_stop (EV_A_ w); } else if (w->repeat) { ev_at (w) = w->repeat; ev_timer_start (EV_A_ w); } EV_FREQUENT_CHECK; } ev_tstamp ev_timer_remaining (EV_P_ ev_timer *w) EV_NOEXCEPT { return ev_at (w) - (ev_is_active (w) ? mn_now : 0.); } #if EV_PERIODIC_ENABLE noinline void ev_periodic_start (EV_P_ ev_periodic *w) EV_NOEXCEPT { if (expect_false (ev_is_active (w))) return; if (w->reschedule_cb) ev_at (w) = w->reschedule_cb (w, ev_rt_now); else if (w->interval) { assert (("libev: ev_periodic_start called with negative interval value", w->interval >= 0.)); periodic_recalc (EV_A_ w); } else ev_at (w) = w->offset; EV_FREQUENT_CHECK; ++periodiccnt; ev_start (EV_A_ (W)w, periodiccnt + HEAP0 - 1); array_needsize (ANHE, periodics, periodicmax, ev_active (w) + 1, EMPTY2); ANHE_w (periodics [ev_active (w)]) = (WT)w; ANHE_at_cache (periodics [ev_active (w)]); upheap (periodics, ev_active (w)); EV_FREQUENT_CHECK; /*assert (("libev: internal periodic heap corruption", ANHE_w (periodics [ev_active (w)]) == (WT)w));*/ } noinline void ev_periodic_stop (EV_P_ ev_periodic *w) EV_NOEXCEPT { clear_pending (EV_A_ (W)w); if (expect_false (!ev_is_active (w))) return; EV_FREQUENT_CHECK; { int active = ev_active (w); assert (("libev: internal periodic heap corruption", ANHE_w (periodics [active]) == (WT)w)); --periodiccnt; if (expect_true (active < periodiccnt + HEAP0)) { periodics [active] = periodics [periodiccnt + HEAP0]; adjustheap (periodics, periodiccnt, active); } } ev_stop (EV_A_ (W)w); EV_FREQUENT_CHECK; } noinline void ev_periodic_again (EV_P_ ev_periodic *w) EV_NOEXCEPT { /* TODO: use adjustheap and recalculation */ ev_periodic_stop (EV_A_ w); ev_periodic_start (EV_A_ w); } #endif #ifndef SA_RESTART # define SA_RESTART 0 #endif #if EV_SIGNAL_ENABLE noinline void ev_signal_start (EV_P_ ev_signal *w) EV_NOEXCEPT { if (expect_false (ev_is_active (w))) return; assert (("libev: ev_signal_start called with illegal signal number", w->signum > 0 && w->signum < EV_NSIG)); #if EV_MULTIPLICITY assert (("libev: a signal must not be attached to two different loops", !signals [w->signum - 1].loop || signals [w->signum - 1].loop == loop)); signals [w->signum - 1].loop = EV_A; ECB_MEMORY_FENCE_RELEASE; #endif EV_FREQUENT_CHECK; #if EV_USE_SIGNALFD if (sigfd == -2) { sigfd = signalfd (-1, &sigfd_set, SFD_NONBLOCK | SFD_CLOEXEC); if (sigfd < 0 && errno == EINVAL) sigfd = signalfd (-1, &sigfd_set, 0); /* retry without flags */ if (sigfd >= 0) { fd_intern (sigfd); /* doing it twice will not hurt */ sigemptyset (&sigfd_set); ev_io_init (&sigfd_w, sigfdcb, sigfd, EV_READ); ev_set_priority (&sigfd_w, EV_MAXPRI); ev_io_start (EV_A_ &sigfd_w); ev_unref (EV_A); /* signalfd watcher should not keep loop alive */ } } if (sigfd >= 0) { /* TODO: check .head */ sigaddset (&sigfd_set, w->signum); sigprocmask (SIG_BLOCK, &sigfd_set, 0); signalfd (sigfd, &sigfd_set, 0); } #endif ev_start (EV_A_ (W)w, 1); wlist_add (&signals [w->signum - 1].head, (WL)w); if (!((WL)w)->next) # if EV_USE_SIGNALFD if (sigfd < 0) /*TODO*/ # endif { # ifdef _WIN32 evpipe_init (EV_A); signal (w->signum, ev_sighandler); # else struct sigaction sa; evpipe_init (EV_A); sa.sa_handler = ev_sighandler; sigfillset (&sa.sa_mask); sa.sa_flags = SA_RESTART; /* if restarting works we save one iteration */ sigaction (w->signum, &sa, 0); if (origflags & EVFLAG_NOSIGMASK) { sigemptyset (&sa.sa_mask); sigaddset (&sa.sa_mask, w->signum); sigprocmask (SIG_UNBLOCK, &sa.sa_mask, 0); } #endif } EV_FREQUENT_CHECK; } noinline void ev_signal_stop (EV_P_ ev_signal *w) EV_NOEXCEPT { clear_pending (EV_A_ (W)w); if (expect_false (!ev_is_active (w))) return; EV_FREQUENT_CHECK; wlist_del (&signals [w->signum - 1].head, (WL)w); ev_stop (EV_A_ (W)w); if (!signals [w->signum - 1].head) { #if EV_MULTIPLICITY signals [w->signum - 1].loop = 0; /* unattach from signal */ #endif #if EV_USE_SIGNALFD if (sigfd >= 0) { sigset_t ss; sigemptyset (&ss); sigaddset (&ss, w->signum); sigdelset (&sigfd_set, w->signum); signalfd (sigfd, &sigfd_set, 0); sigprocmask (SIG_UNBLOCK, &ss, 0); } else #endif signal (w->signum, SIG_DFL); } EV_FREQUENT_CHECK; } #endif #if EV_CHILD_ENABLE void ev_child_start (EV_P_ ev_child *w) EV_NOEXCEPT { #if EV_MULTIPLICITY assert (("libev: child watchers are only supported in the default loop", loop == ev_default_loop_ptr)); #endif if (expect_false (ev_is_active (w))) return; EV_FREQUENT_CHECK; ev_start (EV_A_ (W)w, 1); wlist_add (&childs [w->pid & ((EV_PID_HASHSIZE) - 1)], (WL)w); EV_FREQUENT_CHECK; } void ev_child_stop (EV_P_ ev_child *w) EV_NOEXCEPT { clear_pending (EV_A_ (W)w); if (expect_false (!ev_is_active (w))) return; EV_FREQUENT_CHECK; wlist_del (&childs [w->pid & ((EV_PID_HASHSIZE) - 1)], (WL)w); ev_stop (EV_A_ (W)w); EV_FREQUENT_CHECK; } #endif #if EV_STAT_ENABLE # ifdef _WIN32 # undef lstat # define lstat(a,b) _stati64 (a,b) # endif #define DEF_STAT_INTERVAL 5.0074891 #define NFS_STAT_INTERVAL 30.1074891 /* for filesystems potentially failing inotify */ #define MIN_STAT_INTERVAL 0.1074891 noinline static void stat_timer_cb (EV_P_ ev_timer *w_, int revents); #if EV_USE_INOTIFY /* the * 2 is to allow for alignment padding, which for some reason is >> 8 */ # define EV_INOTIFY_BUFSIZE (sizeof (struct inotify_event) * 2 + NAME_MAX) noinline static void infy_add (EV_P_ ev_stat *w) { w->wd = inotify_add_watch (fs_fd, w->path, IN_ATTRIB | IN_DELETE_SELF | IN_MOVE_SELF | IN_MODIFY | IN_CREATE | IN_DELETE | IN_MOVED_FROM | IN_MOVED_TO | IN_DONT_FOLLOW | IN_MASK_ADD); if (w->wd >= 0) { struct statfs sfs; /* now local changes will be tracked by inotify, but remote changes won't */ /* unless the filesystem is known to be local, we therefore still poll */ /* also do poll on <2.6.25, but with normal frequency */ if (!fs_2625) w->timer.repeat = w->interval ? w->interval : DEF_STAT_INTERVAL; else if (!statfs (w->path, &sfs) && (sfs.f_type == 0x1373 /* devfs */ || sfs.f_type == 0x4006 /* fat */ || sfs.f_type == 0x4d44 /* msdos */ || sfs.f_type == 0xEF53 /* ext2/3 */ || sfs.f_type == 0x72b6 /* jffs2 */ || sfs.f_type == 0x858458f6 /* ramfs */ || sfs.f_type == 0x5346544e /* ntfs */ || sfs.f_type == 0x3153464a /* jfs */ || sfs.f_type == 0x9123683e /* btrfs */ || sfs.f_type == 0x52654973 /* reiser3 */ || sfs.f_type == 0x01021994 /* tmpfs */ || sfs.f_type == 0x58465342 /* xfs */)) w->timer.repeat = 0.; /* filesystem is local, kernel new enough */ else w->timer.repeat = w->interval ? w->interval : NFS_STAT_INTERVAL; /* remote, use reduced frequency */ } else { /* can't use inotify, continue to stat */ w->timer.repeat = w->interval ? w->interval : DEF_STAT_INTERVAL; /* if path is not there, monitor some parent directory for speedup hints */ /* note that exceeding the hardcoded path limit is not a correctness issue, */ /* but an efficiency issue only */ if ((errno == ENOENT || errno == EACCES) && strlen (w->path) < 4096) { char path [4096]; strcpy (path, w->path); do { int mask = IN_MASK_ADD | IN_DELETE_SELF | IN_MOVE_SELF | (errno == EACCES ? IN_ATTRIB : IN_CREATE | IN_MOVED_TO); char *pend = strrchr (path, '/'); if (!pend || pend == path) break; *pend = 0; w->wd = inotify_add_watch (fs_fd, path, mask); } while (w->wd < 0 && (errno == ENOENT || errno == EACCES)); } } if (w->wd >= 0) wlist_add (&fs_hash [w->wd & ((EV_INOTIFY_HASHSIZE) - 1)].head, (WL)w); /* now re-arm timer, if required */ if (ev_is_active (&w->timer)) ev_ref (EV_A); ev_timer_again (EV_A_ &w->timer); if (ev_is_active (&w->timer)) ev_unref (EV_A); } noinline static void infy_del (EV_P_ ev_stat *w) { int slot; int wd = w->wd; if (wd < 0) return; w->wd = -2; slot = wd & ((EV_INOTIFY_HASHSIZE) - 1); wlist_del (&fs_hash [slot].head, (WL)w); /* remove this watcher, if others are watching it, they will rearm */ inotify_rm_watch (fs_fd, wd); } noinline static void infy_wd (EV_P_ int slot, int wd, struct inotify_event *ev) { if (slot < 0) /* overflow, need to check for all hash slots */ for (slot = 0; slot < (EV_INOTIFY_HASHSIZE); ++slot) infy_wd (EV_A_ slot, wd, ev); else { WL w_; for (w_ = fs_hash [slot & ((EV_INOTIFY_HASHSIZE) - 1)].head; w_; ) { ev_stat *w = (ev_stat *)w_; w_ = w_->next; /* lets us remove this watcher and all before it */ if (w->wd == wd || wd == -1) { if (ev->mask & (IN_IGNORED | IN_UNMOUNT | IN_DELETE_SELF)) { wlist_del (&fs_hash [slot & ((EV_INOTIFY_HASHSIZE) - 1)].head, (WL)w); w->wd = -1; infy_add (EV_A_ w); /* re-add, no matter what */ } stat_timer_cb (EV_A_ &w->timer, 0); } } } } static void infy_cb (EV_P_ ev_io *w, int revents) { char buf [EV_INOTIFY_BUFSIZE]; int ofs; int len = read (fs_fd, buf, sizeof (buf)); for (ofs = 0; ofs < len; ) { struct inotify_event *ev = (struct inotify_event *)(buf + ofs); infy_wd (EV_A_ ev->wd, ev->wd, ev); ofs += sizeof (struct inotify_event) + ev->len; } } inline_size ecb_cold void ev_check_2625 (EV_P) { /* kernels < 2.6.25 are borked * http://www.ussg.indiana.edu/hypermail/linux/kernel/0711.3/1208.html */ if (ev_linux_version () < 0x020619) return; fs_2625 = 1; } inline_size int infy_newfd (void) { #if defined IN_CLOEXEC && defined IN_NONBLOCK int fd = inotify_init1 (IN_CLOEXEC | IN_NONBLOCK); if (fd >= 0) return fd; #endif return inotify_init (); } inline_size void infy_init (EV_P) { if (fs_fd != -2) return; fs_fd = -1; ev_check_2625 (EV_A); fs_fd = infy_newfd (); if (fs_fd >= 0) { fd_intern (fs_fd); ev_io_init (&fs_w, infy_cb, fs_fd, EV_READ); ev_set_priority (&fs_w, EV_MAXPRI); ev_io_start (EV_A_ &fs_w); ev_unref (EV_A); } } inline_size void infy_fork (EV_P) { int slot; if (fs_fd < 0) return; ev_ref (EV_A); ev_io_stop (EV_A_ &fs_w); close (fs_fd); fs_fd = infy_newfd (); if (fs_fd >= 0) { fd_intern (fs_fd); ev_io_set (&fs_w, fs_fd, EV_READ); ev_io_start (EV_A_ &fs_w); ev_unref (EV_A); } for (slot = 0; slot < (EV_INOTIFY_HASHSIZE); ++slot) { WL w_ = fs_hash [slot].head; fs_hash [slot].head = 0; while (w_) { ev_stat *w = (ev_stat *)w_; w_ = w_->next; /* lets us add this watcher */ w->wd = -1; if (fs_fd >= 0) infy_add (EV_A_ w); /* re-add, no matter what */ else { w->timer.repeat = w->interval ? w->interval : DEF_STAT_INTERVAL; if (ev_is_active (&w->timer)) ev_ref (EV_A); ev_timer_again (EV_A_ &w->timer); if (ev_is_active (&w->timer)) ev_unref (EV_A); } } } } #endif #ifdef _WIN32 # define EV_LSTAT(p,b) _stati64 (p, b) #else # define EV_LSTAT(p,b) lstat (p, b) #endif void ev_stat_stat (EV_P_ ev_stat *w) EV_NOEXCEPT { if (lstat (w->path, &w->attr) < 0) w->attr.st_nlink = 0; else if (!w->attr.st_nlink) w->attr.st_nlink = 1; } noinline static void stat_timer_cb (EV_P_ ev_timer *w_, int revents) { ev_stat *w = (ev_stat *)(((char *)w_) - offsetof (ev_stat, timer)); ev_statdata prev = w->attr; ev_stat_stat (EV_A_ w); /* memcmp doesn't work on netbsd, they.... do stuff to their struct stat */ if ( prev.st_dev != w->attr.st_dev || prev.st_ino != w->attr.st_ino || prev.st_mode != w->attr.st_mode || prev.st_nlink != w->attr.st_nlink || prev.st_uid != w->attr.st_uid || prev.st_gid != w->attr.st_gid || prev.st_rdev != w->attr.st_rdev || prev.st_size != w->attr.st_size || prev.st_atime != w->attr.st_atime || prev.st_mtime != w->attr.st_mtime || prev.st_ctime != w->attr.st_ctime ) { /* we only update w->prev on actual differences */ /* in case we test more often than invoke the callback, */ /* to ensure that prev is always different to attr */ w->prev = prev; #if EV_USE_INOTIFY if (fs_fd >= 0) { infy_del (EV_A_ w); infy_add (EV_A_ w); ev_stat_stat (EV_A_ w); /* avoid race... */ } #endif ev_feed_event (EV_A_ w, EV_STAT); } } void ev_stat_start (EV_P_ ev_stat *w) EV_NOEXCEPT { if (expect_false (ev_is_active (w))) return; ev_stat_stat (EV_A_ w); if (w->interval < MIN_STAT_INTERVAL && w->interval) w->interval = MIN_STAT_INTERVAL; ev_timer_init (&w->timer, stat_timer_cb, 0., w->interval ? w->interval : DEF_STAT_INTERVAL); ev_set_priority (&w->timer, ev_priority (w)); #if EV_USE_INOTIFY infy_init (EV_A); if (fs_fd >= 0) infy_add (EV_A_ w); else #endif { ev_timer_again (EV_A_ &w->timer); ev_unref (EV_A); } ev_start (EV_A_ (W)w, 1); EV_FREQUENT_CHECK; } void ev_stat_stop (EV_P_ ev_stat *w) EV_NOEXCEPT { clear_pending (EV_A_ (W)w); if (expect_false (!ev_is_active (w))) return; EV_FREQUENT_CHECK; #if EV_USE_INOTIFY infy_del (EV_A_ w); #endif if (ev_is_active (&w->timer)) { ev_ref (EV_A); ev_timer_stop (EV_A_ &w->timer); } ev_stop (EV_A_ (W)w); EV_FREQUENT_CHECK; } #endif #if EV_IDLE_ENABLE void ev_idle_start (EV_P_ ev_idle *w) EV_NOEXCEPT { if (expect_false (ev_is_active (w))) return; pri_adjust (EV_A_ (W)w); EV_FREQUENT_CHECK; { int active = ++idlecnt [ABSPRI (w)]; ++idleall; ev_start (EV_A_ (W)w, active); array_needsize (ev_idle *, idles [ABSPRI (w)], idlemax [ABSPRI (w)], active, EMPTY2); idles [ABSPRI (w)][active - 1] = w; } EV_FREQUENT_CHECK; } void ev_idle_stop (EV_P_ ev_idle *w) EV_NOEXCEPT { clear_pending (EV_A_ (W)w); if (expect_false (!ev_is_active (w))) return; EV_FREQUENT_CHECK; { int active = ev_active (w); idles [ABSPRI (w)][active - 1] = idles [ABSPRI (w)][--idlecnt [ABSPRI (w)]]; ev_active (idles [ABSPRI (w)][active - 1]) = active; ev_stop (EV_A_ (W)w); --idleall; } EV_FREQUENT_CHECK; } #endif #if EV_PREPARE_ENABLE void ev_prepare_start (EV_P_ ev_prepare *w) EV_NOEXCEPT { if (expect_false (ev_is_active (w))) return; EV_FREQUENT_CHECK; ev_start (EV_A_ (W)w, ++preparecnt); array_needsize (ev_prepare *, prepares, preparemax, preparecnt, EMPTY2); prepares [preparecnt - 1] = w; EV_FREQUENT_CHECK; } void ev_prepare_stop (EV_P_ ev_prepare *w) EV_NOEXCEPT { clear_pending (EV_A_ (W)w); if (expect_false (!ev_is_active (w))) return; EV_FREQUENT_CHECK; { int active = ev_active (w); prepares [active - 1] = prepares [--preparecnt]; ev_active (prepares [active - 1]) = active; } ev_stop (EV_A_ (W)w); EV_FREQUENT_CHECK; } #endif #if EV_CHECK_ENABLE void ev_check_start (EV_P_ ev_check *w) EV_NOEXCEPT { if (expect_false (ev_is_active (w))) return; EV_FREQUENT_CHECK; ev_start (EV_A_ (W)w, ++checkcnt); array_needsize (ev_check *, checks, checkmax, checkcnt, EMPTY2); checks [checkcnt - 1] = w; EV_FREQUENT_CHECK; } void ev_check_stop (EV_P_ ev_check *w) EV_NOEXCEPT { clear_pending (EV_A_ (W)w); if (expect_false (!ev_is_active (w))) return; EV_FREQUENT_CHECK; { int active = ev_active (w); checks [active - 1] = checks [--checkcnt]; ev_active (checks [active - 1]) = active; } ev_stop (EV_A_ (W)w); EV_FREQUENT_CHECK; } #endif #if EV_EMBED_ENABLE noinline void ev_embed_sweep (EV_P_ ev_embed *w) EV_NOEXCEPT { ev_run (w->other, EVRUN_NOWAIT); } static void embed_io_cb (EV_P_ ev_io *io, int revents) { ev_embed *w = (ev_embed *)(((char *)io) - offsetof (ev_embed, io)); if (ev_cb (w)) ev_feed_event (EV_A_ (W)w, EV_EMBED); else ev_run (w->other, EVRUN_NOWAIT); } static void embed_prepare_cb (EV_P_ ev_prepare *prepare, int revents) { ev_embed *w = (ev_embed *)(((char *)prepare) - offsetof (ev_embed, prepare)); { EV_P = w->other; while (fdchangecnt) { fd_reify (EV_A); ev_run (EV_A_ EVRUN_NOWAIT); } } } static void embed_fork_cb (EV_P_ ev_fork *fork_w, int revents) { ev_embed *w = (ev_embed *)(((char *)fork_w) - offsetof (ev_embed, fork)); ev_embed_stop (EV_A_ w); { EV_P = w->other; ev_loop_fork (EV_A); ev_run (EV_A_ EVRUN_NOWAIT); } ev_embed_start (EV_A_ w); } #if 0 static void embed_idle_cb (EV_P_ ev_idle *idle, int revents) { ev_idle_stop (EV_A_ idle); } #endif void ev_embed_start (EV_P_ ev_embed *w) EV_NOEXCEPT { if (expect_false (ev_is_active (w))) return; { EV_P = w->other; assert (("libev: loop to be embedded is not embeddable", backend & ev_embeddable_backends ())); ev_io_init (&w->io, embed_io_cb, backend_fd, EV_READ); } EV_FREQUENT_CHECK; ev_set_priority (&w->io, ev_priority (w)); ev_io_start (EV_A_ &w->io); ev_prepare_init (&w->prepare, embed_prepare_cb); ev_set_priority (&w->prepare, EV_MINPRI); ev_prepare_start (EV_A_ &w->prepare); ev_fork_init (&w->fork, embed_fork_cb); ev_fork_start (EV_A_ &w->fork); /*ev_idle_init (&w->idle, e,bed_idle_cb);*/ ev_start (EV_A_ (W)w, 1); EV_FREQUENT_CHECK; } void ev_embed_stop (EV_P_ ev_embed *w) EV_NOEXCEPT { clear_pending (EV_A_ (W)w); if (expect_false (!ev_is_active (w))) return; EV_FREQUENT_CHECK; ev_io_stop (EV_A_ &w->io); ev_prepare_stop (EV_A_ &w->prepare); ev_fork_stop (EV_A_ &w->fork); ev_stop (EV_A_ (W)w); EV_FREQUENT_CHECK; } #endif #if EV_FORK_ENABLE void ev_fork_start (EV_P_ ev_fork *w) EV_NOEXCEPT { if (expect_false (ev_is_active (w))) return; EV_FREQUENT_CHECK; ev_start (EV_A_ (W)w, ++forkcnt); array_needsize (ev_fork *, forks, forkmax, forkcnt, EMPTY2); forks [forkcnt - 1] = w; EV_FREQUENT_CHECK; } void ev_fork_stop (EV_P_ ev_fork *w) EV_NOEXCEPT { clear_pending (EV_A_ (W)w); if (expect_false (!ev_is_active (w))) return; EV_FREQUENT_CHECK; { int active = ev_active (w); forks [active - 1] = forks [--forkcnt]; ev_active (forks [active - 1]) = active; } ev_stop (EV_A_ (W)w); EV_FREQUENT_CHECK; } #endif #if EV_CLEANUP_ENABLE void ev_cleanup_start (EV_P_ ev_cleanup *w) EV_NOEXCEPT { if (expect_false (ev_is_active (w))) return; EV_FREQUENT_CHECK; ev_start (EV_A_ (W)w, ++cleanupcnt); array_needsize (ev_cleanup *, cleanups, cleanupmax, cleanupcnt, EMPTY2); cleanups [cleanupcnt - 1] = w; /* cleanup watchers should never keep a refcount on the loop */ ev_unref (EV_A); EV_FREQUENT_CHECK; } void ev_cleanup_stop (EV_P_ ev_cleanup *w) EV_NOEXCEPT { clear_pending (EV_A_ (W)w); if (expect_false (!ev_is_active (w))) return; EV_FREQUENT_CHECK; ev_ref (EV_A); { int active = ev_active (w); cleanups [active - 1] = cleanups [--cleanupcnt]; ev_active (cleanups [active - 1]) = active; } ev_stop (EV_A_ (W)w); EV_FREQUENT_CHECK; } #endif #if EV_ASYNC_ENABLE void ev_async_start (EV_P_ ev_async *w) EV_NOEXCEPT { if (expect_false (ev_is_active (w))) return; w->sent = 0; evpipe_init (EV_A); EV_FREQUENT_CHECK; ev_start (EV_A_ (W)w, ++asynccnt); array_needsize (ev_async *, asyncs, asyncmax, asynccnt, EMPTY2); asyncs [asynccnt - 1] = w; EV_FREQUENT_CHECK; } void ev_async_stop (EV_P_ ev_async *w) EV_NOEXCEPT { clear_pending (EV_A_ (W)w); if (expect_false (!ev_is_active (w))) return; EV_FREQUENT_CHECK; { int active = ev_active (w); asyncs [active - 1] = asyncs [--asynccnt]; ev_active (asyncs [active - 1]) = active; } ev_stop (EV_A_ (W)w); EV_FREQUENT_CHECK; } void ev_async_send (EV_P_ ev_async *w) EV_NOEXCEPT { w->sent = 1; evpipe_write (EV_A_ &async_pending); } #endif /*****************************************************************************/ struct ev_once { ev_io io; ev_timer to; void (*cb)(int revents, void *arg); void *arg; }; static void once_cb (EV_P_ struct ev_once *once, int revents) { void (*cb)(int revents, void *arg) = once->cb; void *arg = once->arg; ev_io_stop (EV_A_ &once->io); ev_timer_stop (EV_A_ &once->to); ev_free (once); cb (revents, arg); } static void once_cb_io (EV_P_ ev_io *w, int revents) { struct ev_once *once = (struct ev_once *)(((char *)w) - offsetof (struct ev_once, io)); once_cb (EV_A_ once, revents | ev_clear_pending (EV_A_ &once->to)); } static void once_cb_to (EV_P_ ev_timer *w, int revents) { struct ev_once *once = (struct ev_once *)(((char *)w) - offsetof (struct ev_once, to)); once_cb (EV_A_ once, revents | ev_clear_pending (EV_A_ &once->io)); } void ev_once (EV_P_ int fd, int events, ev_tstamp timeout, void (*cb)(int revents, void *arg), void *arg) EV_NOEXCEPT { struct ev_once *once = (struct ev_once *)ev_malloc (sizeof (struct ev_once)); if (expect_false (!once)) { cb (EV_ERROR | EV_READ | EV_WRITE | EV_TIMER, arg); return; } once->cb = cb; once->arg = arg; ev_init (&once->io, once_cb_io); if (fd >= 0) { ev_io_set (&once->io, fd, events); ev_io_start (EV_A_ &once->io); } ev_init (&once->to, once_cb_to); if (timeout >= 0.) { ev_timer_set (&once->to, timeout, 0.); ev_timer_start (EV_A_ &once->to); } } /*****************************************************************************/ #if EV_WALK_ENABLE ecb_cold void ev_walk (EV_P_ int types, void (*cb)(EV_P_ int type, void *w)) EV_NOEXCEPT { int i, j; ev_watcher_list *wl, *wn; if (types & (EV_IO | EV_EMBED)) for (i = 0; i < anfdmax; ++i) for (wl = anfds [i].head; wl; ) { wn = wl->next; #if EV_EMBED_ENABLE if (ev_cb ((ev_io *)wl) == embed_io_cb) { if (types & EV_EMBED) cb (EV_A_ EV_EMBED, ((char *)wl) - offsetof (struct ev_embed, io)); } else #endif #if EV_USE_INOTIFY if (ev_cb ((ev_io *)wl) == infy_cb) ; else #endif if ((ev_io *)wl != &pipe_w) if (types & EV_IO) cb (EV_A_ EV_IO, wl); wl = wn; } if (types & (EV_TIMER | EV_STAT)) for (i = timercnt + HEAP0; i-- > HEAP0; ) #if EV_STAT_ENABLE /*TODO: timer is not always active*/ if (ev_cb ((ev_timer *)ANHE_w (timers [i])) == stat_timer_cb) { if (types & EV_STAT) cb (EV_A_ EV_STAT, ((char *)ANHE_w (timers [i])) - offsetof (struct ev_stat, timer)); } else #endif if (types & EV_TIMER) cb (EV_A_ EV_TIMER, ANHE_w (timers [i])); #if EV_PERIODIC_ENABLE if (types & EV_PERIODIC) for (i = periodiccnt + HEAP0; i-- > HEAP0; ) cb (EV_A_ EV_PERIODIC, ANHE_w (periodics [i])); #endif #if EV_IDLE_ENABLE if (types & EV_IDLE) for (j = NUMPRI; j--; ) for (i = idlecnt [j]; i--; ) cb (EV_A_ EV_IDLE, idles [j][i]); #endif #if EV_FORK_ENABLE if (types & EV_FORK) for (i = forkcnt; i--; ) if (ev_cb (forks [i]) != embed_fork_cb) cb (EV_A_ EV_FORK, forks [i]); #endif #if EV_ASYNC_ENABLE if (types & EV_ASYNC) for (i = asynccnt; i--; ) cb (EV_A_ EV_ASYNC, asyncs [i]); #endif #if EV_PREPARE_ENABLE if (types & EV_PREPARE) for (i = preparecnt; i--; ) # if EV_EMBED_ENABLE if (ev_cb (prepares [i]) != embed_prepare_cb) # endif cb (EV_A_ EV_PREPARE, prepares [i]); #endif #if EV_CHECK_ENABLE if (types & EV_CHECK) for (i = checkcnt; i--; ) cb (EV_A_ EV_CHECK, checks [i]); #endif #if EV_SIGNAL_ENABLE if (types & EV_SIGNAL) for (i = 0; i < EV_NSIG - 1; ++i) for (wl = signals [i].head; wl; ) { wn = wl->next; cb (EV_A_ EV_SIGNAL, wl); wl = wn; } #endif #if EV_CHILD_ENABLE if (types & EV_CHILD) for (i = (EV_PID_HASHSIZE); i--; ) for (wl = childs [i]; wl; ) { wn = wl->next; cb (EV_A_ EV_CHILD, wl); wl = wn; } #endif /* EV_STAT 0x00001000 /* stat data changed */ /* EV_EMBED 0x00010000 /* embedded event loop needs sweep */ } #endif #if EV_MULTIPLICITY #include "ev_wrap.h" #endif nsca-ng-1.6/lib/ev/ev.h000066400000000000000000000721101344421036200146510ustar00rootroot00000000000000/* * libev native API header * * Copyright (c) 2007-2018 Marc Alexander Lehmann * All rights reserved. * * Redistribution and use in source and binary forms, with or without modifica- * tion, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER- * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH- * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License ("GPL") version 2 or any later version, * in which case the provisions of the GPL are applicable instead of * the above. If you wish to allow the use of your version of this file * only under the terms of the GPL and not to allow others to use your * version of this file under the BSD license, indicate your decision * by deleting the provisions above and replace them with the notice * and other provisions required by the GPL. If you do not delete the * provisions above, a recipient may use your version of this file under * either the BSD or the GPL. */ #ifndef EV_H_ #define EV_H_ #ifdef __cplusplus # define EV_CPP(x) x # if __cplusplus >= 201103L # define EV_NOEXCEPT noexcept # else # define EV_NOEXCEPT # endif #else # define EV_CPP(x) # define EV_NOEXCEPT #endif #define EV_THROW EV_NOEXCEPT /* pre-4.25, do not use in new code */ EV_CPP(extern "C" {) /*****************************************************************************/ /* pre-4.0 compatibility */ #ifndef EV_COMPAT3 # define EV_COMPAT3 1 #endif #ifndef EV_FEATURES # if defined __OPTIMIZE_SIZE__ # define EV_FEATURES 0x7c # else # define EV_FEATURES 0x7f # endif #endif #define EV_FEATURE_CODE ((EV_FEATURES) & 1) #define EV_FEATURE_DATA ((EV_FEATURES) & 2) #define EV_FEATURE_CONFIG ((EV_FEATURES) & 4) #define EV_FEATURE_API ((EV_FEATURES) & 8) #define EV_FEATURE_WATCHERS ((EV_FEATURES) & 16) #define EV_FEATURE_BACKENDS ((EV_FEATURES) & 32) #define EV_FEATURE_OS ((EV_FEATURES) & 64) /* these priorities are inclusive, higher priorities will be invoked earlier */ #ifndef EV_MINPRI # define EV_MINPRI (EV_FEATURE_CONFIG ? -2 : 0) #endif #ifndef EV_MAXPRI # define EV_MAXPRI (EV_FEATURE_CONFIG ? +2 : 0) #endif #ifndef EV_MULTIPLICITY # define EV_MULTIPLICITY EV_FEATURE_CONFIG #endif #ifndef EV_PERIODIC_ENABLE # define EV_PERIODIC_ENABLE EV_FEATURE_WATCHERS #endif #ifndef EV_STAT_ENABLE # define EV_STAT_ENABLE EV_FEATURE_WATCHERS #endif #ifndef EV_PREPARE_ENABLE # define EV_PREPARE_ENABLE EV_FEATURE_WATCHERS #endif #ifndef EV_CHECK_ENABLE # define EV_CHECK_ENABLE EV_FEATURE_WATCHERS #endif #ifndef EV_IDLE_ENABLE # define EV_IDLE_ENABLE EV_FEATURE_WATCHERS #endif #ifndef EV_FORK_ENABLE # define EV_FORK_ENABLE EV_FEATURE_WATCHERS #endif #ifndef EV_CLEANUP_ENABLE # define EV_CLEANUP_ENABLE EV_FEATURE_WATCHERS #endif #ifndef EV_SIGNAL_ENABLE # define EV_SIGNAL_ENABLE EV_FEATURE_WATCHERS #endif #ifndef EV_CHILD_ENABLE # ifdef _WIN32 # define EV_CHILD_ENABLE 0 # else # define EV_CHILD_ENABLE EV_FEATURE_WATCHERS #endif #endif #ifndef EV_ASYNC_ENABLE # define EV_ASYNC_ENABLE EV_FEATURE_WATCHERS #endif #ifndef EV_EMBED_ENABLE # define EV_EMBED_ENABLE EV_FEATURE_WATCHERS #endif #ifndef EV_WALK_ENABLE # define EV_WALK_ENABLE 0 /* not yet */ #endif /*****************************************************************************/ #if EV_CHILD_ENABLE && !EV_SIGNAL_ENABLE # undef EV_SIGNAL_ENABLE # define EV_SIGNAL_ENABLE 1 #endif /*****************************************************************************/ typedef double ev_tstamp; #include /* for memmove */ #ifndef EV_ATOMIC_T # include # define EV_ATOMIC_T sig_atomic_t volatile #endif #if EV_STAT_ENABLE # ifdef _WIN32 # include # include # endif # include #endif /* support multiple event loops? */ #if EV_MULTIPLICITY struct ev_loop; # define EV_P struct ev_loop *loop /* a loop as sole parameter in a declaration */ # define EV_P_ EV_P, /* a loop as first of multiple parameters */ # define EV_A loop /* a loop as sole argument to a function call */ # define EV_A_ EV_A, /* a loop as first of multiple arguments */ # define EV_DEFAULT_UC ev_default_loop_uc_ () /* the default loop, if initialised, as sole arg */ # define EV_DEFAULT_UC_ EV_DEFAULT_UC, /* the default loop as first of multiple arguments */ # define EV_DEFAULT ev_default_loop (0) /* the default loop as sole arg */ # define EV_DEFAULT_ EV_DEFAULT, /* the default loop as first of multiple arguments */ #else # define EV_P void # define EV_P_ # define EV_A # define EV_A_ # define EV_DEFAULT # define EV_DEFAULT_ # define EV_DEFAULT_UC # define EV_DEFAULT_UC_ # undef EV_EMBED_ENABLE #endif /* EV_INLINE is used for functions in header files */ #if __STDC_VERSION__ >= 199901L || __GNUC__ >= 3 # define EV_INLINE static inline #else # define EV_INLINE static #endif #ifdef EV_API_STATIC # define EV_API_DECL static #else # define EV_API_DECL extern #endif /* EV_PROTOTYPES can be used to switch of prototype declarations */ #ifndef EV_PROTOTYPES # define EV_PROTOTYPES 1 #endif /*****************************************************************************/ #define EV_VERSION_MAJOR 4 #define EV_VERSION_MINOR 25 /* eventmask, revents, events... */ enum { EV_UNDEF = (int)0xFFFFFFFF, /* guaranteed to be invalid */ EV_NONE = 0x00, /* no events */ EV_READ = 0x01, /* ev_io detected read will not block */ EV_WRITE = 0x02, /* ev_io detected write will not block */ EV__IOFDSET = 0x80, /* internal use only */ EV_IO = EV_READ, /* alias for type-detection */ EV_TIMER = 0x00000100, /* timer timed out */ #if EV_COMPAT3 EV_TIMEOUT = EV_TIMER, /* pre 4.0 API compatibility */ #endif EV_PERIODIC = 0x00000200, /* periodic timer timed out */ EV_SIGNAL = 0x00000400, /* signal was received */ EV_CHILD = 0x00000800, /* child/pid had status change */ EV_STAT = 0x00001000, /* stat data changed */ EV_IDLE = 0x00002000, /* event loop is idling */ EV_PREPARE = 0x00004000, /* event loop about to poll */ EV_CHECK = 0x00008000, /* event loop finished poll */ EV_EMBED = 0x00010000, /* embedded event loop needs sweep */ EV_FORK = 0x00020000, /* event loop resumed in child */ EV_CLEANUP = 0x00040000, /* event loop resumed in child */ EV_ASYNC = 0x00080000, /* async intra-loop signal */ EV_CUSTOM = 0x01000000, /* for use by user code */ EV_ERROR = (int)0x80000000 /* sent when an error occurs */ }; /* can be used to add custom fields to all watchers, while losing binary compatibility */ #ifndef EV_COMMON # define EV_COMMON void *data; #endif #ifndef EV_CB_DECLARE # define EV_CB_DECLARE(type) void (*cb)(EV_P_ struct type *w, int revents); #endif #ifndef EV_CB_INVOKE # define EV_CB_INVOKE(watcher,revents) (watcher)->cb (EV_A_ (watcher), (revents)) #endif /* not official, do not use */ #define EV_CB(type,name) void name (EV_P_ struct ev_ ## type *w, int revents) /* * struct member types: * private: you may look at them, but not change them, * and they might not mean anything to you. * ro: can be read anytime, but only changed when the watcher isn't active. * rw: can be read and modified anytime, even when the watcher is active. * * some internal details that might be helpful for debugging: * * active is either 0, which means the watcher is not active, * or the array index of the watcher (periodics, timers) * or the array index + 1 (most other watchers) * or simply 1 for watchers that aren't in some array. * pending is either 0, in which case the watcher isn't, * or the array index + 1 in the pendings array. */ #if EV_MINPRI == EV_MAXPRI # define EV_DECL_PRIORITY #elif !defined (EV_DECL_PRIORITY) # define EV_DECL_PRIORITY int priority; #endif /* shared by all watchers */ #define EV_WATCHER(type) \ int active; /* private */ \ int pending; /* private */ \ EV_DECL_PRIORITY /* private */ \ EV_COMMON /* rw */ \ EV_CB_DECLARE (type) /* private */ #define EV_WATCHER_LIST(type) \ EV_WATCHER (type) \ struct ev_watcher_list *next; /* private */ #define EV_WATCHER_TIME(type) \ EV_WATCHER (type) \ ev_tstamp at; /* private */ /* base class, nothing to see here unless you subclass */ typedef struct ev_watcher { EV_WATCHER (ev_watcher) } ev_watcher; /* base class, nothing to see here unless you subclass */ typedef struct ev_watcher_list { EV_WATCHER_LIST (ev_watcher_list) } ev_watcher_list; /* base class, nothing to see here unless you subclass */ typedef struct ev_watcher_time { EV_WATCHER_TIME (ev_watcher_time) } ev_watcher_time; /* invoked when fd is either EV_READable or EV_WRITEable */ /* revent EV_READ, EV_WRITE */ typedef struct ev_io { EV_WATCHER_LIST (ev_io) int fd; /* ro */ int events; /* ro */ } ev_io; /* invoked after a specific time, repeatable (based on monotonic clock) */ /* revent EV_TIMEOUT */ typedef struct ev_timer { EV_WATCHER_TIME (ev_timer) ev_tstamp repeat; /* rw */ } ev_timer; /* invoked at some specific time, possibly repeating at regular intervals (based on UTC) */ /* revent EV_PERIODIC */ typedef struct ev_periodic { EV_WATCHER_TIME (ev_periodic) ev_tstamp offset; /* rw */ ev_tstamp interval; /* rw */ ev_tstamp (*reschedule_cb)(struct ev_periodic *w, ev_tstamp now) EV_NOEXCEPT; /* rw */ } ev_periodic; /* invoked when the given signal has been received */ /* revent EV_SIGNAL */ typedef struct ev_signal { EV_WATCHER_LIST (ev_signal) int signum; /* ro */ } ev_signal; /* invoked when sigchld is received and waitpid indicates the given pid */ /* revent EV_CHILD */ /* does not support priorities */ typedef struct ev_child { EV_WATCHER_LIST (ev_child) int flags; /* private */ int pid; /* ro */ int rpid; /* rw, holds the received pid */ int rstatus; /* rw, holds the exit status, use the macros from sys/wait.h */ } ev_child; #if EV_STAT_ENABLE /* st_nlink = 0 means missing file or other error */ # ifdef _WIN32 typedef struct _stati64 ev_statdata; # else typedef struct stat ev_statdata; # endif /* invoked each time the stat data changes for a given path */ /* revent EV_STAT */ typedef struct ev_stat { EV_WATCHER_LIST (ev_stat) ev_timer timer; /* private */ ev_tstamp interval; /* ro */ const char *path; /* ro */ ev_statdata prev; /* ro */ ev_statdata attr; /* ro */ int wd; /* wd for inotify, fd for kqueue */ } ev_stat; #endif #if EV_IDLE_ENABLE /* invoked when the nothing else needs to be done, keeps the process from blocking */ /* revent EV_IDLE */ typedef struct ev_idle { EV_WATCHER (ev_idle) } ev_idle; #endif /* invoked for each run of the mainloop, just before the blocking call */ /* you can still change events in any way you like */ /* revent EV_PREPARE */ typedef struct ev_prepare { EV_WATCHER (ev_prepare) } ev_prepare; /* invoked for each run of the mainloop, just after the blocking call */ /* revent EV_CHECK */ typedef struct ev_check { EV_WATCHER (ev_check) } ev_check; #if EV_FORK_ENABLE /* the callback gets invoked before check in the child process when a fork was detected */ /* revent EV_FORK */ typedef struct ev_fork { EV_WATCHER (ev_fork) } ev_fork; #endif #if EV_CLEANUP_ENABLE /* is invoked just before the loop gets destroyed */ /* revent EV_CLEANUP */ typedef struct ev_cleanup { EV_WATCHER (ev_cleanup) } ev_cleanup; #endif #if EV_EMBED_ENABLE /* used to embed an event loop inside another */ /* the callback gets invoked when the event loop has handled events, and can be 0 */ typedef struct ev_embed { EV_WATCHER (ev_embed) struct ev_loop *other; /* ro */ ev_io io; /* private */ ev_prepare prepare; /* private */ ev_check check; /* unused */ ev_timer timer; /* unused */ ev_periodic periodic; /* unused */ ev_idle idle; /* unused */ ev_fork fork; /* private */ #if EV_CLEANUP_ENABLE ev_cleanup cleanup; /* unused */ #endif } ev_embed; #endif #if EV_ASYNC_ENABLE /* invoked when somebody calls ev_async_send on the watcher */ /* revent EV_ASYNC */ typedef struct ev_async { EV_WATCHER (ev_async) EV_ATOMIC_T sent; /* private */ } ev_async; # define ev_async_pending(w) (+(w)->sent) #endif /* the presence of this union forces similar struct layout */ union ev_any_watcher { struct ev_watcher w; struct ev_watcher_list wl; struct ev_io io; struct ev_timer timer; struct ev_periodic periodic; struct ev_signal signal; struct ev_child child; #if EV_STAT_ENABLE struct ev_stat stat; #endif #if EV_IDLE_ENABLE struct ev_idle idle; #endif struct ev_prepare prepare; struct ev_check check; #if EV_FORK_ENABLE struct ev_fork fork; #endif #if EV_CLEANUP_ENABLE struct ev_cleanup cleanup; #endif #if EV_EMBED_ENABLE struct ev_embed embed; #endif #if EV_ASYNC_ENABLE struct ev_async async; #endif }; /* flag bits for ev_default_loop and ev_loop_new */ enum { /* the default */ EVFLAG_AUTO = 0x00000000U, /* not quite a mask */ /* flag bits */ EVFLAG_NOENV = 0x01000000U, /* do NOT consult environment */ EVFLAG_FORKCHECK = 0x02000000U, /* check for a fork in each iteration */ /* debugging/feature disable */ EVFLAG_NOINOTIFY = 0x00100000U, /* do not attempt to use inotify */ #if EV_COMPAT3 EVFLAG_NOSIGFD = 0, /* compatibility to pre-3.9 */ #endif EVFLAG_SIGNALFD = 0x00200000U, /* attempt to use signalfd */ EVFLAG_NOSIGMASK = 0x00400000U /* avoid modifying the signal mask */ }; /* method bits to be ored together */ enum { EVBACKEND_SELECT = 0x00000001U, /* available just about anywhere */ EVBACKEND_POLL = 0x00000002U, /* !win, !aix, broken on osx */ EVBACKEND_EPOLL = 0x00000004U, /* linux */ EVBACKEND_KQUEUE = 0x00000008U, /* bsd, broken on osx */ EVBACKEND_DEVPOLL = 0x00000010U, /* solaris 8 */ /* NYI */ EVBACKEND_PORT = 0x00000020U, /* solaris 10 */ EVBACKEND_ALL = 0x0000003FU, /* all known backends */ EVBACKEND_MASK = 0x0000FFFFU /* all future backends */ }; #if EV_PROTOTYPES EV_API_DECL int ev_version_major (void) EV_NOEXCEPT; EV_API_DECL int ev_version_minor (void) EV_NOEXCEPT; EV_API_DECL unsigned int ev_supported_backends (void) EV_NOEXCEPT; EV_API_DECL unsigned int ev_recommended_backends (void) EV_NOEXCEPT; EV_API_DECL unsigned int ev_embeddable_backends (void) EV_NOEXCEPT; EV_API_DECL ev_tstamp ev_time (void) EV_NOEXCEPT; EV_API_DECL void ev_sleep (ev_tstamp delay) EV_NOEXCEPT; /* sleep for a while */ /* Sets the allocation function to use, works like realloc. * It is used to allocate and free memory. * If it returns zero when memory needs to be allocated, the library might abort * or take some potentially destructive action. * The default is your system realloc function. */ EV_API_DECL void ev_set_allocator (void *(*cb)(void *ptr, long size) EV_NOEXCEPT) EV_NOEXCEPT; /* set the callback function to call on a * retryable syscall error * (such as failed select, poll, epoll_wait) */ EV_API_DECL void ev_set_syserr_cb (void (*cb)(const char *msg) EV_NOEXCEPT) EV_NOEXCEPT; #if EV_MULTIPLICITY /* the default loop is the only one that handles signals and child watchers */ /* you can call this as often as you like */ EV_API_DECL struct ev_loop *ev_default_loop (unsigned int flags EV_CPP (= 0)) EV_NOEXCEPT; #ifdef EV_API_STATIC EV_API_DECL struct ev_loop *ev_default_loop_ptr; #endif EV_INLINE struct ev_loop * ev_default_loop_uc_ (void) EV_NOEXCEPT { extern struct ev_loop *ev_default_loop_ptr; return ev_default_loop_ptr; } EV_INLINE int ev_is_default_loop (EV_P) EV_NOEXCEPT { return EV_A == EV_DEFAULT_UC; } /* create and destroy alternative loops that don't handle signals */ EV_API_DECL struct ev_loop *ev_loop_new (unsigned int flags EV_CPP (= 0)) EV_NOEXCEPT; EV_API_DECL ev_tstamp ev_now (EV_P) EV_NOEXCEPT; /* time w.r.t. timers and the eventloop, updated after each poll */ #else EV_API_DECL int ev_default_loop (unsigned int flags EV_CPP (= 0)) EV_NOEXCEPT; /* returns true when successful */ EV_API_DECL ev_tstamp ev_rt_now; EV_INLINE ev_tstamp ev_now (void) EV_NOEXCEPT { return ev_rt_now; } /* looks weird, but ev_is_default_loop (EV_A) still works if this exists */ EV_INLINE int ev_is_default_loop (void) EV_NOEXCEPT { return 1; } #endif /* multiplicity */ /* destroy event loops, also works for the default loop */ EV_API_DECL void ev_loop_destroy (EV_P); /* this needs to be called after fork, to duplicate the loop */ /* when you want to re-use it in the child */ /* you can call it in either the parent or the child */ /* you can actually call it at any time, anywhere :) */ EV_API_DECL void ev_loop_fork (EV_P) EV_NOEXCEPT; EV_API_DECL unsigned int ev_backend (EV_P) EV_NOEXCEPT; /* backend in use by loop */ EV_API_DECL void ev_now_update (EV_P) EV_NOEXCEPT; /* update event loop time */ #if EV_WALK_ENABLE /* walk (almost) all watchers in the loop of a given type, invoking the */ /* callback on every such watcher. The callback might stop the watcher, */ /* but do nothing else with the loop */ EV_API_DECL void ev_walk (EV_P_ int types, void (*cb)(EV_P_ int type, void *w)) EV_NOEXCEPT; #endif #endif /* prototypes */ /* ev_run flags values */ enum { EVRUN_NOWAIT = 1, /* do not block/wait */ EVRUN_ONCE = 2 /* block *once* only */ }; /* ev_break how values */ enum { EVBREAK_CANCEL = 0, /* undo unloop */ EVBREAK_ONE = 1, /* unloop once */ EVBREAK_ALL = 2 /* unloop all loops */ }; #if EV_PROTOTYPES EV_API_DECL int ev_run (EV_P_ int flags EV_CPP (= 0)); EV_API_DECL void ev_break (EV_P_ int how EV_CPP (= EVBREAK_ONE)) EV_NOEXCEPT; /* break out of the loop */ /* * ref/unref can be used to add or remove a refcount on the mainloop. every watcher * keeps one reference. if you have a long-running watcher you never unregister that * should not keep ev_loop from running, unref() after starting, and ref() before stopping. */ EV_API_DECL void ev_ref (EV_P) EV_NOEXCEPT; EV_API_DECL void ev_unref (EV_P) EV_NOEXCEPT; /* * convenience function, wait for a single event, without registering an event watcher * if timeout is < 0, do wait indefinitely */ EV_API_DECL void ev_once (EV_P_ int fd, int events, ev_tstamp timeout, void (*cb)(int revents, void *arg), void *arg) EV_NOEXCEPT; # if EV_FEATURE_API EV_API_DECL unsigned int ev_iteration (EV_P) EV_NOEXCEPT; /* number of loop iterations */ EV_API_DECL unsigned int ev_depth (EV_P) EV_NOEXCEPT; /* #ev_loop enters - #ev_loop leaves */ EV_API_DECL void ev_verify (EV_P) EV_NOEXCEPT; /* abort if loop data corrupted */ EV_API_DECL void ev_set_io_collect_interval (EV_P_ ev_tstamp interval) EV_NOEXCEPT; /* sleep at least this time, default 0 */ EV_API_DECL void ev_set_timeout_collect_interval (EV_P_ ev_tstamp interval) EV_NOEXCEPT; /* sleep at least this time, default 0 */ /* advanced stuff for threading etc. support, see docs */ EV_API_DECL void ev_set_userdata (EV_P_ void *data) EV_NOEXCEPT; EV_API_DECL void *ev_userdata (EV_P) EV_NOEXCEPT; typedef void (*ev_loop_callback)(EV_P); EV_API_DECL void ev_set_invoke_pending_cb (EV_P_ ev_loop_callback invoke_pending_cb) EV_NOEXCEPT; /* C++ doesn't allow the use of the ev_loop_callback typedef here, so we need to spell it out */ EV_API_DECL void ev_set_loop_release_cb (EV_P_ void (*release)(EV_P) EV_NOEXCEPT, void (*acquire)(EV_P) EV_NOEXCEPT) EV_NOEXCEPT; EV_API_DECL unsigned int ev_pending_count (EV_P) EV_NOEXCEPT; /* number of pending events, if any */ EV_API_DECL void ev_invoke_pending (EV_P); /* invoke all pending watchers */ /* * stop/start the timer handling. */ EV_API_DECL void ev_suspend (EV_P) EV_NOEXCEPT; EV_API_DECL void ev_resume (EV_P) EV_NOEXCEPT; #endif #endif /* these may evaluate ev multiple times, and the other arguments at most once */ /* either use ev_init + ev_TYPE_set, or the ev_TYPE_init macro, below, to first initialise a watcher */ #define ev_init(ev,cb_) do { \ ((ev_watcher *)(void *)(ev))->active = \ ((ev_watcher *)(void *)(ev))->pending = 0; \ ev_set_priority ((ev), 0); \ ev_set_cb ((ev), cb_); \ } while (0) #define ev_io_set(ev,fd_,events_) do { (ev)->fd = (fd_); (ev)->events = (events_) | EV__IOFDSET; } while (0) #define ev_timer_set(ev,after_,repeat_) do { ((ev_watcher_time *)(ev))->at = (after_); (ev)->repeat = (repeat_); } while (0) #define ev_periodic_set(ev,ofs_,ival_,rcb_) do { (ev)->offset = (ofs_); (ev)->interval = (ival_); (ev)->reschedule_cb = (rcb_); } while (0) #define ev_signal_set(ev,signum_) do { (ev)->signum = (signum_); } while (0) #define ev_child_set(ev,pid_,trace_) do { (ev)->pid = (pid_); (ev)->flags = !!(trace_); } while (0) #define ev_stat_set(ev,path_,interval_) do { (ev)->path = (path_); (ev)->interval = (interval_); (ev)->wd = -2; } while (0) #define ev_idle_set(ev) /* nop, yes, this is a serious in-joke */ #define ev_prepare_set(ev) /* nop, yes, this is a serious in-joke */ #define ev_check_set(ev) /* nop, yes, this is a serious in-joke */ #define ev_embed_set(ev,other_) do { (ev)->other = (other_); } while (0) #define ev_fork_set(ev) /* nop, yes, this is a serious in-joke */ #define ev_cleanup_set(ev) /* nop, yes, this is a serious in-joke */ #define ev_async_set(ev) /* nop, yes, this is a serious in-joke */ #define ev_io_init(ev,cb,fd,events) do { ev_init ((ev), (cb)); ev_io_set ((ev),(fd),(events)); } while (0) #define ev_timer_init(ev,cb,after,repeat) do { ev_init ((ev), (cb)); ev_timer_set ((ev),(after),(repeat)); } while (0) #define ev_periodic_init(ev,cb,ofs,ival,rcb) do { ev_init ((ev), (cb)); ev_periodic_set ((ev),(ofs),(ival),(rcb)); } while (0) #define ev_signal_init(ev,cb,signum) do { ev_init ((ev), (cb)); ev_signal_set ((ev), (signum)); } while (0) #define ev_child_init(ev,cb,pid,trace) do { ev_init ((ev), (cb)); ev_child_set ((ev),(pid),(trace)); } while (0) #define ev_stat_init(ev,cb,path,interval) do { ev_init ((ev), (cb)); ev_stat_set ((ev),(path),(interval)); } while (0) #define ev_idle_init(ev,cb) do { ev_init ((ev), (cb)); ev_idle_set ((ev)); } while (0) #define ev_prepare_init(ev,cb) do { ev_init ((ev), (cb)); ev_prepare_set ((ev)); } while (0) #define ev_check_init(ev,cb) do { ev_init ((ev), (cb)); ev_check_set ((ev)); } while (0) #define ev_embed_init(ev,cb,other) do { ev_init ((ev), (cb)); ev_embed_set ((ev),(other)); } while (0) #define ev_fork_init(ev,cb) do { ev_init ((ev), (cb)); ev_fork_set ((ev)); } while (0) #define ev_cleanup_init(ev,cb) do { ev_init ((ev), (cb)); ev_cleanup_set ((ev)); } while (0) #define ev_async_init(ev,cb) do { ev_init ((ev), (cb)); ev_async_set ((ev)); } while (0) #define ev_is_pending(ev) (0 + ((ev_watcher *)(void *)(ev))->pending) /* ro, true when watcher is waiting for callback invocation */ #define ev_is_active(ev) (0 + ((ev_watcher *)(void *)(ev))->active) /* ro, true when the watcher has been started */ #define ev_cb_(ev) (ev)->cb /* rw */ #define ev_cb(ev) (memmove (&ev_cb_ (ev), &((ev_watcher *)(ev))->cb, sizeof (ev_cb_ (ev))), (ev)->cb) #if EV_MINPRI == EV_MAXPRI # define ev_priority(ev) ((ev), EV_MINPRI) # define ev_set_priority(ev,pri) ((ev), (pri)) #else # define ev_priority(ev) (+(((ev_watcher *)(void *)(ev))->priority)) # define ev_set_priority(ev,pri) ( (ev_watcher *)(void *)(ev))->priority = (pri) #endif #define ev_periodic_at(ev) (+((ev_watcher_time *)(ev))->at) #ifndef ev_set_cb # define ev_set_cb(ev,cb_) (ev_cb_ (ev) = (cb_), memmove (&((ev_watcher *)(ev))->cb, &ev_cb_ (ev), sizeof (ev_cb_ (ev)))) #endif /* stopping (enabling, adding) a watcher does nothing if it is already running */ /* stopping (disabling, deleting) a watcher does nothing unless it's already running */ #if EV_PROTOTYPES /* feeds an event into a watcher as if the event actually occurred */ /* accepts any ev_watcher type */ EV_API_DECL void ev_feed_event (EV_P_ void *w, int revents) EV_NOEXCEPT; EV_API_DECL void ev_feed_fd_event (EV_P_ int fd, int revents) EV_NOEXCEPT; #if EV_SIGNAL_ENABLE EV_API_DECL void ev_feed_signal (int signum) EV_NOEXCEPT; EV_API_DECL void ev_feed_signal_event (EV_P_ int signum) EV_NOEXCEPT; #endif EV_API_DECL void ev_invoke (EV_P_ void *w, int revents); EV_API_DECL int ev_clear_pending (EV_P_ void *w) EV_NOEXCEPT; EV_API_DECL void ev_io_start (EV_P_ ev_io *w) EV_NOEXCEPT; EV_API_DECL void ev_io_stop (EV_P_ ev_io *w) EV_NOEXCEPT; EV_API_DECL void ev_timer_start (EV_P_ ev_timer *w) EV_NOEXCEPT; EV_API_DECL void ev_timer_stop (EV_P_ ev_timer *w) EV_NOEXCEPT; /* stops if active and no repeat, restarts if active and repeating, starts if inactive and repeating */ EV_API_DECL void ev_timer_again (EV_P_ ev_timer *w) EV_NOEXCEPT; /* return remaining time */ EV_API_DECL ev_tstamp ev_timer_remaining (EV_P_ ev_timer *w) EV_NOEXCEPT; #if EV_PERIODIC_ENABLE EV_API_DECL void ev_periodic_start (EV_P_ ev_periodic *w) EV_NOEXCEPT; EV_API_DECL void ev_periodic_stop (EV_P_ ev_periodic *w) EV_NOEXCEPT; EV_API_DECL void ev_periodic_again (EV_P_ ev_periodic *w) EV_NOEXCEPT; #endif /* only supported in the default loop */ #if EV_SIGNAL_ENABLE EV_API_DECL void ev_signal_start (EV_P_ ev_signal *w) EV_NOEXCEPT; EV_API_DECL void ev_signal_stop (EV_P_ ev_signal *w) EV_NOEXCEPT; #endif /* only supported in the default loop */ # if EV_CHILD_ENABLE EV_API_DECL void ev_child_start (EV_P_ ev_child *w) EV_NOEXCEPT; EV_API_DECL void ev_child_stop (EV_P_ ev_child *w) EV_NOEXCEPT; # endif # if EV_STAT_ENABLE EV_API_DECL void ev_stat_start (EV_P_ ev_stat *w) EV_NOEXCEPT; EV_API_DECL void ev_stat_stop (EV_P_ ev_stat *w) EV_NOEXCEPT; EV_API_DECL void ev_stat_stat (EV_P_ ev_stat *w) EV_NOEXCEPT; # endif # if EV_IDLE_ENABLE EV_API_DECL void ev_idle_start (EV_P_ ev_idle *w) EV_NOEXCEPT; EV_API_DECL void ev_idle_stop (EV_P_ ev_idle *w) EV_NOEXCEPT; # endif #if EV_PREPARE_ENABLE EV_API_DECL void ev_prepare_start (EV_P_ ev_prepare *w) EV_NOEXCEPT; EV_API_DECL void ev_prepare_stop (EV_P_ ev_prepare *w) EV_NOEXCEPT; #endif #if EV_CHECK_ENABLE EV_API_DECL void ev_check_start (EV_P_ ev_check *w) EV_NOEXCEPT; EV_API_DECL void ev_check_stop (EV_P_ ev_check *w) EV_NOEXCEPT; #endif # if EV_FORK_ENABLE EV_API_DECL void ev_fork_start (EV_P_ ev_fork *w) EV_NOEXCEPT; EV_API_DECL void ev_fork_stop (EV_P_ ev_fork *w) EV_NOEXCEPT; # endif # if EV_CLEANUP_ENABLE EV_API_DECL void ev_cleanup_start (EV_P_ ev_cleanup *w) EV_NOEXCEPT; EV_API_DECL void ev_cleanup_stop (EV_P_ ev_cleanup *w) EV_NOEXCEPT; # endif # if EV_EMBED_ENABLE /* only supported when loop to be embedded is in fact embeddable */ EV_API_DECL void ev_embed_start (EV_P_ ev_embed *w) EV_NOEXCEPT; EV_API_DECL void ev_embed_stop (EV_P_ ev_embed *w) EV_NOEXCEPT; EV_API_DECL void ev_embed_sweep (EV_P_ ev_embed *w) EV_NOEXCEPT; # endif # if EV_ASYNC_ENABLE EV_API_DECL void ev_async_start (EV_P_ ev_async *w) EV_NOEXCEPT; EV_API_DECL void ev_async_stop (EV_P_ ev_async *w) EV_NOEXCEPT; EV_API_DECL void ev_async_send (EV_P_ ev_async *w) EV_NOEXCEPT; # endif #if EV_COMPAT3 #define EVLOOP_NONBLOCK EVRUN_NOWAIT #define EVLOOP_ONESHOT EVRUN_ONCE #define EVUNLOOP_CANCEL EVBREAK_CANCEL #define EVUNLOOP_ONE EVBREAK_ONE #define EVUNLOOP_ALL EVBREAK_ALL #if EV_PROTOTYPES EV_INLINE void ev_loop (EV_P_ int flags) { ev_run (EV_A_ flags); } EV_INLINE void ev_unloop (EV_P_ int how ) { ev_break (EV_A_ how ); } EV_INLINE void ev_default_destroy (void) { ev_loop_destroy (EV_DEFAULT); } EV_INLINE void ev_default_fork (void) { ev_loop_fork (EV_DEFAULT); } #if EV_FEATURE_API EV_INLINE unsigned int ev_loop_count (EV_P) { return ev_iteration (EV_A); } EV_INLINE unsigned int ev_loop_depth (EV_P) { return ev_depth (EV_A); } EV_INLINE void ev_loop_verify (EV_P) { ev_verify (EV_A); } #endif #endif #else typedef struct ev_loop ev_loop; #endif #endif EV_CPP(}) #endif nsca-ng-1.6/lib/ev/ev_epoll.c000066400000000000000000000232531344421036200160430ustar00rootroot00000000000000/* * libev epoll fd activity backend * * Copyright (c) 2007,2008,2009,2010,2011 Marc Alexander Lehmann * All rights reserved. * * Redistribution and use in source and binary forms, with or without modifica- * tion, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER- * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH- * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License ("GPL") version 2 or any later version, * in which case the provisions of the GPL are applicable instead of * the above. If you wish to allow the use of your version of this file * only under the terms of the GPL and not to allow others to use your * version of this file under the BSD license, indicate your decision * by deleting the provisions above and replace them with the notice * and other provisions required by the GPL. If you do not delete the * provisions above, a recipient may use your version of this file under * either the BSD or the GPL. */ /* * general notes about epoll: * * a) epoll silently removes fds from the fd set. as nothing tells us * that an fd has been removed otherwise, we have to continually * "rearm" fds that we suspect *might* have changed (same * problem with kqueue, but much less costly there). * b) the fact that ADD != MOD creates a lot of extra syscalls due to a) * and seems not to have any advantage. * c) the inability to handle fork or file descriptors (think dup) * limits the applicability over poll, so this is not a generic * poll replacement. * d) epoll doesn't work the same as select with many file descriptors * (such as files). while not critical, no other advanced interface * seems to share this (rather non-unixy) limitation. * e) epoll claims to be embeddable, but in practise you never get * a ready event for the epoll fd (broken: <=2.6.26, working: >=2.6.32). * f) epoll_ctl returning EPERM means the fd is always ready. * * lots of "weird code" and complication handling in this file is due * to these design problems with epoll, as we try very hard to avoid * epoll_ctl syscalls for common usage patterns and handle the breakage * ensuing from receiving events for closed and otherwise long gone * file descriptors. */ #include #define EV_EMASK_EPERM 0x80 static void epoll_modify (EV_P_ int fd, int oev, int nev) { struct epoll_event ev; unsigned char oldmask; /* * we handle EPOLL_CTL_DEL by ignoring it here * on the assumption that the fd is gone anyways * if that is wrong, we have to handle the spurious * event in epoll_poll. * if the fd is added again, we try to ADD it, and, if that * fails, we assume it still has the same eventmask. */ if (!nev) return; oldmask = anfds [fd].emask; anfds [fd].emask = nev; /* store the generation counter in the upper 32 bits, the fd in the lower 32 bits */ ev.data.u64 = (uint64_t)(uint32_t)fd | ((uint64_t)(uint32_t)++anfds [fd].egen << 32); ev.events = (nev & EV_READ ? EPOLLIN : 0) | (nev & EV_WRITE ? EPOLLOUT : 0); if (expect_true (!epoll_ctl (backend_fd, oev && oldmask != nev ? EPOLL_CTL_MOD : EPOLL_CTL_ADD, fd, &ev))) return; if (expect_true (errno == ENOENT)) { /* if ENOENT then the fd went away, so try to do the right thing */ if (!nev) goto dec_egen; if (!epoll_ctl (backend_fd, EPOLL_CTL_ADD, fd, &ev)) return; } else if (expect_true (errno == EEXIST)) { /* EEXIST means we ignored a previous DEL, but the fd is still active */ /* if the kernel mask is the same as the new mask, we assume it hasn't changed */ if (oldmask == nev) goto dec_egen; if (!epoll_ctl (backend_fd, EPOLL_CTL_MOD, fd, &ev)) return; } else if (expect_true (errno == EPERM)) { /* EPERM means the fd is always ready, but epoll is too snobbish */ /* to handle it, unlike select or poll. */ anfds [fd].emask = EV_EMASK_EPERM; /* add fd to epoll_eperms, if not already inside */ if (!(oldmask & EV_EMASK_EPERM)) { array_needsize (int, epoll_eperms, epoll_epermmax, epoll_epermcnt + 1, EMPTY2); epoll_eperms [epoll_epermcnt++] = fd; } return; } fd_kill (EV_A_ fd); dec_egen: /* we didn't successfully call epoll_ctl, so decrement the generation counter again */ --anfds [fd].egen; } static void epoll_poll (EV_P_ ev_tstamp timeout) { int i; int eventcnt; if (expect_false (epoll_epermcnt)) timeout = 0.; /* epoll wait times cannot be larger than (LONG_MAX - 999UL) / HZ msecs, which is below */ /* the default libev max wait time, however. */ EV_RELEASE_CB; eventcnt = epoll_wait (backend_fd, epoll_events, epoll_eventmax, timeout * 1e3); EV_ACQUIRE_CB; if (expect_false (eventcnt < 0)) { if (errno != EINTR) ev_syserr ("(libev) epoll_wait"); return; } for (i = 0; i < eventcnt; ++i) { struct epoll_event *ev = epoll_events + i; int fd = (uint32_t)ev->data.u64; /* mask out the lower 32 bits */ int want = anfds [fd].events; int got = (ev->events & (EPOLLOUT | EPOLLERR | EPOLLHUP) ? EV_WRITE : 0) | (ev->events & (EPOLLIN | EPOLLERR | EPOLLHUP) ? EV_READ : 0); /* * check for spurious notification. * this only finds spurious notifications on egen updates * other spurious notifications will be found by epoll_ctl, below * we assume that fd is always in range, as we never shrink the anfds array */ if (expect_false ((uint32_t)anfds [fd].egen != (uint32_t)(ev->data.u64 >> 32))) { /* recreate kernel state */ postfork |= 2; continue; } if (expect_false (got & ~want)) { anfds [fd].emask = want; /* * we received an event but are not interested in it, try mod or del * this often happens because we optimistically do not unregister fds * when we are no longer interested in them, but also when we get spurious * notifications for fds from another process. this is partially handled * above with the gencounter check (== our fd is not the event fd), and * partially here, when epoll_ctl returns an error (== a child has the fd * but we closed it). */ ev->events = (want & EV_READ ? EPOLLIN : 0) | (want & EV_WRITE ? EPOLLOUT : 0); /* pre-2.6.9 kernels require a non-null pointer with EPOLL_CTL_DEL, */ /* which is fortunately easy to do for us. */ if (epoll_ctl (backend_fd, want ? EPOLL_CTL_MOD : EPOLL_CTL_DEL, fd, ev)) { postfork |= 2; /* an error occurred, recreate kernel state */ continue; } } fd_event (EV_A_ fd, got); } /* if the receive array was full, increase its size */ if (expect_false (eventcnt == epoll_eventmax)) { ev_free (epoll_events); epoll_eventmax = array_nextsize (sizeof (struct epoll_event), epoll_eventmax, epoll_eventmax + 1); epoll_events = (struct epoll_event *)ev_malloc (sizeof (struct epoll_event) * epoll_eventmax); } /* now synthesize events for all fds where epoll fails, while select works... */ for (i = epoll_epermcnt; i--; ) { int fd = epoll_eperms [i]; unsigned char events = anfds [fd].events & (EV_READ | EV_WRITE); if (anfds [fd].emask & EV_EMASK_EPERM && events) fd_event (EV_A_ fd, events); else { epoll_eperms [i] = epoll_eperms [--epoll_epermcnt]; anfds [fd].emask = 0; } } } inline_size int epoll_init (EV_P_ int flags) { #if defined EPOLL_CLOEXEC && !defined __ANDROID__ backend_fd = epoll_create1 (EPOLL_CLOEXEC); if (backend_fd < 0 && (errno == EINVAL || errno == ENOSYS)) #endif backend_fd = epoll_create (256); if (backend_fd < 0) return 0; fcntl (backend_fd, F_SETFD, FD_CLOEXEC); backend_mintime = 1e-3; /* epoll does sometimes return early, this is just to avoid the worst */ backend_modify = epoll_modify; backend_poll = epoll_poll; epoll_eventmax = 64; /* initial number of events receivable per poll */ epoll_events = (struct epoll_event *)ev_malloc (sizeof (struct epoll_event) * epoll_eventmax); return EVBACKEND_EPOLL; } inline_size void epoll_destroy (EV_P) { ev_free (epoll_events); array_free (epoll_eperm, EMPTY); } inline_size void epoll_fork (EV_P) { close (backend_fd); while ((backend_fd = epoll_create (256)) < 0) ev_syserr ("(libev) epoll_create"); fcntl (backend_fd, F_SETFD, FD_CLOEXEC); fd_rearm_all (EV_A); } nsca-ng-1.6/lib/ev/ev_kqueue.c000066400000000000000000000152321344421036200162250ustar00rootroot00000000000000/* * libev kqueue backend * * Copyright (c) 2007,2008,2009,2010,2011,2012,2013 Marc Alexander Lehmann * All rights reserved. * * Redistribution and use in source and binary forms, with or without modifica- * tion, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER- * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH- * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License ("GPL") version 2 or any later version, * in which case the provisions of the GPL are applicable instead of * the above. If you wish to allow the use of your version of this file * only under the terms of the GPL and not to allow others to use your * version of this file under the BSD license, indicate your decision * by deleting the provisions above and replace them with the notice * and other provisions required by the GPL. If you do not delete the * provisions above, a recipient may use your version of this file under * either the BSD or the GPL. */ #include #include #include #include #include inline_speed void kqueue_change (EV_P_ int fd, int filter, int flags, int fflags) { ++kqueue_changecnt; array_needsize (struct kevent, kqueue_changes, kqueue_changemax, kqueue_changecnt, EMPTY2); EV_SET (&kqueue_changes [kqueue_changecnt - 1], fd, filter, flags, fflags, 0, 0); } /* OS X at least needs this */ #ifndef EV_ENABLE # define EV_ENABLE 0 #endif #ifndef NOTE_EOF # define NOTE_EOF 0 #endif static void kqueue_modify (EV_P_ int fd, int oev, int nev) { if (oev != nev) { if (oev & EV_READ) kqueue_change (EV_A_ fd, EVFILT_READ , EV_DELETE, 0); if (oev & EV_WRITE) kqueue_change (EV_A_ fd, EVFILT_WRITE, EV_DELETE, 0); } /* to detect close/reopen reliably, we have to re-add */ /* event requests even when oev == nev */ if (nev & EV_READ) kqueue_change (EV_A_ fd, EVFILT_READ , EV_ADD | EV_ENABLE, NOTE_EOF); if (nev & EV_WRITE) kqueue_change (EV_A_ fd, EVFILT_WRITE, EV_ADD | EV_ENABLE, NOTE_EOF); } static void kqueue_poll (EV_P_ ev_tstamp timeout) { int res, i; struct timespec ts; /* need to resize so there is enough space for errors */ if (kqueue_changecnt > kqueue_eventmax) { ev_free (kqueue_events); kqueue_eventmax = array_nextsize (sizeof (struct kevent), kqueue_eventmax, kqueue_changecnt); kqueue_events = (struct kevent *)ev_malloc (sizeof (struct kevent) * kqueue_eventmax); } EV_RELEASE_CB; EV_TS_SET (ts, timeout); res = kevent (backend_fd, kqueue_changes, kqueue_changecnt, kqueue_events, kqueue_eventmax, &ts); EV_ACQUIRE_CB; kqueue_changecnt = 0; if (expect_false (res < 0)) { if (errno != EINTR) ev_syserr ("(libev) kevent"); return; } for (i = 0; i < res; ++i) { int fd = kqueue_events [i].ident; if (expect_false (kqueue_events [i].flags & EV_ERROR)) { int err = kqueue_events [i].data; /* we are only interested in errors for fds that we are interested in :) */ if (anfds [fd].events) { if (err == ENOENT) /* resubmit changes on ENOENT */ kqueue_modify (EV_A_ fd, 0, anfds [fd].events); else if (err == EBADF) /* on EBADF, we re-check the fd */ { if (fd_valid (fd)) kqueue_modify (EV_A_ fd, 0, anfds [fd].events); else fd_kill (EV_A_ fd); } else /* on all other errors, we error out on the fd */ fd_kill (EV_A_ fd); } } else fd_event ( EV_A_ fd, kqueue_events [i].filter == EVFILT_READ ? EV_READ : kqueue_events [i].filter == EVFILT_WRITE ? EV_WRITE : 0 ); } if (expect_false (res == kqueue_eventmax)) { ev_free (kqueue_events); kqueue_eventmax = array_nextsize (sizeof (struct kevent), kqueue_eventmax, kqueue_eventmax + 1); kqueue_events = (struct kevent *)ev_malloc (sizeof (struct kevent) * kqueue_eventmax); } } inline_size int kqueue_init (EV_P_ int flags) { /* initialize the kernel queue */ kqueue_fd_pid = getpid (); if ((backend_fd = kqueue ()) < 0) return 0; fcntl (backend_fd, F_SETFD, FD_CLOEXEC); /* not sure if necessary, hopefully doesn't hurt */ backend_mintime = 1e-9; /* apparently, they did the right thing in freebsd */ backend_modify = kqueue_modify; backend_poll = kqueue_poll; kqueue_eventmax = 64; /* initial number of events receivable per poll */ kqueue_events = (struct kevent *)ev_malloc (sizeof (struct kevent) * kqueue_eventmax); kqueue_changes = 0; kqueue_changemax = 0; kqueue_changecnt = 0; return EVBACKEND_KQUEUE; } inline_size void kqueue_destroy (EV_P) { ev_free (kqueue_events); ev_free (kqueue_changes); } inline_size void kqueue_fork (EV_P) { /* some BSD kernels don't just destroy the kqueue itself, * but also close the fd, which isn't documented, and * impossible to support properly. * we remember the pid of the kqueue call and only close * the fd if the pid is still the same. * this leaks fds on sane kernels, but BSD interfaces are * notoriously buggy and rarely get fixed. */ pid_t newpid = getpid (); if (newpid == kqueue_fd_pid) close (backend_fd); kqueue_fd_pid = newpid; while ((backend_fd = kqueue ()) < 0) ev_syserr ("(libev) kqueue"); fcntl (backend_fd, F_SETFD, FD_CLOEXEC); /* re-register interest in fds */ fd_rearm_all (EV_A); } /* sys/event.h defines EV_ERROR */ #undef EV_ERROR nsca-ng-1.6/lib/ev/ev_poll.c000066400000000000000000000105331344421036200156730ustar00rootroot00000000000000/* * libev poll fd activity backend * * Copyright (c) 2007,2008,2009,2010,2011 Marc Alexander Lehmann * All rights reserved. * * Redistribution and use in source and binary forms, with or without modifica- * tion, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER- * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH- * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License ("GPL") version 2 or any later version, * in which case the provisions of the GPL are applicable instead of * the above. If you wish to allow the use of your version of this file * only under the terms of the GPL and not to allow others to use your * version of this file under the BSD license, indicate your decision * by deleting the provisions above and replace them with the notice * and other provisions required by the GPL. If you do not delete the * provisions above, a recipient may use your version of this file under * either the BSD or the GPL. */ #include inline_size void pollidx_init (int *base, int count) { /* consider using memset (.., -1, ...), which is practically guaranteed * to work on all systems implementing poll */ while (count--) *base++ = -1; } static void poll_modify (EV_P_ int fd, int oev, int nev) { int idx; if (oev == nev) return; array_needsize (int, pollidxs, pollidxmax, fd + 1, pollidx_init); idx = pollidxs [fd]; if (idx < 0) /* need to allocate a new pollfd */ { pollidxs [fd] = idx = pollcnt++; array_needsize (struct pollfd, polls, pollmax, pollcnt, EMPTY2); polls [idx].fd = fd; } assert (polls [idx].fd == fd); if (nev) polls [idx].events = (nev & EV_READ ? POLLIN : 0) | (nev & EV_WRITE ? POLLOUT : 0); else /* remove pollfd */ { pollidxs [fd] = -1; if (expect_true (idx < --pollcnt)) { polls [idx] = polls [pollcnt]; pollidxs [polls [idx].fd] = idx; } } } static void poll_poll (EV_P_ ev_tstamp timeout) { struct pollfd *p; int res; EV_RELEASE_CB; res = poll (polls, pollcnt, timeout * 1e3); EV_ACQUIRE_CB; if (expect_false (res < 0)) { if (errno == EBADF) fd_ebadf (EV_A); else if (errno == ENOMEM && !syserr_cb) fd_enomem (EV_A); else if (errno != EINTR) ev_syserr ("(libev) poll"); } else for (p = polls; res; ++p) { assert (("libev: poll() returned illegal result, broken BSD kernel?", p < polls + pollcnt)); if (expect_false (p->revents)) /* this expect is debatable */ { --res; if (expect_false (p->revents & POLLNVAL)) fd_kill (EV_A_ p->fd); else fd_event ( EV_A_ p->fd, (p->revents & (POLLOUT | POLLERR | POLLHUP) ? EV_WRITE : 0) | (p->revents & (POLLIN | POLLERR | POLLHUP) ? EV_READ : 0) ); } } } inline_size int poll_init (EV_P_ int flags) { backend_mintime = 1e-3; backend_modify = poll_modify; backend_poll = poll_poll; pollidxs = 0; pollidxmax = 0; polls = 0; pollmax = 0; pollcnt = 0; return EVBACKEND_POLL; } inline_size void poll_destroy (EV_P) { ev_free (pollidxs); ev_free (polls); } nsca-ng-1.6/lib/ev/ev_port.c000066400000000000000000000144041344421036200157120ustar00rootroot00000000000000/* * libev solaris event port backend * * Copyright (c) 2007,2008,2009,2010,2011 Marc Alexander Lehmann * All rights reserved. * * Redistribution and use in source and binary forms, with or without modifica- * tion, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER- * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH- * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License ("GPL") version 2 or any later version, * in which case the provisions of the GPL are applicable instead of * the above. If you wish to allow the use of your version of this file * only under the terms of the GPL and not to allow others to use your * version of this file under the BSD license, indicate your decision * by deleting the provisions above and replace them with the notice * and other provisions required by the GPL. If you do not delete the * provisions above, a recipient may use your version of this file under * either the BSD or the GPL. */ /* useful reading: * * http://bugs.opensolaris.org/view_bug.do?bug_id=6268715 (random results) * http://bugs.opensolaris.org/view_bug.do?bug_id=6455223 (just totally broken) * http://bugs.opensolaris.org/view_bug.do?bug_id=6873782 (manpage ETIME) * http://bugs.opensolaris.org/view_bug.do?bug_id=6874410 (implementation ETIME) * http://www.mail-archive.com/networking-discuss@opensolaris.org/msg11898.html ETIME vs. nget * http://src.opensolaris.org/source/xref/onnv/onnv-gate/usr/src/lib/libc/port/gen/event_port.c (libc) * http://cvs.opensolaris.org/source/xref/onnv/onnv-gate/usr/src/uts/common/fs/portfs/port.c#1325 (kernel) */ #include #include #include #include #include #include inline_speed void port_associate_and_check (EV_P_ int fd, int ev) { if (0 > port_associate ( backend_fd, PORT_SOURCE_FD, fd, (ev & EV_READ ? POLLIN : 0) | (ev & EV_WRITE ? POLLOUT : 0), 0 ) ) { if (errno == EBADFD) fd_kill (EV_A_ fd); else ev_syserr ("(libev) port_associate"); } } static void port_modify (EV_P_ int fd, int oev, int nev) { /* we need to reassociate no matter what, as closes are * once more silently being discarded. */ if (!nev) { if (oev) port_dissociate (backend_fd, PORT_SOURCE_FD, fd); } else port_associate_and_check (EV_A_ fd, nev); } static void port_poll (EV_P_ ev_tstamp timeout) { int res, i; struct timespec ts; uint_t nget = 1; /* we initialise this to something we will skip in the loop, as */ /* port_getn can return with nget unchanged, but no indication */ /* whether it was the original value or has been updated :/ */ port_events [0].portev_source = 0; EV_RELEASE_CB; EV_TS_SET (ts, timeout); res = port_getn (backend_fd, port_events, port_eventmax, &nget, &ts); EV_ACQUIRE_CB; /* port_getn may or may not set nget on error */ /* so we rely on port_events [0].portev_source not being updated */ if (res == -1 && errno != ETIME && errno != EINTR) ev_syserr ("(libev) port_getn (see http://bugs.opensolaris.org/view_bug.do?bug_id=6268715, try LIBEV_FLAGS=3 env variable)"); for (i = 0; i < nget; ++i) { if (port_events [i].portev_source == PORT_SOURCE_FD) { int fd = port_events [i].portev_object; fd_event ( EV_A_ fd, (port_events [i].portev_events & (POLLOUT | POLLERR | POLLHUP) ? EV_WRITE : 0) | (port_events [i].portev_events & (POLLIN | POLLERR | POLLHUP) ? EV_READ : 0) ); fd_change (EV_A_ fd, EV__IOFDSET); } } if (expect_false (nget == port_eventmax)) { ev_free (port_events); port_eventmax = array_nextsize (sizeof (port_event_t), port_eventmax, port_eventmax + 1); port_events = (port_event_t *)ev_malloc (sizeof (port_event_t) * port_eventmax); } } inline_size int port_init (EV_P_ int flags) { /* Initialize the kernel queue */ if ((backend_fd = port_create ()) < 0) return 0; assert (("libev: PORT_SOURCE_FD must not be zero", PORT_SOURCE_FD)); fcntl (backend_fd, F_SETFD, FD_CLOEXEC); /* not sure if necessary, hopefully doesn't hurt */ /* if my reading of the opensolaris kernel sources are correct, then * opensolaris does something very stupid: it checks if the time has already * elapsed and doesn't round up if that is the case,m otherwise it DOES round * up. Since we can't know what the case is, we need to guess by using a * "large enough" timeout. Normally, 1e-9 would be correct. */ backend_mintime = 1e-3; /* needed to compensate for port_getn returning early */ backend_modify = port_modify; backend_poll = port_poll; port_eventmax = 64; /* initial number of events receivable per poll */ port_events = (port_event_t *)ev_malloc (sizeof (port_event_t) * port_eventmax); return EVBACKEND_PORT; } inline_size void port_destroy (EV_P) { ev_free (port_events); } inline_size void port_fork (EV_P) { close (backend_fd); while ((backend_fd = port_create ()) < 0) ev_syserr ("(libev) port"); fcntl (backend_fd, F_SETFD, FD_CLOEXEC); /* re-register interest in fds */ fd_rearm_all (EV_A); } nsca-ng-1.6/lib/ev/ev_select.c000066400000000000000000000211551344421036200162060ustar00rootroot00000000000000/* * libev select fd activity backend * * Copyright (c) 2007,2008,2009,2010,2011 Marc Alexander Lehmann * All rights reserved. * * Redistribution and use in source and binary forms, with or without modifica- * tion, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER- * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH- * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License ("GPL") version 2 or any later version, * in which case the provisions of the GPL are applicable instead of * the above. If you wish to allow the use of your version of this file * only under the terms of the GPL and not to allow others to use your * version of this file under the BSD license, indicate your decision * by deleting the provisions above and replace them with the notice * and other provisions required by the GPL. If you do not delete the * provisions above, a recipient may use your version of this file under * either the BSD or the GPL. */ #ifndef _WIN32 /* for unix systems */ # include # ifndef __hpux /* for REAL unix systems */ # include # endif #endif #ifndef EV_SELECT_USE_FD_SET # ifdef NFDBITS # define EV_SELECT_USE_FD_SET 0 # else # define EV_SELECT_USE_FD_SET 1 # endif #endif #if EV_SELECT_IS_WINSOCKET # undef EV_SELECT_USE_FD_SET # define EV_SELECT_USE_FD_SET 1 # undef NFDBITS # define NFDBITS 0 #endif #if !EV_SELECT_USE_FD_SET # define NFDBYTES (NFDBITS / 8) #endif #include static void select_modify (EV_P_ int fd, int oev, int nev) { if (oev == nev) return; { #if EV_SELECT_USE_FD_SET #if EV_SELECT_IS_WINSOCKET SOCKET handle = anfds [fd].handle; #else int handle = fd; #endif assert (("libev: fd >= FD_SETSIZE passed to fd_set-based select backend", fd < FD_SETSIZE)); /* FD_SET is broken on windows (it adds the fd to a set twice or more, * which eventually leads to overflows). Need to call it only on changes. */ #if EV_SELECT_IS_WINSOCKET if ((oev ^ nev) & EV_READ) #endif if (nev & EV_READ) FD_SET (handle, (fd_set *)vec_ri); else FD_CLR (handle, (fd_set *)vec_ri); #if EV_SELECT_IS_WINSOCKET if ((oev ^ nev) & EV_WRITE) #endif if (nev & EV_WRITE) FD_SET (handle, (fd_set *)vec_wi); else FD_CLR (handle, (fd_set *)vec_wi); #else int word = fd / NFDBITS; fd_mask mask = 1UL << (fd % NFDBITS); if (expect_false (vec_max <= word)) { int new_max = word + 1; vec_ri = ev_realloc (vec_ri, new_max * NFDBYTES); vec_ro = ev_realloc (vec_ro, new_max * NFDBYTES); /* could free/malloc */ vec_wi = ev_realloc (vec_wi, new_max * NFDBYTES); vec_wo = ev_realloc (vec_wo, new_max * NFDBYTES); /* could free/malloc */ #ifdef _WIN32 vec_eo = ev_realloc (vec_eo, new_max * NFDBYTES); /* could free/malloc */ #endif for (; vec_max < new_max; ++vec_max) ((fd_mask *)vec_ri) [vec_max] = ((fd_mask *)vec_wi) [vec_max] = 0; } ((fd_mask *)vec_ri) [word] |= mask; if (!(nev & EV_READ)) ((fd_mask *)vec_ri) [word] &= ~mask; ((fd_mask *)vec_wi) [word] |= mask; if (!(nev & EV_WRITE)) ((fd_mask *)vec_wi) [word] &= ~mask; #endif } } static void select_poll (EV_P_ ev_tstamp timeout) { struct timeval tv; int res; int fd_setsize; EV_RELEASE_CB; EV_TV_SET (tv, timeout); #if EV_SELECT_USE_FD_SET fd_setsize = sizeof (fd_set); #else fd_setsize = vec_max * NFDBYTES; #endif memcpy (vec_ro, vec_ri, fd_setsize); memcpy (vec_wo, vec_wi, fd_setsize); #ifdef _WIN32 /* pass in the write set as except set. * the idea behind this is to work around a windows bug that causes * errors to be reported as an exception and not by setting * the writable bit. this is so uncontrollably lame. */ memcpy (vec_eo, vec_wi, fd_setsize); res = select (vec_max * NFDBITS, (fd_set *)vec_ro, (fd_set *)vec_wo, (fd_set *)vec_eo, &tv); #elif EV_SELECT_USE_FD_SET fd_setsize = anfdmax < FD_SETSIZE ? anfdmax : FD_SETSIZE; res = select (fd_setsize, (fd_set *)vec_ro, (fd_set *)vec_wo, 0, &tv); #else res = select (vec_max * NFDBITS, (fd_set *)vec_ro, (fd_set *)vec_wo, 0, &tv); #endif EV_ACQUIRE_CB; if (expect_false (res < 0)) { #if EV_SELECT_IS_WINSOCKET errno = WSAGetLastError (); #endif #ifdef WSABASEERR /* on windows, select returns incompatible error codes, fix this */ if (errno >= WSABASEERR && errno < WSABASEERR + 1000) if (errno == WSAENOTSOCK) errno = EBADF; else errno -= WSABASEERR; #endif #ifdef _WIN32 /* select on windows erroneously returns EINVAL when no fd sets have been * provided (this is documented). what microsoft doesn't tell you that this bug * exists even when the fd sets _are_ provided, so we have to check for this bug * here and emulate by sleeping manually. * we also get EINVAL when the timeout is invalid, but we ignore this case here * and assume that EINVAL always means: you have to wait manually. */ if (errno == EINVAL) { if (timeout) { unsigned long ms = timeout * 1e3; Sleep (ms ? ms : 1); } return; } #endif if (errno == EBADF) fd_ebadf (EV_A); else if (errno == ENOMEM && !syserr_cb) fd_enomem (EV_A); else if (errno != EINTR) ev_syserr ("(libev) select"); return; } #if EV_SELECT_USE_FD_SET { int fd; for (fd = 0; fd < anfdmax; ++fd) if (anfds [fd].events) { int events = 0; #if EV_SELECT_IS_WINSOCKET SOCKET handle = anfds [fd].handle; #else int handle = fd; #endif if (FD_ISSET (handle, (fd_set *)vec_ro)) events |= EV_READ; if (FD_ISSET (handle, (fd_set *)vec_wo)) events |= EV_WRITE; #ifdef _WIN32 if (FD_ISSET (handle, (fd_set *)vec_eo)) events |= EV_WRITE; #endif if (expect_true (events)) fd_event (EV_A_ fd, events); } } #else { int word, bit; for (word = vec_max; word--; ) { fd_mask word_r = ((fd_mask *)vec_ro) [word]; fd_mask word_w = ((fd_mask *)vec_wo) [word]; #ifdef _WIN32 word_w |= ((fd_mask *)vec_eo) [word]; #endif if (word_r || word_w) for (bit = NFDBITS; bit--; ) { fd_mask mask = 1UL << bit; int events = 0; events |= word_r & mask ? EV_READ : 0; events |= word_w & mask ? EV_WRITE : 0; if (expect_true (events)) fd_event (EV_A_ word * NFDBITS + bit, events); } } } #endif } inline_size int select_init (EV_P_ int flags) { backend_mintime = 1e-6; backend_modify = select_modify; backend_poll = select_poll; #if EV_SELECT_USE_FD_SET vec_ri = ev_malloc (sizeof (fd_set)); FD_ZERO ((fd_set *)vec_ri); vec_ro = ev_malloc (sizeof (fd_set)); vec_wi = ev_malloc (sizeof (fd_set)); FD_ZERO ((fd_set *)vec_wi); vec_wo = ev_malloc (sizeof (fd_set)); #ifdef _WIN32 vec_eo = ev_malloc (sizeof (fd_set)); #endif #else vec_max = 0; vec_ri = 0; vec_ro = 0; vec_wi = 0; vec_wo = 0; #ifdef _WIN32 vec_eo = 0; #endif #endif return EVBACKEND_SELECT; } inline_size void select_destroy (EV_P) { ev_free (vec_ri); ev_free (vec_ro); ev_free (vec_wi); ev_free (vec_wo); #ifdef _WIN32 ev_free (vec_eo); #endif } nsca-ng-1.6/lib/ev/ev_vars.h000066400000000000000000000141331344421036200157050ustar00rootroot00000000000000/* * loop member variable declarations * * Copyright (c) 2007,2008,2009,2010,2011,2012,2013 Marc Alexander Lehmann * All rights reserved. * * Redistribution and use in source and binary forms, with or without modifica- * tion, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER- * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH- * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License ("GPL") version 2 or any later version, * in which case the provisions of the GPL are applicable instead of * the above. If you wish to allow the use of your version of this file * only under the terms of the GPL and not to allow others to use your * version of this file under the BSD license, indicate your decision * by deleting the provisions above and replace them with the notice * and other provisions required by the GPL. If you do not delete the * provisions above, a recipient may use your version of this file under * either the BSD or the GPL. */ #define VARx(type,name) VAR(name, type name) VARx(ev_tstamp, now_floor) /* last time we refreshed rt_time */ VARx(ev_tstamp, mn_now) /* monotonic clock "now" */ VARx(ev_tstamp, rtmn_diff) /* difference realtime - monotonic time */ /* for reverse feeding of events */ VARx(W *, rfeeds) VARx(int, rfeedmax) VARx(int, rfeedcnt) VAR (pendings, ANPENDING *pendings [NUMPRI]) VAR (pendingmax, int pendingmax [NUMPRI]) VAR (pendingcnt, int pendingcnt [NUMPRI]) VARx(int, pendingpri) /* highest priority currently pending */ VARx(ev_prepare, pending_w) /* dummy pending watcher */ VARx(ev_tstamp, io_blocktime) VARx(ev_tstamp, timeout_blocktime) VARx(int, backend) VARx(int, activecnt) /* total number of active events ("refcount") */ VARx(EV_ATOMIC_T, loop_done) /* signal by ev_break */ VARx(int, backend_fd) VARx(ev_tstamp, backend_mintime) /* assumed typical timer resolution */ VAR (backend_modify, void (*backend_modify)(EV_P_ int fd, int oev, int nev)) VAR (backend_poll , void (*backend_poll)(EV_P_ ev_tstamp timeout)) VARx(ANFD *, anfds) VARx(int, anfdmax) VAR (evpipe, int evpipe [2]) VARx(ev_io, pipe_w) VARx(EV_ATOMIC_T, pipe_write_wanted) VARx(EV_ATOMIC_T, pipe_write_skipped) #if !defined(_WIN32) || EV_GENWRAP VARx(pid_t, curpid) #endif VARx(char, postfork) /* true if we need to recreate kernel state after fork */ #if EV_USE_SELECT || EV_GENWRAP VARx(void *, vec_ri) VARx(void *, vec_ro) VARx(void *, vec_wi) VARx(void *, vec_wo) #if defined(_WIN32) || EV_GENWRAP VARx(void *, vec_eo) #endif VARx(int, vec_max) #endif #if EV_USE_POLL || EV_GENWRAP VARx(struct pollfd *, polls) VARx(int, pollmax) VARx(int, pollcnt) VARx(int *, pollidxs) /* maps fds into structure indices */ VARx(int, pollidxmax) #endif #if EV_USE_EPOLL || EV_GENWRAP VARx(struct epoll_event *, epoll_events) VARx(int, epoll_eventmax) VARx(int *, epoll_eperms) VARx(int, epoll_epermcnt) VARx(int, epoll_epermmax) #endif #if EV_USE_KQUEUE || EV_GENWRAP VARx(pid_t, kqueue_fd_pid) VARx(struct kevent *, kqueue_changes) VARx(int, kqueue_changemax) VARx(int, kqueue_changecnt) VARx(struct kevent *, kqueue_events) VARx(int, kqueue_eventmax) #endif #if EV_USE_PORT || EV_GENWRAP VARx(struct port_event *, port_events) VARx(int, port_eventmax) #endif #if EV_USE_IOCP || EV_GENWRAP VARx(HANDLE, iocp) #endif VARx(int *, fdchanges) VARx(int, fdchangemax) VARx(int, fdchangecnt) VARx(ANHE *, timers) VARx(int, timermax) VARx(int, timercnt) #if EV_PERIODIC_ENABLE || EV_GENWRAP VARx(ANHE *, periodics) VARx(int, periodicmax) VARx(int, periodiccnt) #endif #if EV_IDLE_ENABLE || EV_GENWRAP VAR (idles, ev_idle **idles [NUMPRI]) VAR (idlemax, int idlemax [NUMPRI]) VAR (idlecnt, int idlecnt [NUMPRI]) #endif VARx(int, idleall) /* total number */ VARx(struct ev_prepare **, prepares) VARx(int, preparemax) VARx(int, preparecnt) VARx(struct ev_check **, checks) VARx(int, checkmax) VARx(int, checkcnt) #if EV_FORK_ENABLE || EV_GENWRAP VARx(struct ev_fork **, forks) VARx(int, forkmax) VARx(int, forkcnt) #endif #if EV_CLEANUP_ENABLE || EV_GENWRAP VARx(struct ev_cleanup **, cleanups) VARx(int, cleanupmax) VARx(int, cleanupcnt) #endif #if EV_ASYNC_ENABLE || EV_GENWRAP VARx(EV_ATOMIC_T, async_pending) VARx(struct ev_async **, asyncs) VARx(int, asyncmax) VARx(int, asynccnt) #endif #if EV_USE_INOTIFY || EV_GENWRAP VARx(int, fs_fd) VARx(ev_io, fs_w) VARx(char, fs_2625) /* whether we are running in linux 2.6.25 or newer */ VAR (fs_hash, ANFS fs_hash [EV_INOTIFY_HASHSIZE]) #endif VARx(EV_ATOMIC_T, sig_pending) #if EV_USE_SIGNALFD || EV_GENWRAP VARx(int, sigfd) VARx(ev_io, sigfd_w) VARx(sigset_t, sigfd_set) #endif VARx(unsigned int, origflags) /* original loop flags */ #if EV_FEATURE_API || EV_GENWRAP VARx(unsigned int, loop_count) /* total number of loop iterations/blocks */ VARx(unsigned int, loop_depth) /* #ev_run enters - #ev_run leaves */ VARx(void *, userdata) /* C++ doesn't support the ev_loop_callback typedef here. stinks. */ VAR (release_cb, void (*release_cb)(EV_P) EV_NOEXCEPT) VAR (acquire_cb, void (*acquire_cb)(EV_P) EV_NOEXCEPT) VAR (invoke_cb , ev_loop_callback invoke_cb) #endif #undef VARx nsca-ng-1.6/lib/ev/ev_win32.c000066400000000000000000000123101344421036200156620ustar00rootroot00000000000000/* * libev win32 compatibility cruft (_not_ a backend) * * Copyright (c) 2007,2008,2009 Marc Alexander Lehmann * All rights reserved. * * Redistribution and use in source and binary forms, with or without modifica- * tion, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER- * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE- * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH- * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License ("GPL") version 2 or any later version, * in which case the provisions of the GPL are applicable instead of * the above. If you wish to allow the use of your version of this file * only under the terms of the GPL and not to allow others to use your * version of this file under the BSD license, indicate your decision * by deleting the provisions above and replace them with the notice * and other provisions required by the GPL. If you do not delete the * provisions above, a recipient may use your version of this file under * either the BSD or the GPL. */ #ifdef _WIN32 /* note: the comment below could not be substantiated, but what would I care */ /* MSDN says this is required to handle SIGFPE */ /* my wild guess would be that using something floating-pointy is required */ /* for the crt to do something about it */ volatile double SIGFPE_REQ = 0.0f; static SOCKET ev_tcp_socket (void) { #if EV_USE_WSASOCKET return WSASocket (AF_INET, SOCK_STREAM, 0, 0, 0, 0); #else return socket (AF_INET, SOCK_STREAM, 0); #endif } /* oh, the humanity! */ static int ev_pipe (int filedes [2]) { struct sockaddr_in addr = { 0 }; int addr_size = sizeof (addr); struct sockaddr_in adr2; int adr2_size = sizeof (adr2); SOCKET listener; SOCKET sock [2] = { -1, -1 }; if ((listener = ev_tcp_socket ()) == INVALID_SOCKET) return -1; addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK); addr.sin_port = 0; if (bind (listener, (struct sockaddr *)&addr, addr_size)) goto fail; if (getsockname (listener, (struct sockaddr *)&addr, &addr_size)) goto fail; if (listen (listener, 1)) goto fail; if ((sock [0] = ev_tcp_socket ()) == INVALID_SOCKET) goto fail; if (connect (sock [0], (struct sockaddr *)&addr, addr_size)) goto fail; /* TODO: returns INVALID_SOCKET on winsock accept, not < 0. fix it */ /* when convenient, probably by just removing error checking altogether? */ if ((sock [1] = accept (listener, 0, 0)) < 0) goto fail; /* windows vista returns fantasy port numbers for sockets: * example for two interconnected tcp sockets: * * (Socket::unpack_sockaddr_in getsockname $sock0)[0] == 53364 * (Socket::unpack_sockaddr_in getpeername $sock0)[0] == 53363 * (Socket::unpack_sockaddr_in getsockname $sock1)[0] == 53363 * (Socket::unpack_sockaddr_in getpeername $sock1)[0] == 53365 * * wow! tridirectional sockets! * * this way of checking ports seems to work: */ if (getpeername (sock [0], (struct sockaddr *)&addr, &addr_size)) goto fail; if (getsockname (sock [1], (struct sockaddr *)&adr2, &adr2_size)) goto fail; errno = WSAEINVAL; if (addr_size != adr2_size || addr.sin_addr.s_addr != adr2.sin_addr.s_addr /* just to be sure, I mean, it's windows */ || addr.sin_port != adr2.sin_port) goto fail; closesocket (listener); #if EV_SELECT_IS_WINSOCKET filedes [0] = EV_WIN32_HANDLE_TO_FD (sock [0]); filedes [1] = EV_WIN32_HANDLE_TO_FD (sock [1]); #else /* when select isn't winsocket, we also expect socket, connect, accept etc. * to work on fds */ filedes [0] = sock [0]; filedes [1] = sock [1]; #endif return 0; fail: closesocket (listener); if (sock [0] != INVALID_SOCKET) closesocket (sock [0]); if (sock [1] != INVALID_SOCKET) closesocket (sock [1]); return -1; } #undef pipe #define pipe(filedes) ev_pipe (filedes) #define EV_HAVE_EV_TIME 1 ev_tstamp ev_time (void) { FILETIME ft; ULARGE_INTEGER ui; GetSystemTimeAsFileTime (&ft); ui.u.LowPart = ft.dwLowDateTime; ui.u.HighPart = ft.dwHighDateTime; /* msvc cannot convert ulonglong to double... yes, it is that sucky */ return (LONGLONG)(ui.QuadPart - 116444736000000000) * 1e-7; } #endif nsca-ng-1.6/lib/ev/ev_wrap.h000066400000000000000000000126061344421036200157060ustar00rootroot00000000000000/* DO NOT EDIT, automatically generated by update_ev_wrap */ #ifndef EV_WRAP_H #define EV_WRAP_H #define acquire_cb ((loop)->acquire_cb) #define activecnt ((loop)->activecnt) #define anfdmax ((loop)->anfdmax) #define anfds ((loop)->anfds) #define async_pending ((loop)->async_pending) #define asynccnt ((loop)->asynccnt) #define asyncmax ((loop)->asyncmax) #define asyncs ((loop)->asyncs) #define backend ((loop)->backend) #define backend_fd ((loop)->backend_fd) #define backend_mintime ((loop)->backend_mintime) #define backend_modify ((loop)->backend_modify) #define backend_poll ((loop)->backend_poll) #define checkcnt ((loop)->checkcnt) #define checkmax ((loop)->checkmax) #define checks ((loop)->checks) #define cleanupcnt ((loop)->cleanupcnt) #define cleanupmax ((loop)->cleanupmax) #define cleanups ((loop)->cleanups) #define curpid ((loop)->curpid) #define epoll_epermcnt ((loop)->epoll_epermcnt) #define epoll_epermmax ((loop)->epoll_epermmax) #define epoll_eperms ((loop)->epoll_eperms) #define epoll_eventmax ((loop)->epoll_eventmax) #define epoll_events ((loop)->epoll_events) #define evpipe ((loop)->evpipe) #define fdchangecnt ((loop)->fdchangecnt) #define fdchangemax ((loop)->fdchangemax) #define fdchanges ((loop)->fdchanges) #define forkcnt ((loop)->forkcnt) #define forkmax ((loop)->forkmax) #define forks ((loop)->forks) #define fs_2625 ((loop)->fs_2625) #define fs_fd ((loop)->fs_fd) #define fs_hash ((loop)->fs_hash) #define fs_w ((loop)->fs_w) #define idleall ((loop)->idleall) #define idlecnt ((loop)->idlecnt) #define idlemax ((loop)->idlemax) #define idles ((loop)->idles) #define invoke_cb ((loop)->invoke_cb) #define io_blocktime ((loop)->io_blocktime) #define iocp ((loop)->iocp) #define kqueue_changecnt ((loop)->kqueue_changecnt) #define kqueue_changemax ((loop)->kqueue_changemax) #define kqueue_changes ((loop)->kqueue_changes) #define kqueue_eventmax ((loop)->kqueue_eventmax) #define kqueue_events ((loop)->kqueue_events) #define kqueue_fd_pid ((loop)->kqueue_fd_pid) #define loop_count ((loop)->loop_count) #define loop_depth ((loop)->loop_depth) #define loop_done ((loop)->loop_done) #define mn_now ((loop)->mn_now) #define now_floor ((loop)->now_floor) #define origflags ((loop)->origflags) #define pending_w ((loop)->pending_w) #define pendingcnt ((loop)->pendingcnt) #define pendingmax ((loop)->pendingmax) #define pendingpri ((loop)->pendingpri) #define pendings ((loop)->pendings) #define periodiccnt ((loop)->periodiccnt) #define periodicmax ((loop)->periodicmax) #define periodics ((loop)->periodics) #define pipe_w ((loop)->pipe_w) #define pipe_write_skipped ((loop)->pipe_write_skipped) #define pipe_write_wanted ((loop)->pipe_write_wanted) #define pollcnt ((loop)->pollcnt) #define pollidxmax ((loop)->pollidxmax) #define pollidxs ((loop)->pollidxs) #define pollmax ((loop)->pollmax) #define polls ((loop)->polls) #define port_eventmax ((loop)->port_eventmax) #define port_events ((loop)->port_events) #define postfork ((loop)->postfork) #define preparecnt ((loop)->preparecnt) #define preparemax ((loop)->preparemax) #define prepares ((loop)->prepares) #define release_cb ((loop)->release_cb) #define rfeedcnt ((loop)->rfeedcnt) #define rfeedmax ((loop)->rfeedmax) #define rfeeds ((loop)->rfeeds) #define rtmn_diff ((loop)->rtmn_diff) #define sig_pending ((loop)->sig_pending) #define sigfd ((loop)->sigfd) #define sigfd_set ((loop)->sigfd_set) #define sigfd_w ((loop)->sigfd_w) #define timeout_blocktime ((loop)->timeout_blocktime) #define timercnt ((loop)->timercnt) #define timermax ((loop)->timermax) #define timers ((loop)->timers) #define userdata ((loop)->userdata) #define vec_eo ((loop)->vec_eo) #define vec_max ((loop)->vec_max) #define vec_ri ((loop)->vec_ri) #define vec_ro ((loop)->vec_ro) #define vec_wi ((loop)->vec_wi) #define vec_wo ((loop)->vec_wo) #else #undef EV_WRAP_H #undef acquire_cb #undef activecnt #undef anfdmax #undef anfds #undef async_pending #undef asynccnt #undef asyncmax #undef asyncs #undef backend #undef backend_fd #undef backend_mintime #undef backend_modify #undef backend_poll #undef checkcnt #undef checkmax #undef checks #undef cleanupcnt #undef cleanupmax #undef cleanups #undef curpid #undef epoll_epermcnt #undef epoll_epermmax #undef epoll_eperms #undef epoll_eventmax #undef epoll_events #undef evpipe #undef fdchangecnt #undef fdchangemax #undef fdchanges #undef forkcnt #undef forkmax #undef forks #undef fs_2625 #undef fs_fd #undef fs_hash #undef fs_w #undef idleall #undef idlecnt #undef idlemax #undef idles #undef invoke_cb #undef io_blocktime #undef iocp #undef kqueue_changecnt #undef kqueue_changemax #undef kqueue_changes #undef kqueue_eventmax #undef kqueue_events #undef kqueue_fd_pid #undef loop_count #undef loop_depth #undef loop_done #undef mn_now #undef now_floor #undef origflags #undef pending_w #undef pendingcnt #undef pendingmax #undef pendingpri #undef pendings #undef periodiccnt #undef periodicmax #undef periodics #undef pipe_w #undef pipe_write_skipped #undef pipe_write_wanted #undef pollcnt #undef pollidxmax #undef pollidxs #undef pollmax #undef polls #undef port_eventmax #undef port_events #undef postfork #undef preparecnt #undef preparemax #undef prepares #undef release_cb #undef rfeedcnt #undef rfeedmax #undef rfeeds #undef rtmn_diff #undef sig_pending #undef sigfd #undef sigfd_set #undef sigfd_w #undef timeout_blocktime #undef timercnt #undef timermax #undef timers #undef userdata #undef vec_eo #undef vec_max #undef vec_ri #undef vec_ro #undef vec_wi #undef vec_wo #endif nsca-ng-1.6/lib/ev/libev.m4000066400000000000000000000030461344421036200154330ustar00rootroot00000000000000dnl this file is part of libev, do not make local modifications dnl http://software.schmorp.de/pkg/libev dnl libev support AC_CHECK_HEADERS(sys/inotify.h sys/epoll.h sys/event.h port.h poll.h sys/select.h sys/eventfd.h sys/signalfd.h) AC_CHECK_FUNCS(inotify_init epoll_ctl kqueue port_create poll select eventfd signalfd) AC_CHECK_FUNCS(clock_gettime, [], [ dnl on linux, try syscall wrapper first if test $(uname) = Linux; then AC_MSG_CHECKING(for clock_gettime syscall) AC_LINK_IFELSE([AC_LANG_PROGRAM( [#include #include #include ], [struct timespec ts; int status = syscall (SYS_clock_gettime, CLOCK_REALTIME, &ts)])], [ac_have_clock_syscall=1 AC_DEFINE(HAVE_CLOCK_SYSCALL, 1, Define to 1 to use the syscall interface for clock_gettime) AC_MSG_RESULT(yes)], [AC_MSG_RESULT(no)]) fi if test -z "$LIBEV_M4_AVOID_LIBRT" && test -z "$ac_have_clock_syscall"; then AC_CHECK_LIB(rt, clock_gettime) unset ac_cv_func_clock_gettime AC_CHECK_FUNCS(clock_gettime) fi ]) AC_CHECK_FUNCS(nanosleep, [], [ if test -z "$LIBEV_M4_AVOID_LIBRT"; then AC_CHECK_LIB(rt, nanosleep) unset ac_cv_func_nanosleep AC_CHECK_FUNCS(nanosleep) fi ]) if test -z "$LIBEV_M4_AVOID_LIBM"; then LIBM=m fi AC_SEARCH_LIBS(floor, $LIBM, [AC_DEFINE(HAVE_FLOOR, 1, Define to 1 if the floor function is available)]) nsca-ng-1.6/lib/pidfile/000077500000000000000000000000001344421036200150675ustar00rootroot00000000000000nsca-ng-1.6/lib/pidfile/Makefile.am000066400000000000000000000031411344421036200171220ustar00rootroot00000000000000## Process this file with automake(1) to produce Makefile.in. ## Copyright (c) 2013 Holger Weiss ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1. Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## ## 2. Redistributions in binary form must reproduce the above copyright notice, ## this list of conditions and the following disclaimer in the documentation ## and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE ## LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ## CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF ## SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ## INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ## CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ## ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ## POSSIBILITY OF SUCH DAMAGE. AM_CPPFLAGS = -I$(top_srcdir)/lib noinst_LIBRARIES = libpidfile.a libpidfile_a_SOURCES = flopen.c libutil.h pidfile.c if !HAVE_FLOCK libpidfile_a_SOURCES += flock.c endif nsca-ng-1.6/lib/pidfile/flock.c000066400000000000000000000046151344421036200163370ustar00rootroot00000000000000/* $NetBSD: flock.c,v 1.6 2008/04/28 20:24:12 martin Exp $ */ /*- * Copyright (c) 2001 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Todd Vierling. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * This is the file src/tools/compat/flock.c taken from NetBSD 6.0 and slightly * modified by Holger Weiss in 2012. */ /* * Emulate flock() with fcntl(), where available. Otherwise, don't do locking; * just pretend success. */ #if HAVE_CONFIG_H # include #endif #include #include #include "libutil.h" #include "system.h" int flock(int fd, int op) { int rc = 0; #if defined(F_SETLK) && defined(F_SETLKW) struct flock fl = {0}; switch (op & (LOCK_EX|LOCK_SH|LOCK_UN)) { case LOCK_EX: fl.l_type = F_WRLCK; break; case LOCK_SH: fl.l_type = F_RDLCK; break; case LOCK_UN: fl.l_type = F_UNLCK; break; default: errno = EINVAL; return -1; } fl.l_whence = SEEK_SET; rc = fcntl(fd, op & LOCK_NB ? F_SETLK : F_SETLKW, &fl); if (rc && (errno == EAGAIN)) errno = EWOULDBLOCK; #endif return rc; } nsca-ng-1.6/lib/pidfile/flopen.c000066400000000000000000000057351344421036200165300ustar00rootroot00000000000000/*- * Copyright (c) 2007 Dag-Erling Coïdan Smørgrav * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer * in this position and unchanged. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * This is the file lib/libutil/flopen.c taken from FreeBSD's SVN trunk as of * 2012-10-30 and modified by Holger Weiss in 2012. */ #if HAVE_CONFIG_H # include #endif #if HAVE_SYS_FILE_H # include #endif #include #include #include #include #include "libutil.h" #include "system.h" int flopen(const char *path, int flags, ...) { int fd, operation, serrno, trunc; struct stat sb, fsb; mode_t mode; #ifdef O_EXLOCK flags &= ~O_EXLOCK; #endif mode = 0; if (flags & O_CREAT) { va_list ap; va_start(ap, flags); mode = (mode_t)va_arg(ap, int); /* mode_t promoted to int */ va_end(ap); } operation = LOCK_EX; if (flags & O_NONBLOCK) operation |= LOCK_NB; trunc = (flags & O_TRUNC); flags &= ~O_TRUNC; for (;;) { if ((fd = open(path, flags, mode)) == -1) /* non-existent or no access */ return (-1); if (flock(fd, operation) == -1) { /* unsupported or interrupted */ serrno = errno; (void)close(fd); errno = serrno; return (-1); } if (stat(path, &sb) == -1) { /* disappeared from under our feet */ (void)close(fd); continue; } if (fstat(fd, &fsb) == -1) { /* can't happen [tm] */ serrno = errno; (void)close(fd); errno = serrno; return (-1); } if (sb.st_dev != fsb.st_dev || sb.st_ino != fsb.st_ino) { /* changed under our feet */ (void)close(fd); continue; } if (trunc && ftruncate(fd, 0) != 0) { /* can't happen [tm] */ serrno = errno; (void)close(fd); errno = serrno; return (-1); } return (fd); } } nsca-ng-1.6/lib/pidfile/libutil.h000066400000000000000000000041311344421036200167030ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef LIBUTIL_H # define LIBUTIL_H # if HAVE_CONFIG_H # include # endif # include # include # include # ifndef HAVE_FLOCK int flock(int, int); # ifndef LOCK_SH # define LOCK_SH 1 # endif # ifndef LOCK_EX # define LOCK_EX 2 # endif # ifndef LOCK_NB # define LOCK_NB 4 # endif # ifndef LOCK_UN # define LOCK_UN 8 # endif # endif struct pidfh; int flopen(const char *, int, ...); struct pidfh *pidfile_open(const char *, mode_t, pid_t *); int pidfile_write(struct pidfh *); int pidfile_remove(struct pidfh *); int pidfile_close(struct pidfh *); int pidfile_fileno(const struct pidfh *); #endif /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/lib/pidfile/pidfile.c000066400000000000000000000140141344421036200166470ustar00rootroot00000000000000/*- * Copyright (c) 2005 Pawel Jakub Dawidek * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * This is the file lib/libutil/pidfile.c taken from FreeBSD's SVN trunk as of * 2012-10-30 and modified by Holger Weiss in 2012. */ #if HAVE_CONFIG_H # include #endif #if HAVE_SYS_PARAM_H # include #endif #if HAVE_SYS_FILE_H # include #endif #include #include #include #include #include #include #include #include #include "libutil.h" #include "system.h" #ifndef MAXPATHLEN # define MAXPATHLEN 256 #endif struct pidfh { int pf_fd; char pf_path[MAXPATHLEN + 1]; dev_t pf_dev; ino_t pf_ino; }; static int _pidfile_remove(struct pidfh *pfh, int freeit); static int pidfile_verify(const struct pidfh *pfh) { struct stat sb; if (pfh == NULL || pfh->pf_fd == -1) return (EINVAL); /* * Check remembered descriptor. */ if (fstat(pfh->pf_fd, &sb) == -1) return (errno); if (sb.st_dev != pfh->pf_dev || sb.st_ino != pfh->pf_ino) return (EINVAL); return (0); } static int pidfile_read(const char *path, pid_t *pidptr) { char buf[16], *endptr; int error, fd, i; fd = open(path, O_RDONLY); if (fd == -1) return (errno); i = (int)read(fd, buf, sizeof(buf) - 1); error = errno; /* Remember errno in case close() wants to change it. */ close(fd); if (i == -1) return (error); else if (i == 0) return (EAGAIN); buf[i] = '\0'; *pidptr = (pid_t)strtol(buf, &endptr, 10); if (endptr != &buf[i]) return (EINVAL); return (0); } struct pidfh * pidfile_open(const char *path, mode_t mode, pid_t *pidptr) { struct pidfh *pfh; struct stat sb; int error, fd, len, count; struct timespec rqtp; pfh = malloc(sizeof(*pfh)); if (pfh == NULL) return (NULL); if (path == NULL) len = snprintf(pfh->pf_path, sizeof(pfh->pf_path), "/var/run/%s.pid", PACKAGE_NAME); else len = snprintf(pfh->pf_path, sizeof(pfh->pf_path), "%s", path); if (len >= (int)sizeof(pfh->pf_path)) { free(pfh); errno = ENAMETOOLONG; return (NULL); } /* * Open the PID file and obtain exclusive lock. * We truncate PID file here only to remove old PID immediatelly, * PID file will be truncated again in pidfile_write(), so * pidfile_write() can be called multiple times. */ fd = flopen(pfh->pf_path, O_WRONLY | O_CREAT | O_TRUNC | O_NONBLOCK, mode); if (fd == -1) { if (errno == EWOULDBLOCK && pidptr != NULL) { count = 20; rqtp.tv_sec = 0; rqtp.tv_nsec = 5000000; for (;;) { errno = pidfile_read(pfh->pf_path, pidptr); if (errno != EAGAIN || --count == 0) break; nanosleep(&rqtp, 0); } if (errno == EAGAIN) *pidptr = -1; if (errno == 0 || errno == EAGAIN) errno = EEXIST; } free(pfh); return (NULL); } /* * Remember file information, so in pidfile_write() we are sure we write * to the proper descriptor. */ if (fstat(fd, &sb) == -1) { error = errno; unlink(pfh->pf_path); close(fd); free(pfh); errno = error; return (NULL); } pfh->pf_fd = fd; pfh->pf_dev = sb.st_dev; pfh->pf_ino = sb.st_ino; return (pfh); } int pidfile_write(struct pidfh *pfh) { char pidstr[16]; int error, fd; /* * Check remembered descriptor, so we don't overwrite some other * file if pidfile was closed and descriptor reused. */ errno = pidfile_verify(pfh); if (errno != 0) { /* * Don't close descriptor, because we are not sure if it's ours. */ return (-1); } fd = pfh->pf_fd; /* * Truncate PID file, so multiple calls of pidfile_write() are allowed. */ if (ftruncate(fd, 0) == -1) { error = errno; _pidfile_remove(pfh, 0); errno = error; return (-1); } snprintf(pidstr, sizeof(pidstr), "%u", getpid()); if (pwrite(fd, pidstr, strlen(pidstr), 0) != (ssize_t)strlen(pidstr)) { error = errno; _pidfile_remove(pfh, 0); errno = error; return (-1); } return (0); } int pidfile_close(struct pidfh *pfh) { int error; error = pidfile_verify(pfh); if (error != 0) { errno = error; return (-1); } if (close(pfh->pf_fd) == -1) error = errno; free(pfh); if (error != 0) { errno = error; return (-1); } return (0); } static int _pidfile_remove(struct pidfh *pfh, int freeit) { int error; error = pidfile_verify(pfh); if (error != 0) { errno = error; return (-1); } if (unlink(pfh->pf_path) == -1) error = errno; if (close(pfh->pf_fd) == -1) { if (error == 0) error = errno; } if (freeit) free(pfh); else pfh->pf_fd = -1; if (error != 0) { errno = error; return (-1); } return (0); } int pidfile_remove(struct pidfh *pfh) { return (_pidfile_remove(pfh, 1)); } int pidfile_fileno(const struct pidfh *pfh) { if (pfh == NULL || pfh->pf_fd == -1) { errno = EINVAL; return (-1); } return (pfh->pf_fd); } nsca-ng-1.6/lib/progname.c000066400000000000000000000033661344421036200154370ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #if HAVE_CONFIG_H # include #endif #include #include "system.h" static const char *progname; const char * getprogname(void) { return progname; } void setprogname(const char *path) { const char *p; if ((p = strrchr(path, '/')) == NULL) p = path; else p++; progname = p; } /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/lib/strcasecmp.c000066400000000000000000000033401344421036200157630ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #if HAVE_CONFIG_H # include #endif #include #include "system.h" int strcasecmp(const char *s1, const char *s2) { size_t i = 0; int c1, c2; while ((c1 = tolower(s1[i])) == (c2 = tolower(s2[i]))) { if (s1[i] == '\0') return 0; i++; } return c1 - c2; } /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/lib/strdup.c000066400000000000000000000033311344421036200151400ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #if HAVE_CONFIG_H # include #endif #include #include #include "system.h" char * strdup(const char *string) { char *new; size_t size = strlen(string) + 1; if ((new = malloc(size)) == NULL) return NULL; return memcpy(new, string, size); } /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/lib/strncasecmp.c000066400000000000000000000034521344421036200161450ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #if HAVE_CONFIG_H # include #endif #include #include /* For size_t. */ #include "system.h" int strncasecmp(const char *s1, const char *s2, size_t n) { size_t i; for (i = 0; i < n; i++) { int c1 = tolower(s1[i]); int c2 = tolower(s2[i]); if (c1 != c2) return c1 - c2; if (s1[i] == '\0') break; } return 0; } /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/lib/system.h000066400000000000000000000065251344421036200151600ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef NSCA_NG_H # define NSCA_NG_H # if HAVE_CONFIG_H # include # endif # include /* For size_t. */ /* * Turn __attribute__() into a no-op unless GCC is used. */ # ifndef __GNUC__ # define __attribute__(x) /* Nothing. */ # endif /* * Define the bool type. */ # if HAVE_STDBOOL_H # include # else # if HAVE__BOOL # ifdef __cplusplus typedef bool _Bool; # else # define _Bool signed char # endif # endif # define bool _Bool # define false 0 # define true 1 # define __bool_true_false_are_defined 1 # endif /* * Make sure EWOULDBLOCK is defined. */ # ifndef EWOULDBLOCK # define EWOULDBLOCK EAGAIN # endif /* * Define a MIN() macro. */ # ifdef MIN # undef MIN # endif # define MIN(x, y) ((x) < (y) ? (x) : (y)) /* * For building without systemd(1) support. */ # ifndef SD_LISTEN_FDS_START # define SD_LISTEN_FDS_START 3 # endif # ifndef HAVE_SYSTEMD_SD_DAEMON_H # define sd_notify(a, b) 0 # define sd_listen_fds(a) 0 # endif /* * Declare replacement functions (if necessary). */ # ifndef HAVE_DAEMON int daemon(int, int); # endif # ifndef HAVE_GETPROGNAME const char *getprogname(void); # endif # ifndef HAVE_SETPROGNAME void setprogname(const char *); # endif # ifndef HAVE_STRDUP char *strdup(const char *); # endif # ifndef HAVE_STRCASECMP int strcasecmp(const char *, const char *); # endif # ifndef HAVE_STRNCASECMP int strncasecmp(const char *, const char *, size_t); # endif # if !HAVE_SNPRINTF || !HAVE_VSNPRINTF || !HAVE_ASPRINTF || !HAVE_VASPRINTF # if HAVE_STDARG_H # include # if !HAVE_VSNPRINTF int rpl_vsnprintf(char *, size_t, const char *, va_list); # endif # if !HAVE_SNPRINTF int rpl_snprintf(char *, size_t, const char *, ...); # endif # if !HAVE_VASPRINTF int rpl_vasprintf(char **, const char *, va_list); # endif # if !HAVE_ASPRINTF int rpl_asprintf(char **, const char *, ...); # endif # endif # endif #endif /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/lib/wrappers.c000066400000000000000000000051621344421036200154660ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #if HAVE_CONFIG_H # include #endif #include #include #include #include "log.h" #include "system.h" #include "wrappers.h" void * xmalloc(size_t size) { void *new; if ((new = malloc(size)) == NULL) die("Error: Cannot allocate %zu bytes", size); return new; } void * xrealloc(void *p, size_t size) { void *new; if ((new = realloc(p, size)) == NULL) { free(p); die("Cannot reallocate %zu bytes: %m", size); } return new; } char * xstrdup(const char *string) { char *new; if ((new = strdup(string)) == NULL) die("Cannot duplicate string: %m"); return new; } void xasprintf(char ** restrict result, const char * restrict format, ...) { va_list ap; va_start(ap, format); xvasprintf(result, format, ap); va_end(ap); } void xvasprintf(char ** restrict result, const char * restrict format, va_list ap) { if (vasprintf(result, format, ap) < 0) die("Cannot create buffer with formatted output"); } size_t xfgets(char * restrict buf, int size, FILE * restrict fp) { size_t len; if (fgets(buf, size, fp) != NULL) len = strlen(buf); else { if (ferror(fp)) die("Cannot read input stream: %m"); len = 0; } return len; } /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/lib/wrappers.h000066400000000000000000000035201344421036200154670ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef XLIB_H # define XLIB_H # if HAVE_CONFIG_H # include # endif # include # include void *xmalloc(size_t); void *xrealloc(void *, size_t); char *xstrdup(const char *); void xasprintf(char ** restrict, const char * restrict, ...); void xvasprintf(char ** restrict, const char * restrict, va_list); size_t xfgets(char * restrict, int, FILE * restrict); #endif /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/lib/xprintf.c000066400000000000000000001044411344421036200153150ustar00rootroot00000000000000/* * Copyright (c) 1995 Patrick Powell. * * This code is based on code written by Patrick Powell . * It may be used for any purpose as long as this notice remains intact on all * source code distributions. */ /* * Copyright (c) 2008 Holger Weiss. * * This version of the code is maintained by Holger Weiss . * My changes to the code may freely be used, modified and/or redistributed for * any purpose. It would be nice if additions and fixes to this file (including * trivial code cleanups) would be sent back in order to let me include them in * the version available at . * However, this is not a requirement for using or redistributing (possibly * modified) versions of this file, nor is leaving this notice intact mandatory. */ #if HAVE_CONFIG_H # include #endif /* HAVE_CONFIG_H */ #if !HAVE_SNPRINTF || !HAVE_VSNPRINTF || !HAVE_ASPRINTF || !HAVE_VASPRINTF # include /* For NULL, size_t, vsnprintf(3), and vasprintf(3). */ # ifdef VA_START # undef VA_START # endif /* defined(VA_START) */ # ifdef VA_SHIFT # undef VA_SHIFT # endif /* defined(VA_SHIFT) */ # if HAVE_STDARG_H # include # define VA_START(ap, last) va_start(ap, last) # define VA_SHIFT(ap, value, type) /* No-op for ANSI C. */ # else /* Assume is available. */ # include # define VA_START(ap, last) va_start(ap) /* "last" is ignored. */ # define VA_SHIFT(ap, value, type) value = va_arg(ap, type) # endif /* HAVE_STDARG_H */ # if !HAVE_VASPRINTF # if HAVE_STDLIB_H # include /* For malloc(3). */ # endif /* HAVE_STDLIB_H */ # ifdef VA_COPY # undef VA_COPY # endif /* defined(VA_COPY) */ # ifdef VA_END_COPY # undef VA_END_COPY # endif /* defined(VA_END_COPY) */ # if HAVE_VA_COPY # define VA_COPY(dest, src) va_copy(dest, src) # define VA_END_COPY(ap) va_end(ap) # elif HAVE___VA_COPY # define VA_COPY(dest, src) __va_copy(dest, src) # define VA_END_COPY(ap) va_end(ap) # else # define VA_COPY(dest, src) (void)mymemcpy(&dest, &src, sizeof(va_list)) # define VA_END_COPY(ap) /* No-op. */ # define NEED_MYMEMCPY 1 static void *mymemcpy(void *, void *, size_t); # endif /* HAVE_VA_COPY */ # endif /* !HAVE_VASPRINTF */ # if !HAVE_VSNPRINTF # include /* For ERANGE and errno. */ # include /* For *_MAX. */ # if HAVE_INTTYPES_H # include /* For intmax_t (if it's not in ). */ # endif /* HAVE_INTTYPES_H */ # if HAVE_LOCALE_H # include /* For localeconv(3). */ # endif /* HAVE_LOCALE_H */ # if HAVE_STDDEF_H # include /* For ptrdiff_t. */ # endif /* HAVE_STDDEF_H */ # if HAVE_STDINT_H # include /* For intmax_t. */ # endif /* HAVE_STDINT_H */ # include "system.h" /* Support for unsigned long long int. We may also need ULLONG_MAX. */ # ifndef ULONG_MAX /* We may need ULONG_MAX as a fallback. */ # ifdef UINT_MAX # define ULONG_MAX UINT_MAX # else # define ULONG_MAX INT_MAX # endif /* defined(UINT_MAX) */ # endif /* !defined(ULONG_MAX) */ # ifdef ULLONG # undef ULLONG # endif /* defined(ULLONG) */ # if HAVE_UNSIGNED_LONG_LONG_INT # define ULLONG unsigned long long int # ifndef ULLONG_MAX # define ULLONG_MAX ULONG_MAX # endif /* !defined(ULLONG_MAX) */ # else # define ULLONG unsigned long int # ifdef ULLONG_MAX # undef ULLONG_MAX # endif /* defined(ULLONG_MAX) */ # define ULLONG_MAX ULONG_MAX # endif /* HAVE_LONG_LONG_INT */ /* Support for uintmax_t. We also need UINTMAX_MAX. */ # ifdef UINTMAX_T # undef UINTMAX_T # endif /* defined(UINTMAX_T) */ # if HAVE_UINTMAX_T || defined(uintmax_t) # define UINTMAX_T uintmax_t # ifndef UINTMAX_MAX # define UINTMAX_MAX ULLONG_MAX # endif /* !defined(UINTMAX_MAX) */ # else # define UINTMAX_T ULLONG # ifdef UINTMAX_MAX # undef UINTMAX_MAX # endif /* defined(UINTMAX_MAX) */ # define UINTMAX_MAX ULLONG_MAX # endif /* HAVE_UINTMAX_T || defined(uintmax_t) */ /* Support for long double. */ # ifndef LDOUBLE # if HAVE_LONG_DOUBLE # define LDOUBLE long double # else # define LDOUBLE double # endif /* HAVE_LONG_DOUBLE */ # endif /* !defined(LDOUBLE) */ /* Support for long long int. */ # ifndef LLONG # if HAVE_LONG_LONG_INT # define LLONG long long int # else # define LLONG long int # endif /* HAVE_LONG_LONG_INT */ # endif /* !defined(LLONG) */ /* Support for intmax_t. */ # ifndef INTMAX_T # if HAVE_INTMAX_T || defined(intmax_t) # define INTMAX_T intmax_t # else # define INTMAX_T LLONG # endif /* HAVE_INTMAX_T || defined(intmax_t) */ # endif /* !defined(INTMAX_T) */ /* Support for uintptr_t. */ # ifndef UINTPTR_T # if HAVE_UINTPTR_T || defined(uintptr_t) # define UINTPTR_T uintptr_t # else # define UINTPTR_T unsigned long int # endif /* HAVE_UINTPTR_T || defined(uintptr_t) */ # endif /* !defined(UINTPTR_T) */ /* Support for ptrdiff_t. */ # ifndef PTRDIFF_T # if HAVE_PTRDIFF_T || defined(ptrdiff_t) # define PTRDIFF_T ptrdiff_t # else # define PTRDIFF_T long int # endif /* HAVE_PTRDIFF_T || defined(ptrdiff_t) */ # endif /* !defined(PTRDIFF_T) */ /* * We need an unsigned integer type corresponding to ptrdiff_t (cf. C99: * 7.19.6.1, 7). However, we'll simply use PTRDIFF_T and convert it to an * unsigned type if necessary. This should work just fine in practice. */ # ifndef UPTRDIFF_T # define UPTRDIFF_T PTRDIFF_T # endif /* !defined(UPTRDIFF_T) */ /* * We need a signed integer type corresponding to size_t (cf. C99: 7.19.6.1, 7). * However, we'll simply use size_t and convert it to a signed type if * necessary. This should work just fine in practice. */ # ifndef SSIZE_T # define SSIZE_T size_t # endif /* !defined(SSIZE_T) */ /* Either ERANGE or E2BIG should be available everywhere. */ # ifndef ERANGE # define ERANGE E2BIG # endif /* !defined(ERANGE) */ # ifndef EOVERFLOW # define EOVERFLOW ERANGE # endif /* !defined(EOVERFLOW) */ /* * Buffer size to hold the octal string representation of UINT128_MAX without * nul-termination ("3777777777777777777777777777777777777777777"). */ # ifdef MAX_CONVERT_LENGTH # undef MAX_CONVERT_LENGTH # endif /* defined(MAX_CONVERT_LENGTH) */ # define MAX_CONVERT_LENGTH 43 /* Format read states. */ # define PRINT_S_DEFAULT 0 # define PRINT_S_FLAGS 1 # define PRINT_S_WIDTH 2 # define PRINT_S_DOT 3 # define PRINT_S_PRECISION 4 # define PRINT_S_MOD 5 # define PRINT_S_CONV 6 /* Format flags. */ # define PRINT_F_MINUS (1 << 0) # define PRINT_F_PLUS (1 << 1) # define PRINT_F_SPACE (1 << 2) # define PRINT_F_NUM (1 << 3) # define PRINT_F_ZERO (1 << 4) # define PRINT_F_QUOTE (1 << 5) # define PRINT_F_UP (1 << 6) # define PRINT_F_UNSIGNED (1 << 7) # define PRINT_F_TYPE_G (1 << 8) # define PRINT_F_TYPE_E (1 << 9) /* Conversion flags. */ # define PRINT_C_CHAR 1 # define PRINT_C_SHORT 2 # define PRINT_C_LONG 3 # define PRINT_C_LLONG 4 # define PRINT_C_LDOUBLE 5 # define PRINT_C_SIZE 6 # define PRINT_C_PTRDIFF 7 # define PRINT_C_INTMAX 8 # ifndef MAX # define MAX(x, y) ((x >= y) ? x : y) # endif /* !defined(MAX) */ # ifndef CHARTOINT # define CHARTOINT(ch) (ch - '0') # endif /* !defined(CHARTOINT) */ # ifndef ISDIGIT # define ISDIGIT(ch) ('0' <= (unsigned char)ch && (unsigned char)ch <= '9') # endif /* !defined(ISDIGIT) */ # ifndef ISNAN # define ISNAN(x) (x != x) # endif /* !defined(ISNAN) */ # ifndef ISINF # define ISINF(x) (x != 0.0 && x + x == x) # endif /* !defined(ISINF) */ # ifdef OUTCHAR # undef OUTCHAR # endif /* defined(OUTCHAR) */ # define OUTCHAR(str, len, size, ch) \ do { \ if (len + 1 < size) \ str[len] = ch; \ (len)++; \ } while (/* CONSTCOND */ 0) static void fmtstr(char *, size_t *, size_t, const char *, int, int, int); static void fmtint(char *, size_t *, size_t, INTMAX_T, int, int, int, int); static void fmtflt(char *, size_t *, size_t, LDOUBLE, int, int, int, int *); static void printsep(char *, size_t *, size_t); static int getnumsep(int); static int getexponent(LDOUBLE); static int convert(UINTMAX_T, char *, size_t, int, int); static UINTMAX_T cast(LDOUBLE); static UINTMAX_T myround(LDOUBLE); static LDOUBLE mypow10(int); extern int errno; int rpl_vsnprintf(char *str, size_t size, const char *format, va_list args) { LDOUBLE fvalue; INTMAX_T value; unsigned char cvalue; const char *strvalue; INTMAX_T *intmaxptr; PTRDIFF_T *ptrdiffptr; SSIZE_T *sizeptr; LLONG *llongptr; long int *longptr; int *intptr; short int *shortptr; signed char *charptr; size_t len = 0; int overflow = 0; int base = 0; int cflags = 0; int flags = 0; int width = 0; int precision = -1; int state = PRINT_S_DEFAULT; char ch = *format++; /* * C99 says: "If `n' is zero, nothing is written, and `s' may be a null * pointer." (7.19.6.5, 2) We're forgiving and allow a NULL pointer * even if a size larger than zero was specified. At least NetBSD's * snprintf(3) does the same, as well as other versions of this file. * (Though some of these versions will write to a non-NULL buffer even * if a size of zero was specified, which violates the standard.) */ if (str == NULL && size != 0) size = 0; while (ch != '\0') switch (state) { case PRINT_S_DEFAULT: if (ch == '%') state = PRINT_S_FLAGS; else OUTCHAR(str, len, size, ch); ch = *format++; break; case PRINT_S_FLAGS: switch (ch) { case '-': flags |= PRINT_F_MINUS; ch = *format++; break; case '+': flags |= PRINT_F_PLUS; ch = *format++; break; case ' ': flags |= PRINT_F_SPACE; ch = *format++; break; case '#': flags |= PRINT_F_NUM; ch = *format++; break; case '0': flags |= PRINT_F_ZERO; ch = *format++; break; case '\'': /* SUSv2 flag (not in C99). */ flags |= PRINT_F_QUOTE; ch = *format++; break; default: state = PRINT_S_WIDTH; break; } break; case PRINT_S_WIDTH: if (ISDIGIT(ch)) { ch = CHARTOINT(ch); if (width > (INT_MAX - ch) / 10) { overflow = 1; goto out; } width = 10 * width + ch; ch = *format++; } else if (ch == '*') { /* * C99 says: "A negative field width argument is * taken as a `-' flag followed by a positive * field width." (7.19.6.1, 5) */ if ((width = va_arg(args, int)) < 0) { flags |= PRINT_F_MINUS; width = -width; } ch = *format++; state = PRINT_S_DOT; } else state = PRINT_S_DOT; break; case PRINT_S_DOT: if (ch == '.') { state = PRINT_S_PRECISION; ch = *format++; } else state = PRINT_S_MOD; break; case PRINT_S_PRECISION: if (precision == -1) precision = 0; if (ISDIGIT(ch)) { ch = CHARTOINT(ch); if (precision > (INT_MAX - ch) / 10) { overflow = 1; goto out; } precision = 10 * precision + ch; ch = *format++; } else if (ch == '*') { /* * C99 says: "A negative precision argument is * taken as if the precision were omitted." * (7.19.6.1, 5) */ if ((precision = va_arg(args, int)) < 0) precision = -1; ch = *format++; state = PRINT_S_MOD; } else state = PRINT_S_MOD; break; case PRINT_S_MOD: switch (ch) { case 'h': ch = *format++; if (ch == 'h') { /* It's a char. */ ch = *format++; cflags = PRINT_C_CHAR; } else cflags = PRINT_C_SHORT; break; case 'l': ch = *format++; if (ch == 'l') { /* It's a long long. */ ch = *format++; cflags = PRINT_C_LLONG; } else cflags = PRINT_C_LONG; break; case 'L': cflags = PRINT_C_LDOUBLE; ch = *format++; break; case 'j': cflags = PRINT_C_INTMAX; ch = *format++; break; case 't': cflags = PRINT_C_PTRDIFF; ch = *format++; break; case 'z': cflags = PRINT_C_SIZE; ch = *format++; break; } state = PRINT_S_CONV; break; case PRINT_S_CONV: switch (ch) { case 'd': /* FALLTHROUGH */ case 'i': switch (cflags) { case PRINT_C_CHAR: value = (signed char)va_arg(args, int); break; case PRINT_C_SHORT: value = (short int)va_arg(args, int); break; case PRINT_C_LONG: value = va_arg(args, long int); break; case PRINT_C_LLONG: value = va_arg(args, LLONG); break; case PRINT_C_SIZE: value = va_arg(args, SSIZE_T); break; case PRINT_C_INTMAX: value = va_arg(args, INTMAX_T); break; case PRINT_C_PTRDIFF: value = va_arg(args, PTRDIFF_T); break; default: value = va_arg(args, int); break; } fmtint(str, &len, size, value, 10, width, precision, flags); break; case 'X': flags |= PRINT_F_UP; /* FALLTHROUGH */ case 'x': base = 16; /* FALLTHROUGH */ case 'o': if (base == 0) base = 8; /* FALLTHROUGH */ case 'u': if (base == 0) base = 10; flags |= PRINT_F_UNSIGNED; switch (cflags) { case PRINT_C_CHAR: value = (unsigned char)va_arg(args, unsigned int); break; case PRINT_C_SHORT: value = (unsigned short int)va_arg(args, unsigned int); break; case PRINT_C_LONG: value = va_arg(args, unsigned long int); break; case PRINT_C_LLONG: value = va_arg(args, ULLONG); break; case PRINT_C_SIZE: value = va_arg(args, size_t); break; case PRINT_C_INTMAX: value = va_arg(args, UINTMAX_T); break; case PRINT_C_PTRDIFF: value = va_arg(args, UPTRDIFF_T); break; default: value = va_arg(args, unsigned int); break; } fmtint(str, &len, size, value, base, width, precision, flags); break; case 'A': /* Not yet supported, we'll use "%F". */ /* FALLTHROUGH */ case 'F': flags |= PRINT_F_UP; case 'a': /* Not yet supported, we'll use "%f". */ /* FALLTHROUGH */ case 'f': if (cflags == PRINT_C_LDOUBLE) fvalue = va_arg(args, LDOUBLE); else fvalue = va_arg(args, double); fmtflt(str, &len, size, fvalue, width, precision, flags, &overflow); if (overflow) goto out; break; case 'E': flags |= PRINT_F_UP; /* FALLTHROUGH */ case 'e': flags |= PRINT_F_TYPE_E; if (cflags == PRINT_C_LDOUBLE) fvalue = va_arg(args, LDOUBLE); else fvalue = va_arg(args, double); fmtflt(str, &len, size, fvalue, width, precision, flags, &overflow); if (overflow) goto out; break; case 'G': flags |= PRINT_F_UP; /* FALLTHROUGH */ case 'g': flags |= PRINT_F_TYPE_G; if (cflags == PRINT_C_LDOUBLE) fvalue = va_arg(args, LDOUBLE); else fvalue = va_arg(args, double); /* * If the precision is zero, it is treated as * one (cf. C99: 7.19.6.1, 8). */ if (precision == 0) precision = 1; fmtflt(str, &len, size, fvalue, width, precision, flags, &overflow); if (overflow) goto out; break; case 'c': cvalue = va_arg(args, int); OUTCHAR(str, len, size, cvalue); break; case 's': strvalue = va_arg(args, char *); fmtstr(str, &len, size, strvalue, width, precision, flags); break; case 'p': /* * C99 says: "The value of the pointer is * converted to a sequence of printing * characters, in an implementation-defined * manner." (C99: 7.19.6.1, 8) */ if ((strvalue = va_arg(args, void *)) == NULL) /* * We use the glibc format. BSD prints * "0x0", SysV "0". */ fmtstr(str, &len, size, "(nil)", width, -1, flags); else { /* * We use the BSD/glibc format. SysV * omits the "0x" prefix (which we emit * using the PRINT_F_NUM flag). */ flags |= PRINT_F_NUM; flags |= PRINT_F_UNSIGNED; fmtint(str, &len, size, (UINTPTR_T)strvalue, 16, width, precision, flags); } break; case 'n': switch (cflags) { case PRINT_C_CHAR: charptr = va_arg(args, signed char *); *charptr = len; break; case PRINT_C_SHORT: shortptr = va_arg(args, short int *); *shortptr = len; break; case PRINT_C_LONG: longptr = va_arg(args, long int *); *longptr = len; break; case PRINT_C_LLONG: llongptr = va_arg(args, LLONG *); *llongptr = len; break; case PRINT_C_SIZE: /* * C99 says that with the "z" length * modifier, "a following `n' conversion * specifier applies to a pointer to a * signed integer type corresponding to * size_t argument." (7.19.6.1, 7) */ sizeptr = va_arg(args, SSIZE_T *); *sizeptr = len; break; case PRINT_C_INTMAX: intmaxptr = va_arg(args, INTMAX_T *); *intmaxptr = len; break; case PRINT_C_PTRDIFF: ptrdiffptr = va_arg(args, PTRDIFF_T *); *ptrdiffptr = len; break; default: intptr = va_arg(args, int *); *intptr = len; break; } break; case '%': /* Print a "%" character verbatim. */ OUTCHAR(str, len, size, ch); break; default: /* Skip other characters. */ break; } ch = *format++; state = PRINT_S_DEFAULT; base = cflags = flags = width = 0; precision = -1; break; } out: if (len < size) str[len] = '\0'; else if (size > 0) str[size - 1] = '\0'; if (overflow || len >= INT_MAX) { errno = overflow ? EOVERFLOW : ERANGE; return -1; } return (int)len; } static void fmtstr(char *str, size_t *len, size_t size, const char *value, int width, int precision, int flags) { int padlen, strln; /* Amount to pad. */ int noprecision = (precision == -1); if (value == NULL) /* We're forgiving. */ value = "(null)"; /* If a precision was specified, don't read the string past it. */ for (strln = 0; value[strln] != '\0' && (noprecision || strln < precision); strln++) continue; if ((padlen = width - strln) < 0) padlen = 0; if (flags & PRINT_F_MINUS) /* Left justify. */ padlen = -padlen; while (padlen > 0) { /* Leading spaces. */ OUTCHAR(str, *len, size, ' '); padlen--; } while (*value != '\0' && (noprecision || precision-- > 0)) { OUTCHAR(str, *len, size, *value); value++; } while (padlen < 0) { /* Trailing spaces. */ OUTCHAR(str, *len, size, ' '); padlen++; } } static void fmtint(char *str, size_t *len, size_t size, INTMAX_T value, int base, int width, int precision, int flags) { UINTMAX_T uvalue; char iconvert[MAX_CONVERT_LENGTH]; char sign = 0; char hexprefix = 0; int spadlen = 0; /* Amount to space pad. */ int zpadlen = 0; /* Amount to zero pad. */ int pos; int separators = (flags & PRINT_F_QUOTE); int noprecision = (precision == -1); if (flags & PRINT_F_UNSIGNED) uvalue = value; else { uvalue = (value >= 0) ? value : -value; if (value < 0) sign = '-'; else if (flags & PRINT_F_PLUS) /* Do a sign. */ sign = '+'; else if (flags & PRINT_F_SPACE) sign = ' '; } pos = convert(uvalue, iconvert, sizeof(iconvert), base, flags & PRINT_F_UP); if (flags & PRINT_F_NUM && uvalue != 0) { /* * C99 says: "The result is converted to an `alternative form'. * For `o' conversion, it increases the precision, if and only * if necessary, to force the first digit of the result to be a * zero (if the value and precision are both 0, a single 0 is * printed). For `x' (or `X') conversion, a nonzero result has * `0x' (or `0X') prefixed to it." (7.19.6.1, 6) */ switch (base) { case 8: if (precision <= pos) precision = pos + 1; break; case 16: hexprefix = (flags & PRINT_F_UP) ? 'X' : 'x'; break; } } if (separators) /* Get the number of group separators we'll print. */ separators = getnumsep(pos); zpadlen = precision - pos - separators; spadlen = width /* Minimum field width. */ - separators /* Number of separators. */ - MAX(precision, pos) /* Number of integer digits. */ - ((sign != 0) ? 1 : 0) /* Will we print a sign? */ - ((hexprefix != 0) ? 2 : 0); /* Will we print a prefix? */ if (zpadlen < 0) zpadlen = 0; if (spadlen < 0) spadlen = 0; /* * C99 says: "If the `0' and `-' flags both appear, the `0' flag is * ignored. For `d', `i', `o', `u', `x', and `X' conversions, if a * precision is specified, the `0' flag is ignored." (7.19.6.1, 6) */ if (flags & PRINT_F_MINUS) /* Left justify. */ spadlen = -spadlen; else if (flags & PRINT_F_ZERO && noprecision) { zpadlen += spadlen; spadlen = 0; } while (spadlen > 0) { /* Leading spaces. */ OUTCHAR(str, *len, size, ' '); spadlen--; } if (sign != 0) /* Sign. */ OUTCHAR(str, *len, size, sign); if (hexprefix != 0) { /* A "0x" or "0X" prefix. */ OUTCHAR(str, *len, size, '0'); OUTCHAR(str, *len, size, hexprefix); } while (zpadlen > 0) { /* Leading zeros. */ OUTCHAR(str, *len, size, '0'); zpadlen--; } while (pos > 0) { /* The actual digits. */ pos--; OUTCHAR(str, *len, size, iconvert[pos]); if (separators > 0 && pos > 0 && pos % 3 == 0) printsep(str, len, size); } while (spadlen < 0) { /* Trailing spaces. */ OUTCHAR(str, *len, size, ' '); spadlen++; } } static void fmtflt(char *str, size_t *len, size_t size, LDOUBLE fvalue, int width, int precision, int flags, int *overflow) { LDOUBLE ufvalue; UINTMAX_T intpart; UINTMAX_T fracpart; UINTMAX_T mask; const char *infnan = NULL; char iconvert[MAX_CONVERT_LENGTH]; char fconvert[MAX_CONVERT_LENGTH]; char econvert[4]; /* "e-12" (without nul-termination). */ char esign = 0; char sign = 0; int leadfraczeros = 0; int exponent = 0; int emitpoint = 0; int omitzeros = 0; int omitcount = 0; int padlen = 0; int epos = 0; int fpos = 0; int ipos = 0; int separators = (flags & PRINT_F_QUOTE); int estyle = (flags & PRINT_F_TYPE_E); # if HAVE_LOCALECONV && HAVE_LCONV_DECIMAL_POINT struct lconv *lc = localeconv(); # endif /* HAVE_LOCALECONV && HAVE_LCONV_DECIMAL_POINT */ /* * AIX' man page says the default is 0, but C99 and at least Solaris' * and NetBSD's man pages say the default is 6, and sprintf(3) on AIX * defaults to 6. */ if (precision == -1) precision = 6; if (fvalue < 0.0) sign = '-'; else if (flags & PRINT_F_PLUS) /* Do a sign. */ sign = '+'; else if (flags & PRINT_F_SPACE) sign = ' '; if (ISNAN(fvalue)) infnan = (flags & PRINT_F_UP) ? "NAN" : "nan"; else if (ISINF(fvalue)) infnan = (flags & PRINT_F_UP) ? "INF" : "inf"; if (infnan != NULL) { if (sign != 0) iconvert[ipos++] = sign; while (*infnan != '\0') iconvert[ipos++] = *infnan++; fmtstr(str, len, size, iconvert, width, ipos, flags); return; } /* "%e" (or "%E") or "%g" (or "%G") conversion. */ if (flags & PRINT_F_TYPE_E || flags & PRINT_F_TYPE_G) { if (flags & PRINT_F_TYPE_G) { /* * For "%g" (and "%G") conversions, the precision * specifies the number of significant digits, which * includes the digits in the integer part. The * conversion will or will not be using "e-style" (like * "%e" or "%E" conversions) depending on the precision * and on the exponent. However, the exponent can be * affected by rounding the converted value, so we'll * leave this decision for later. Until then, we'll * assume that we're going to do an "e-style" conversion * (in order to get the exponent calculated). For * "e-style", the precision must be decremented by one. */ precision--; /* * For "%g" (and "%G") conversions, trailing zeros are * removed from the fractional portion of the result * unless the "#" flag was specified. */ if (!(flags & PRINT_F_NUM)) omitzeros = 1; } exponent = getexponent(fvalue); estyle = 1; } again: /* * Sorry, we only support 9, 19, or 38 digits (that is, the number of * digits of the 32-bit, the 64-bit, or the 128-bit UINTMAX_MAX value * minus one) past the decimal point due to our conversion method. */ switch (sizeof(UINTMAX_T)) { case 16: if (precision > 38) precision = 38; break; case 8: if (precision > 19) precision = 19; break; default: if (precision > 9) precision = 9; break; } ufvalue = (fvalue >= 0.0) ? fvalue : -fvalue; if (estyle) /* We want exactly one integer digit. */ ufvalue /= mypow10(exponent); if ((intpart = cast(ufvalue)) == UINTMAX_MAX) { *overflow = 1; return; } /* * Factor of ten with the number of digits needed for the fractional * part. For example, if the precision is 3, the mask will be 1000. */ mask = mypow10(precision); /* * We "cheat" by converting the fractional part to integer by * multiplying by a factor of ten. */ if ((fracpart = myround(mask * (ufvalue - intpart))) >= mask) { /* * For example, ufvalue = 2.99962, intpart = 2, and mask = 1000 * (because precision = 3). Now, myround(1000 * 0.99962) will * return 1000. So, the integer part must be incremented by one * and the fractional part must be set to zero. */ intpart++; fracpart = 0; if (estyle && intpart == 10) { /* * The value was rounded up to ten, but we only want one * integer digit if using "e-style". So, the integer * part must be set to one and the exponent must be * incremented by one. */ intpart = 1; exponent++; } } /* * Now that we know the real exponent, we can check whether or not to * use "e-style" for "%g" (and "%G") conversions. If we don't need * "e-style", the precision must be adjusted and the integer and * fractional parts must be recalculated from the original value. * * C99 says: "Let P equal the precision if nonzero, 6 if the precision * is omitted, or 1 if the precision is zero. Then, if a conversion * with style `E' would have an exponent of X: * * - if P > X >= -4, the conversion is with style `f' (or `F') and * precision P - (X + 1). * * - otherwise, the conversion is with style `e' (or `E') and precision * P - 1." (7.19.6.1, 8) * * Note that we had decremented the precision by one. */ if (flags & PRINT_F_TYPE_G && estyle && precision + 1 > exponent && exponent >= -4) { precision -= exponent; estyle = 0; goto again; } if (estyle) { if (exponent < 0) { exponent = -exponent; esign = '-'; } else esign = '+'; /* * Convert the exponent. The sizeof(econvert) is 4. So, the * econvert buffer can hold e.g. "e+99" and "e-99". We don't * support an exponent which contains more than two digits. * Therefore, the following stores are safe. */ epos = convert(exponent, econvert, 2, 10, 0); /* * C99 says: "The exponent always contains at least two digits, * and only as many more digits as necessary to represent the * exponent." (7.19.6.1, 8) */ if (epos == 1) econvert[epos++] = '0'; econvert[epos++] = esign; econvert[epos++] = (flags & PRINT_F_UP) ? 'E' : 'e'; } /* Convert the integer part and the fractional part. */ ipos = convert(intpart, iconvert, sizeof(iconvert), 10, 0); if (fracpart != 0) /* convert() would return 1 if fracpart == 0. */ fpos = convert(fracpart, fconvert, sizeof(fconvert), 10, 0); leadfraczeros = precision - fpos; if (omitzeros) { if (fpos > 0) /* Omit trailing fractional part zeros. */ while (omitcount < fpos && fconvert[omitcount] == '0') omitcount++; else { /* The fractional part is zero, omit it completely. */ omitcount = precision; leadfraczeros = 0; } precision -= omitcount; } /* * Print a decimal point if either the fractional part is non-zero * and/or the "#" flag was specified. */ if (precision > 0 || flags & PRINT_F_NUM) emitpoint = 1; if (separators) /* Get the number of group separators we'll print. */ separators = getnumsep(ipos); padlen = width /* Minimum field width. */ - ipos /* Number of integer digits. */ - epos /* Number of exponent characters. */ - precision /* Number of fractional digits. */ - separators /* Number of group separators. */ - (emitpoint ? 1 : 0) /* Will we print a decimal point? */ - ((sign != 0) ? 1 : 0); /* Will we print a sign character? */ if (padlen < 0) padlen = 0; /* * C99 says: "If the `0' and `-' flags both appear, the `0' flag is * ignored." (7.19.6.1, 6) */ if (flags & PRINT_F_MINUS) /* Left justifty. */ padlen = -padlen; else if (flags & PRINT_F_ZERO && padlen > 0) { if (sign != 0) { /* Sign. */ OUTCHAR(str, *len, size, sign); sign = 0; } while (padlen > 0) { /* Leading zeros. */ OUTCHAR(str, *len, size, '0'); padlen--; } } while (padlen > 0) { /* Leading spaces. */ OUTCHAR(str, *len, size, ' '); padlen--; } if (sign != 0) /* Sign. */ OUTCHAR(str, *len, size, sign); while (ipos > 0) { /* Integer part. */ ipos--; OUTCHAR(str, *len, size, iconvert[ipos]); if (separators > 0 && ipos > 0 && ipos % 3 == 0) printsep(str, len, size); } if (emitpoint) { /* Decimal point. */ # if HAVE_LOCALECONV && HAVE_LCONV_DECIMAL_POINT if (lc->decimal_point != NULL && *lc->decimal_point != '\0') OUTCHAR(str, *len, size, *lc->decimal_point); else /* We'll always print some decimal point character. */ # endif /* HAVE_LOCALECONV && HAVE_LCONV_DECIMAL_POINT */ OUTCHAR(str, *len, size, '.'); } while (leadfraczeros > 0) { /* Leading fractional part zeros. */ OUTCHAR(str, *len, size, '0'); leadfraczeros--; } while (fpos > omitcount) { /* The remaining fractional part. */ fpos--; OUTCHAR(str, *len, size, fconvert[fpos]); } while (epos > 0) { /* Exponent. */ epos--; OUTCHAR(str, *len, size, econvert[epos]); } while (padlen < 0) { /* Trailing spaces. */ OUTCHAR(str, *len, size, ' '); padlen++; } } static void printsep(char *str, size_t *len, size_t size) { # if HAVE_LOCALECONV && HAVE_LCONV_THOUSANDS_SEP struct lconv *lc = localeconv(); int i; if (lc->thousands_sep != NULL) for (i = 0; lc->thousands_sep[i] != '\0'; i++) OUTCHAR(str, *len, size, lc->thousands_sep[i]); else # endif /* HAVE_LOCALECONV && HAVE_LCONV_THOUSANDS_SEP */ OUTCHAR(str, *len, size, ','); } static int getnumsep(int digits) { int separators = (digits - ((digits % 3 == 0) ? 1 : 0)) / 3; # if HAVE_LOCALECONV && HAVE_LCONV_THOUSANDS_SEP int strln; struct lconv *lc = localeconv(); /* We support an arbitrary separator length (including zero). */ if (lc->thousands_sep != NULL) { for (strln = 0; lc->thousands_sep[strln] != '\0'; strln++) continue; separators *= strln; } # endif /* HAVE_LOCALECONV && HAVE_LCONV_THOUSANDS_SEP */ return separators; } static int getexponent(LDOUBLE value) { LDOUBLE tmp = (value >= 0.0) ? value : -value; int exponent = 0; /* * We check for 99 > exponent > -99 in order to work around possible * endless loops which could happen (at least) in the second loop (at * least) if we're called with an infinite value. However, we checked * for infinity before calling this function using our ISINF() macro, so * this might be somewhat paranoid. */ while (tmp < 1.0 && tmp > 0.0 && --exponent > -99) tmp *= 10; while (tmp >= 10.0 && ++exponent < 99) tmp /= 10; return exponent; } static int convert(UINTMAX_T value, char *buf, size_t size, int base, int caps) { const char *digits = caps ? "0123456789ABCDEF" : "0123456789abcdef"; size_t pos = 0; /* We return an unterminated buffer with the digits in reverse order. */ do { buf[pos++] = digits[value % base]; value /= base; } while (value != 0 && pos < size); return (int)pos; } static UINTMAX_T cast(LDOUBLE value) { UINTMAX_T result; /* * We check for ">=" and not for ">" because if UINTMAX_MAX cannot be * represented exactly as an LDOUBLE value (but is less than LDBL_MAX), * it may be increased to the nearest higher representable value for the * comparison (cf. C99: 6.3.1.4, 2). It might then equal the LDOUBLE * value although converting the latter to UINTMAX_T would overflow. */ if (value >= UINTMAX_MAX) return UINTMAX_MAX; result = value; /* * At least on NetBSD/sparc64 3.0.2 and 4.99.30, casting long double to * an integer type converts e.g. 1.9 to 2 instead of 1 (which violates * the standard). Sigh. */ return (result <= value) ? result : result - 1; } static UINTMAX_T myround(LDOUBLE value) { UINTMAX_T intpart = cast(value); return ((value -= intpart) < 0.5) ? intpart : intpart + 1; } static LDOUBLE mypow10(int exponent) { LDOUBLE result = 1; while (exponent > 0) { result *= 10; exponent--; } while (exponent < 0) { result /= 10; exponent++; } return result; } # endif /* !HAVE_VSNPRINTF */ # if !HAVE_VASPRINTF # if NEED_MYMEMCPY void * mymemcpy(void *dst, void *src, size_t len) { const char *from = src; char *to = dst; /* No need for optimization, we use this only to replace va_copy(3). */ while (len-- > 0) *to++ = *from++; return dst; } # endif /* NEED_MYMEMCPY */ int rpl_vasprintf(char **ret, const char *format, va_list ap) { size_t size; int len; va_list aq; VA_COPY(aq, ap); len = vsnprintf(NULL, 0, format, aq); VA_END_COPY(aq); if (len < 0 || (*ret = malloc(size = len + 1)) == NULL) return -1; return vsnprintf(*ret, size, format, ap); } # endif /* !HAVE_VASPRINTF */ # if !HAVE_SNPRINTF # if HAVE_STDARG_H int rpl_snprintf(char *str, size_t size, const char *format, ...) # else int rpl_snprintf(va_alist) va_dcl # endif /* HAVE_STDARG_H */ { # if !HAVE_STDARG_H char *str; size_t size; char *format; # endif /* HAVE_STDARG_H */ va_list ap; int len; VA_START(ap, format); VA_SHIFT(ap, str, char *); VA_SHIFT(ap, size, size_t); VA_SHIFT(ap, format, const char *); len = vsnprintf(str, size, format, ap); va_end(ap); return len; } # endif /* !HAVE_SNPRINTF */ # if !HAVE_ASPRINTF # if HAVE_STDARG_H int rpl_asprintf(char **ret, const char *format, ...) # else int rpl_asprintf(va_alist) va_dcl # endif /* HAVE_STDARG_H */ { # if !HAVE_STDARG_H char **ret; char *format; # endif /* HAVE_STDARG_H */ va_list ap; int len; VA_START(ap, format); VA_SHIFT(ap, ret, char **); VA_SHIFT(ap, format, const char *); len = vasprintf(ret, format, ap); va_end(ap); return len; } # endif /* !HAVE_ASPRINTF */ #endif /* !HAVE_SNPRINTF || !HAVE_VSNPRINTF || !HAVE_ASPRINTF || [...] */ /* vim:set joinspaces textwidth=80: */ nsca-ng-1.6/m4/000077500000000000000000000000001344421036200132255ustar00rootroot00000000000000nsca-ng-1.6/m4/aio.m4000066400000000000000000000116721344421036200142460ustar00rootroot00000000000000# Copyright (c) 2013 Holger Weiss # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # NSCA_LIB_AIO # ------------ # Check the availability of the POSIX AIO API, and of the aio_init(3) extension # provided by glibc. See for the latter: # # http://www.gnu.org/software/libc/manual/html_node/Configuration-of-AIO.html # # If the POSIX AIO API is available, we set $nsca_lib_posix_aio to "yes" and # define HAVE_POSIX_AIO to 1. We also set the output variable AIOLIBS. Apart # from that, we define symbols which describe the aio_init(3) extension, if # available. # # We check whether POSIX AIO programs can actually be executed because at least # on AIX 5.3, POSIX AIO is not enabled by default even though the header # declarations and library functions are available. When cross-compiling, we # assume that POSIX AIO isn't available on the target system. AC_CACHE_CHECK # allows the user to override this assumption. AC_DEFUN([NSCA_LIB_AIO], [ AC_CHECK_FUNC([aio_return], [nsca_lib_posix_aio=yes], [AC_CHECK_LIB([rt], [aio_return], [AIOLIBS='-lrt' nsca_lib_posix_aio=yes], [AC_CHECK_LIB([pthread], [aio_return], [AIOLIBS='-lrt -lpthread' nsca_lib_posix_aio=yes], [nsca_lib_posix_aio=no], [-lrt -lpthread])])]) AS_IF([test "x$nsca_lib_posix_aio" = xyes], [AC_CACHE_CHECK([whether POSIX AIO works], [nsca_cv_lib_aio_enabled], [nsca_save_LIBS=$LIBS LIBS=$AIOLIBS AC_RUN_IFELSE( [AC_LANG_PROGRAM( [[#include #include #include #include #include #include #include static void signal_handler(int sig, siginfo_t *info, void *ctx) { if (sig != SIGUSR1 || info->si_code != SI_ASYNCIO || ctx == NULL) _exit(1); else { (void)close(info->si_value.sival_int); _exit(0); } }]], [[struct sigaction action; struct aiocb cb; char msg[] = "Hello, world!\n"; int fd; action.sa_sigaction = signal_handler; action.sa_flags = SA_SIGINFO; (void)sigemptyset(&action.sa_mask); (void)sigaction(SIGUSR1, &action, NULL); if ((fd = open("/dev/null", O_WRONLY)) == -1) return 1; (void)memset(&cb, 0, sizeof(cb)); cb.aio_buf = msg; cb.aio_nbytes = sizeof(msg); cb.aio_fildes = fd; cb.aio_offset = 0; cb.aio_sigevent.sigev_notify = SIGEV_SIGNAL; cb.aio_sigevent.sigev_signo = SIGUSR1; cb.aio_sigevent.sigev_value.sival_int = fd; (void)aio_write(&cb); (void)sleep(10); (void)close(fd); return 1;]])], [nsca_cv_lib_aio_enabled=yes], [nsca_cv_lib_aio_enabled=no], [nsca_cv_lib_aio_enabled=no]) LIBS=$nsca_save_LIBS])]) AS_IF([test "x$nsca_cv_lib_aio_enabled" = xyes], [AC_DEFINE([HAVE_POSIX_AIO], [1], [Define to 1 if you have the POSIX AIO API.]) nsca_save_LIBS=$LIBS LIBS=$AIOLIBS AC_CHECK_FUNCS([aio_init], [AC_CHECK_MEMBERS([struct aioinit.aio_threads, struct aioinit.aio_num, struct aioinit.aio_locks, struct aioinit.aio_usedba, struct aioinit.aio_debug, struct aioinit.aio_numusers, struct aioinit.aio_idle_time], [], [], [[#include ]])]) LIBS=$nsca_save_LIBS], [nsca_lib_posix_aio=no]) AC_SUBST([AIOLIBS]) ])# NSCA_LIB_AIO dnl vim:set joinspaces textwidth=80: nsca-ng-1.6/m4/confuse.m4000066400000000000000000000076501344421036200151410ustar00rootroot00000000000000# Copyright (c) 2013 Holger Weiss # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # NSCA_LIB_CONFUSE # ---------------- # Check the availability of libConfuse 2.6 or newer. As this is a required # dependency, we bail out if the user specified "--without-confuse", if we fail # to link against the library, or if the confuse version we found is too old. # On success, we set the output variables CONFUSECPPFLAGS, CONFUSELDFLAGS, and # CONFUSELIBS to appropriate values. (Why are there no underscores in these # variable names? Because Automake treats names like "foo_CPPFLAGS" specially.) AC_DEFUN([NSCA_LIB_CONFUSE], [ nsca_save_CPPFLAGS=$CPPFLAGS nsca_save_LDFLAGS=$LDFLAGS AC_ARG_WITH([confuse], [AS_HELP_STRING([--with-confuse=PATH], [use the libConfuse library in PATH])], [nsca_confuse_dir=$with_confuse], [nsca_confuse_dir=yes]) AC_MSG_CHECKING([whether libConfuse is desired]) AS_CASE([$nsca_confuse_dir], [no], [AC_MSG_RESULT([no]) AC_MSG_ERROR([building without libConfuse is not supported])], [yes], [AC_MSG_RESULT([yes]) AC_MSG_CHECKING([for the location of libConfuse]) nsca_confuse_dir=unknown for _nsca_confuse_dir in "$ac_pwd/lib/confuse" /usr /usr/local /usr/pkg do dnl Solaris 10 doesn't have "test -e". AS_IF([test -r "$_nsca_confuse_dir/include/confuse.h"], [nsca_confuse_dir=$_nsca_confuse_dir break]) done AS_IF([test "x$nsca_confuse_dir" != xunknown], [AC_MSG_RESULT([$nsca_confuse_dir])], [AC_MSG_RESULT([not found, continuing anyway])])], [AC_MSG_RESULT([yes])]) AS_IF([test "x$nsca_confuse_dir" != xunknown && test "x$nsca_confuse_dir" != x/usr], [CONFUSECPPFLAGS="-I$nsca_confuse_dir/include" CONFUSELDFLAGS="-L$nsca_confuse_dir/lib" CPPFLAGS="$CONFUSECPPFLAGS $CPPFLAGS" LDFLAGS="$CONFUSELDFLAGS $LDFLAGS"]) AC_CHECK_HEADER([confuse.h], [], [AC_MSG_ERROR([libConfuse header file not found])]) AC_CHECK_LIB([confuse], [cfg_init], [CONFUSELIBS='-lconfuse'], [AC_CHECK_LIB([intl], [cfg_init], [CONFUSELIBS='-lconfuse -lintl'], [AC_CHECK_LIB([iconv], [cfg_init], [CONFUSELIBS='-lconfuse -lintl -liconv'], [AC_MSG_FAILURE([cannot link with libConfuse])], [-lconfuse -lintl -liconv])], [-lconfuse -lintl])]) AC_CHECK_DECL([CFGF_NO_TITLE_DUPES], [], [AC_MSG_ERROR([libConfuse too old, version 2.6 or newer is required])], [[#include ]]) AC_SUBST([CONFUSECPPFLAGS]) AC_SUBST([CONFUSELDFLAGS]) AC_SUBST([CONFUSELIBS]) CPPFLAGS=$nsca_save_CPPFLAGS LDFLAGS=$nsca_save_LDFLAGS ])# NSCA_LIB_CONFUSE dnl vim:set joinspaces textwidth=80: nsca-ng-1.6/m4/daemon.m4000066400000000000000000000037661344421036200147460ustar00rootroot00000000000000# Copyright (c) 2013 Holger Weiss # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # NSCA_FUNC_DAEMON # ---------------- # Check the availability of a BSD-style daemon(3) function. If no such function # is found, arrange for using the bundled implementation. AC_DEFUN([NSCA_FUNC_DAEMON], [ AC_CHECK_FUNC([daemon], [AC_DEFINE([HAVE_DAEMON], [1], [Define to 1 if you have the `daemon' function.])], [AC_LIBOBJ([daemon]) AC_CHECK_HEADERS([paths.h]) AC_CHECK_DECL([_PATH_DEVNULL], [], [AC_DEFINE([_PATH_DEVNULL], ["/dev/null"], [Define to the path of the `null' device.])], [[#ifdef HAVE_PATHS_H #include #endif]])]) ])# NSCA_FUNC_DAEMON dnl vim:set joinspaces textwidth=80: nsca-ng-1.6/m4/ev.m4000066400000000000000000000134331344421036200141050ustar00rootroot00000000000000# Copyright (c) 2013 Holger Weiss # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # NSCA_LIB_EV # ----------- # Check the availability of libev 4.00 or newer. If it's not found, or if the # user specified "--with-ev=embedded", we use our internal copy of libev and set # $nsca_lib_ev_embedded to "yes". Otherwise, we set $nsca_lib_ev_embedded to # "no". Either way, we set the output variables EVCPPFLAGS, EVLDFLAGS, and # EVLIBS to appropriate values. (Why are there no underscores in these variable # names? Because Automake treats names like "foo_CPPFLAGS" specially.) AC_DEFUN([NSCA_LIB_EV], [ nsca_save_CPPFLAGS=$CPPFLAGS nsca_save_LDFLAGS=$LDFLAGS nsca_lib_ev_embedded=maybe AC_ARG_WITH([ev], [AS_HELP_STRING([--with-ev=PATH], [use the libev library in PATH])], [nsca_ev_dir=$with_ev], [nsca_ev_dir=yes]) AC_MSG_CHECKING([whether libev is desired]) AS_CASE([$nsca_ev_dir], [no], [AC_MSG_RESULT([no]) AC_MSG_ERROR([building without libev is not supported])], [yes|external], [AS_IF([test "x$nsca_ev_dir" = xexternal], [nsca_lib_ev_embedded=no]) AC_MSG_RESULT([yes]) AC_MSG_CHECKING([for the location of libev]) nsca_ev_dir=unknown for _nsca_ev_dir in /usr /usr/local /usr/pkg do dnl Solaris 10 doesn't have "test -e". AS_IF([test -r "$_nsca_ev_dir/include/ev.h"], [nsca_ev_dir=$_nsca_ev_dir break]) done AS_IF([test "x$nsca_ev_dir" != xunknown], [AC_MSG_RESULT([$nsca_ev_dir])], [AC_MSG_RESULT([not found, continuing anyway])])], [embedded], [AC_MSG_RESULT([yes, the bundled copy]) _NSCA_LIB_EV_EMBEDDED nsca_lib_ev_embedded=yes], [AC_MSG_RESULT([yes]) nsca_lib_ev_embedded=no]) AS_IF([test "x$nsca_ev_dir" != xembedded && test "x$nsca_ev_dir" != xunknown && test "x$nsca_ev_dir" != x/usr], [EVCPPFLAGS="-I$nsca_ev_dir/include" EVLDFLAGS="-L$nsca_ev_dir/lib" CPPFLAGS="$EVCPPFLAGS $CPPFLAGS" LDFLAGS="$EVLDFLAGS $LDFLAGS"]) AS_IF([test "x$nsca_lib_ev_embedded" != xyes], [AC_CHECK_HEADER([ev.h], [AC_CHECK_LIB([ev], [ev_version_major], [EVLIBS="-lev" AC_CHECK_LIB([ev], [ev_run], [:], [_NSCA_LIB_EV_ERROR([libev too old], [$nsca_lib_ev_embedded]) nsca_lib_ev_embedded=yes])], [_NSCA_LIB_EV_ERROR([cannot link with libev], [$nsca_lib_ev_embedded]) nsca_lib_ev_embedded=yes])], [_NSCA_LIB_EV_ERROR([libev header not found], [$nsca_lib_ev_embedded]) nsca_lib_ev_embedded=yes])]) AS_IF([test "x$nsca_lib_ev_embedded" = xyes], [unset EVCPPFLAGS EVLDFLAGS EVLIBS], [nsca_lib_ev_embedded=no]) AC_SUBST([EVCPPFLAGS]) AC_SUBST([EVLDFLAGS]) AC_SUBST([EVLIBS]) AC_DEFINE([EV_COMPAT3], [0], [Define to 1 if libev 3.x compatibility is desired.]) CPPFLAGS=$nsca_save_CPPFLAGS LDFLAGS=$nsca_save_LDFLAGS ])# NSCA_LIB_EV # _NSCA_LIB_EV_EMBEDDED # --------------------- # Arrange for using the bundled copy of libev. AC_DEFUN([_NSCA_LIB_EV_EMBEDDED], [ dnl Why don't we use m4_include? The difference is that m4_include warns dnl against multiple inclusions, while the builtin does not. Multiple dnl inclusions yield unexpected results if the included file calls m4_define dnl without quoting the first argument. However, lib/ev/libev.m4 doesn't do dnl that, so it should be safe to include it more than once. m4_builtin([include], [lib/ev/libev.m4]) AC_DEFINE([EV_MULTIPLICITY], [0], [Define to 1 if the bundled libev should support multiple event loops.]) AC_DEFINE([EV_MINPRI], [-1], [Define to the smallest allowed priority in the bundled libev.]) AC_DEFINE([EV_MAXPRI], [1], [Define to the largest allowed priority in the bundled libev.]) AC_DEFINE([EV_VERIFY], [0], [Define to the desired internal verification level of the bundled libev.]) AC_DEFINE([ECB_AVOID_PTHREADS], [1], dnl Otherwise, building on AIX will fail. [Define to 1 if memory fences aren't needed for the bundled libev.]) ])# _NSCA_LIB_EV_EMBEDDED # _NSCA_LIB_EV_ERROR(MESSAGE, USE_EMBEDDED_EV) # -------------------------------------------- # If USE_EMBEDDED_EV is set to "no", bail out with the specified error MESSAGE. # Otherwise, spit out the specified MESSAGE and a note that we're going to use # the included copy of libev, and then call _NSCA_LIB_EV_EMBEDDED. AC_DEFUN([_NSCA_LIB_EV_ERROR], [ AS_IF([test "x$2" = xno], [AC_MSG_ERROR([$1])], [AC_MSG_NOTICE([$1, using bundled copy]) _NSCA_LIB_EV_EMBEDDED]) ])# _NSCA_LIB_EV_ERROR dnl vim:set joinspaces textwidth=80: nsca-ng-1.6/m4/networking.m4000066400000000000000000000050471344421036200156640ustar00rootroot00000000000000# Copyright (c) 2013 Holger Weiss # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # NSCA_LIB_NETWORKING # ------------------- # Check the availability of some networking header files and types. Also, find # out which libraries define the networking functions we're interested in and # add the according flags to LIBS. We bail out if any of these functions aren't # found. AC_DEFUN([NSCA_LIB_NETWORKING], [ AC_CHECK_HEADERS([arpa/inet.h netinet/in.h sys/socket.h]) AC_CHECK_TYPES([struct sockaddr_storage, struct sockaddr_in6], [], [], [[#include #ifdef HAVE_SYS_SOCKET_H #include #endif #ifdef HAVE_NETINET_IN_H #include #endif]]) # Solaris 8 and newer provide the inet_ntop(3) function in libnsl, older # Solaris versions provide inet_ntop(3) in libresolv instead. AC_SEARCH_LIBS([inet_ntop], [nsl resolv], [], [AC_MSG_FAILURE([cannot find the `inet_ntop' function])]) # The libsocket library might or might not depend on libnsl. AC_SEARCH_LIBS([getpeername], [socket], [], [AC_CHECK_LIB([nsl], [getpeername], [LIBS="-lsocket -lnsl $LIBS"], [AC_MSG_FAILURE([cannot find the `getpeername' function])], [-lsocket -lnsl])]) ])# NSCA_LIB_NETWORKING dnl vim:set joinspaces textwidth=80: nsca-ng-1.6/m4/openssl.m4000066400000000000000000000076301344421036200151600ustar00rootroot00000000000000# Copyright (c) 2013 Holger Weiss # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # NSCA_LIB_OPENSSL # ---------------- # Check the availability of OpenSSL 1.0.0 or newer. As this is a required # dependency, we bail out if the user specified "--without-openssl", if we fail # to link against the library, or if the OpenSSL version we found is too old. # On success, we set the output variables SSLCPPFLAGS, SSLLDFLAGS, and SSLLIBS # to appropriate values. (Why are there no underscores in these variable names? # Because Automake treats names like "foo_CPPFLAGS" specially.) AC_DEFUN([NSCA_LIB_OPENSSL], [ nsca_save_CPPFLAGS=$CPPFLAGS nsca_save_LDFLAGS=$LDFLAGS AC_ARG_WITH([openssl], [AS_HELP_STRING([--with-openssl=PATH], [use the OpenSSL library in PATH])], [nsca_ssl_dir=$with_openssl], [nsca_ssl_dir=yes]) AC_MSG_CHECKING([whether OpenSSL is desired]) AS_CASE([$nsca_ssl_dir], [no], [AC_MSG_RESULT([no]) AC_MSG_ERROR([building without OpenSSL is not supported])], [yes], [AC_MSG_RESULT([yes]) AC_MSG_CHECKING([for the location of OpenSSL]) nsca_ssl_dir=unknown for _nsca_ssl_dir in "$ac_pwd/lib/ssl" /usr /usr/local /usr/local/ssl \ /usr/pkg do dnl Solaris 10 doesn't have "test -e". AS_IF([test -r "$_nsca_ssl_dir/include/openssl/ssl.h"], [nsca_ssl_dir=$_nsca_ssl_dir break]) done AS_IF([test "x$nsca_ssl_dir" != xunknown], [AC_MSG_RESULT([$nsca_ssl_dir])], [AC_MSG_RESULT([not found, continuing anyway])])], [AC_MSG_RESULT([yes])]) AS_IF([test "x$nsca_ssl_dir" != xunknown && test "x$nsca_ssl_dir" != x/usr], [SSLCPPFLAGS="-I$nsca_ssl_dir/include" SSLLDFLAGS="-L$nsca_ssl_dir/lib" CPPFLAGS="$SSLCPPFLAGS $CPPFLAGS" LDFLAGS="$SSLLDFLAGS $LDFLAGS"]) AC_CHECK_HEADER([openssl/ssl.h], [], [AC_MSG_ERROR([OpenSSL header files not found])]) AC_CHECK_LIB([crypto], [BIO_new], [AC_CHECK_LIB([crypto], [DSO_load], [SSLLIBS='-lcrypto'], [AC_CHECK_LIB([dl], [DSO_load], [SSLLIBS='-lcrypto -ldl'], [AC_MSG_FAILURE([cannot link with OpenSSL])], [-lcrypto -ldl])])], [AC_MSG_FAILURE([cannot link with OpenSSL])]) AC_CHECK_LIB([ssl], [SSL_new], [SSLLIBS="-lssl $SSLLIBS"], [AC_MSG_FAILURE([cannot link with OpenSSL])], [$SSLLIBS]) AC_CHECK_LIB([ssl], [SSL_get_psk_identity], [:], [AC_MSG_ERROR([OpenSSL too old, version 1.0.0 or newer is required])], [$SSLLIBS]) AC_SUBST([SSLCPPFLAGS]) AC_SUBST([SSLLDFLAGS]) AC_SUBST([SSLLIBS]) CPPFLAGS=$nsca_save_CPPFLAGS LDFLAGS=$nsca_save_LDFLAGS ])# NSCA_LIB_OPENSSL dnl vim:set joinspaces textwidth=80: nsca-ng-1.6/m4/pidfile.m4000066400000000000000000000062141344421036200151060ustar00rootroot00000000000000# Copyright (c) 2013 Holger Weiss # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # NSCA_LIB_PIDFILE # ---------------- # Check the availability of FreeBSD's pidfile(3) API (which is also available on # some Linux systems). If it's found, we set $nsca_lib_pidfile_embedded to "no" # and arrange for using the library which provides the API. Otherwise, we set # $nsca_lib_pidfile_embedded to "yes" and arrange for using the bundled # replacement functions. AC_DEFUN([NSCA_LIB_PIDFILE], [ AC_CHECK_HEADERS([sys/param.h]) AC_CHECK_HEADERS([bsd/libutil.h libutil.h], [AC_CHECK_FUNC([pidfile_open], [nsca_lib_pidfile_embedded=no], [AC_CHECK_LIB([bsd], [pidfile_open], [PIDFILELIBS='-lbsd' nsca_lib_pidfile_embedded=no], [AC_CHECK_LIB([util], [pidfile_open], [PIDFILELIBS='-lutil' nsca_lib_pidfile_embedded=no], [nsca_lib_pidfile_embedded=yes])])]) break], [nsca_lib_pidfile_embedded=yes], [[#if HAVE_SYS_PARAM_H #include #endif]]) AS_IF([test "x$nsca_lib_pidfile_embedded" = xyes], [_NSCA_LIB_PIDFILE_EMBEDDED]) AC_SUBST([PIDFILELIBS]) ])# NSCA_LIB_PIDFILE # _NSCA_LIB_PIDFILE_EMBEDDED # -------------------------- # Arrange for using the bundled pidfile functions. If the flock(2) function is # found, we set $nsca_func_flock to "yes"; otherwise, we set that variable to # "no". AC_DEFUN([_NSCA_LIB_PIDFILE_EMBEDDED], [ AC_CHECK_HEADERS([sys/file.h]) AC_TYPE_MODE_T # At least on AIX 5.3, flock(2) is hidden in libbsd. AC_CHECK_FUNC([flock], [nsca_func_flock=yes], [AC_CHECK_LIB([bsd], [flock], [PIDFILELIBS='-lbsd' nsca_func_flock=yes], [nsca_func_flock=no])]) AS_IF([test "x$nsca_func_flock" = xyes], [AC_DEFINE([HAVE_FLOCK], [1], [Define to 1 if you have the `flock' function.])]) ])# _NSCA_LIB_PIDFILE_EMBEDDED dnl vim:set joinspaces textwidth=80: nsca-ng-1.6/m4/progname.m4000066400000000000000000000052621344421036200153040ustar00rootroot00000000000000# Copyright (c) 2013 Holger Weiss # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # NSCA_FUNC_PROGNAME # ------------------ # Check the availability of BSD-style getprogname(3) and setprogname(3) # functions. If either of these functions isn't found, arrange for using the # bundled implementation. # # Note that some Linux systems provide a crippled version of these functions in # libbsd (they return the full pathname of the program, not just the final # component). On those systems, the functions are declared in . # Using AC_CHECK_DECL instead of AC_CHECK_FUNC should make sure that they won't # be used. # # Also note that glibc provides program_invocation_short_name(3) in if # _GNU_SOURCE is defined, but there's not much point in using it. AC_DEFUN([NSCA_FUNC_PROGNAME], [ AC_CHECK_DECL([getprogname], [nsca_func_getprogname=yes AC_DEFINE([HAVE_GETPROGNAME], [1], [Define to 1 if you have the `getprogname' function.])], [nsca_func_getprogname=no], [[#include ]]) AC_CHECK_DECL([setprogname], [nsca_func_setprogname=yes AC_DEFINE([HAVE_SETPROGNAME], [1], [Define to 1 if you have the `setprogname' function.])], [nsca_func_setprogname=no], [[#include ]]) AS_IF([test "x$nsca_func_getprogname" != xyes || test "x$nsca_func_setprogname" != xyes], [AC_LIBOBJ([progname])]) ])# NSCA_FUNC_PROGNAME dnl vim:set joinspaces textwidth=80: nsca-ng-1.6/m4/systemd.m4000066400000000000000000000075031344421036200151640ustar00rootroot00000000000000# Copyright (c) 2013 Holger Weiss # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # NSCA_LIB_SYSTEMD # ---------------- # Check the availability of systemd. If the systemd (or the old systemd-daemon) # library is found, we define HAVE_SYSTEMD_SD_DAEMON_H to 1. We then also set # the output variables SYSTEMDCPPFLAGS, SYSTEMDLDFLAGS, and SYSTEMDLIBS to # appropriate values. (Why are there no underscores in these variable names? # Because Automake treats names like "foo_CPPFLAGS" specially.) AC_DEFUN([NSCA_LIB_SYSTEMD], [ nsca_save_CPPFLAGS=$CPPFLAGS nsca_save_LDFLAGS=$LDFLAGS nsca_systemd_dir=unknown AC_ARG_WITH([systemd], [AS_HELP_STRING([--with-systemd=PATH], [use the systemd library in PATH])], [nsca_with_systemd=$with_systemd], [nsca_with_systemd=maybe]) AC_MSG_CHECKING([whether systemd is desired]) AS_CASE([$nsca_with_systemd], [no], [AC_MSG_RESULT([no])], [yes|maybe], [AC_MSG_RESULT([$nsca_with_systemd]) AC_MSG_CHECKING([for the location of systemd]) for _nsca_systemd_dir in "$ac_pwd/lib/systemd" /usr /usr/local /usr/pkg do dnl Solaris 10 doesn't have "test -e". AS_IF([test -r "$_nsca_systemd_dir/include/systemd/sd-daemon.h"], [nsca_systemd_dir=$_nsca_systemd_dir break]) done AS_IF([test "x$nsca_systemd_dir" != xunknown], [AC_MSG_RESULT([$nsca_systemd_dir]) AS_IF([test "x$nsca_with_systemd" = xmaybe], [nsca_with_systemd=yes])], [AC_MSG_RESULT([not found]) AS_IF([test "x$nsca_with_systemd" = xmaybe], [nsca_with_systemd=no])])], [AC_MSG_RESULT([yes]) nsca_with_systemd=yes nsca_systemd_dir=$nsca_with_systemd]) AS_IF([test "x$nsca_with_systemd" = xyes], [AS_IF([test "x$nsca_systemd_dir" != xunknown && test "x$nsca_systemd_dir" != x/usr], [SYSTEMDCPPFLAGS="-I$nsca_systemd_dir/include" SYSTEMDLDFLAGS="-L$nsca_systemd_dir/lib" CPPFLAGS="$SYSTEMDCPPFLAGS $CPPFLAGS" LDFLAGS="$SYSTEMDLDFLAGS $LDFLAGS"]) AC_CHECK_HEADERS([systemd/sd-daemon.h], [], [AC_MSG_ERROR([systemd header file not found])]) AC_CHECK_LIB([systemd], [sd_notify], [SYSTEMDLIBS='-lsystemd'], [AC_CHECK_LIB([systemd-daemon], [sd_notify], [SYSTEMDLIBS='-lsystemd-daemon'], [AC_MSG_FAILURE([cannot link with systemd-daemon library])])])]) AC_SUBST([SYSTEMDCPPFLAGS]) AC_SUBST([SYSTEMDLDFLAGS]) AC_SUBST([SYSTEMDLIBS]) CPPFLAGS=$nsca_save_CPPFLAGS LDFLAGS=$nsca_save_LDFLAGS ])# NSCA_LIB_SYSTEMD dnl vim:set joinspaces textwidth=80: nsca-ng-1.6/m4/xprintf.m4000066400000000000000000000227141344421036200151670ustar00rootroot00000000000000# Copyright (c) 2013 Holger Weiss # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # HW_HEADER_STDARG_H # ------------------ # Define HAVE_STDARG_H to 1 if is available. AC_DEFUN([HW_HEADER_STDARG_H], [ AC_PREREQ([2.60])dnl Older releases should work if AC_CHECK_HEADERS is used. AC_CHECK_HEADERS_ONCE([stdarg.h]) ])# HW_HEADER_STDARG_H # HW_HEADER_VARARGS_H # ------------------- # Define HAVE_VARARGS_H to 1 if is available. AC_DEFUN([HW_HEADER_VARARGS_H], [ AC_PREREQ([2.60])dnl Older releases should work if AC_CHECK_HEADERS is used. AC_CHECK_HEADERS_ONCE([varargs.h]) ])# HW_HEADER_VARARGS_H # HW_FUNC_VA_COPY # --------------- # Set $hw_cv_func_va_copy to "yes" or "no". Define HAVE_VA_COPY to 1 if # $hw_cv_func_va_copy is set to "yes". Note that it's "unspecified whether # va_copy and va_end are macros or identifiers declared with external linkage." # (C99: 7.15.1, 1) Therefore, the presence of va_copy(3) cannot simply "be # tested with #ifdef", as suggested by the Autoconf manual (5.5.1). AC_DEFUN([HW_FUNC_VA_COPY], [ AC_REQUIRE([HW_HEADER_STDARG_H])dnl Our check evaluates HAVE_STDARG_H. AC_REQUIRE([HW_HEADER_VARARGS_H])dnl Our check evaluates HAVE_VARARGS_H. AC_CACHE_CHECK([for va_copy], [hw_cv_func_va_copy], [AC_RUN_IFELSE( [AC_LANG_PROGRAM( [[#if HAVE_STDARG_H #include #elif HAVE_VARARGS_H #include #endif]], [[va_list ap, aq; va_copy(aq, ap);]])], [hw_cv_func_va_copy=yes], [hw_cv_func_va_copy=no], [hw_cv_func_va_copy=no])]) AS_IF([test "$hw_cv_func_va_copy" = yes], [AC_DEFINE([HAVE_VA_COPY], [1], [Define to 1 if you have the `va_copy' function or macro.])]) ])# HW_FUNC_VA_COPY # HW_FUNC___VA_COPY # ----------------- # Set $hw_cv_func___va_copy to "yes" or "no". Define HAVE___VA_COPY to 1 if # $hw_cv_func___va_copy is set to "yes". AC_DEFUN([HW_FUNC___VA_COPY], [ AC_REQUIRE([HW_HEADER_STDARG_H])dnl Our check evaluates HAVE_STDARG_H. AC_REQUIRE([HW_HEADER_VARARGS_H])dnl Our check evaluates HAVE_VARARGS_H. AC_CACHE_CHECK([for __va_copy], [hw_cv_func___va_copy], [AC_RUN_IFELSE( [AC_LANG_PROGRAM( [[#if HAVE_STDARG_H #include #elif HAVE_VARARGS_H #include #endif]], [[va_list ap, aq; __va_copy(aq, ap);]])], [hw_cv_func___va_copy=yes], [hw_cv_func___va_copy=no], [hw_cv_func___va_copy=no])]) AS_IF([test "$hw_cv_func___va_copy" = yes], [AC_DEFINE([HAVE___VA_COPY], [1], [Define to 1 if you have the `__va_copy' function or macro.])]) ])# HW_FUNC___VA_COPY # HW_FUNC_VSNPRINTF # ----------------- # Set $hw_cv_func_vsnprintf and $hw_cv_func_vsnprintf_c99 to "yes" or "no", # respectively. Define HAVE_VSNPRINTF to 1 only if $hw_cv_func_vsnprintf_c99 # is set to "yes". Otherwise, define vsnprintf to rpl_vsnprintf and make sure # the replacement function will be built. AC_DEFUN([HW_FUNC_VSNPRINTF], [ AC_PREREQ([2.60])dnl 2.59 should work if some AC_TYPE_* macros are replaced. AC_REQUIRE([HW_HEADER_STDARG_H])dnl Our check evaluates HAVE_STDARG_H. AC_CHECK_FUNC([vsnprintf], [hw_cv_func_vsnprintf=yes], [hw_cv_func_vsnprintf=no]) AS_IF([test "$hw_cv_func_vsnprintf" = yes], [AC_CACHE_CHECK([whether vsnprintf is C99-compliant], [hw_cv_func_vsnprintf_c99], [AC_RUN_IFELSE( [AC_LANG_PROGRAM( [[#if HAVE_STDARG_H #include #endif #include static int testprintf(char *buf, size_t size, const char *fmt, ...) { int result; va_list ap; va_start(ap, fmt); result = vsnprintf(buf, size, fmt, ap); va_end(ap); return result; }]], [[char buf[43]; if (testprintf(buf, 4, "The answer is %27.2g.", 42.0) != 42 || testprintf(buf, 0, "No, it's %32zu.", (size_t)42) != 42 || buf[0] != 'T' || buf[3] != '\0') return 1;]])], [hw_cv_func_vsnprintf_c99=yes], [hw_cv_func_vsnprintf_c99=no], [hw_cv_func_vsnprintf_c99=no])])], [hw_cv_func_vsnprintf_c99=no]) AS_IF([test "$hw_cv_func_vsnprintf_c99" = yes], [AC_DEFINE([HAVE_VSNPRINTF], [1], [Define to 1 if you have a C99-compliant `vsnprintf' function.])], [AC_DEFINE([vsnprintf], [rpl_vsnprintf], [Define to rpl_vsnprintf if the replacement function should be used.]) AC_CHECK_HEADERS([inttypes.h locale.h stddef.h stdint.h]) AC_CHECK_MEMBERS([struct lconv.decimal_point, struct lconv.thousands_sep], [], [], [[#include ]]) AC_TYPE_LONG_DOUBLE AC_TYPE_LONG_LONG_INT AC_TYPE_UNSIGNED_LONG_LONG_INT AC_TYPE_SIZE_T AC_TYPE_INTMAX_T AC_TYPE_UINTMAX_T AC_TYPE_UINTPTR_T AC_CHECK_TYPES([ptrdiff_t]) AC_CHECK_FUNCS([localeconv]) _HW_FUNC_XPRINTF_REPLACE]) ])# HW_FUNC_VSNPRINTF # HW_FUNC_SNPRINTF # ---------------- # Set $hw_cv_func_snprintf and $hw_cv_func_snprintf_c99 to "yes" or "no", # respectively. Define HAVE_SNPRINTF to 1 only if $hw_cv_func_snprintf_c99 # is set to "yes". Otherwise, define snprintf to rpl_snprintf and make sure # the replacement function will be built. AC_DEFUN([HW_FUNC_SNPRINTF], [ AC_REQUIRE([HW_FUNC_VSNPRINTF])dnl Our snprintf(3) calls vsnprintf(3). AC_CHECK_FUNC([snprintf], [hw_cv_func_snprintf=yes], [hw_cv_func_snprintf=no]) AS_IF([test "$hw_cv_func_snprintf" = yes], [AC_CACHE_CHECK([whether snprintf is C99-compliant], [hw_cv_func_snprintf_c99], [AC_RUN_IFELSE( [AC_LANG_PROGRAM([[#include ]], [[char buf[43]; if (snprintf(buf, 4, "The answer is %27.2g.", 42.0) != 42 || snprintf(buf, 0, "No, it's %32zu.", (size_t)42) != 42 || buf[0] != 'T' || buf[3] != '\0') return 1;]])], [hw_cv_func_snprintf_c99=yes], [hw_cv_func_snprintf_c99=no], [hw_cv_func_snprintf_c99=no])])], [hw_cv_func_snprintf_c99=no]) AS_IF([test "$hw_cv_func_snprintf_c99" = yes], [AC_DEFINE([HAVE_SNPRINTF], [1], [Define to 1 if you have a C99-compliant `snprintf' function.])], [AC_DEFINE([snprintf], [rpl_snprintf], [Define to rpl_snprintf if the replacement function should be used.]) _HW_FUNC_XPRINTF_REPLACE]) ])# HW_FUNC_SNPRINTF # HW_FUNC_VASPRINTF # ----------------- # Set $hw_cv_func_vasprintf to "yes" or "no". Define HAVE_VASPRINTF to 1 if # $hw_cv_func_vasprintf is set to "yes". Otherwise, define vasprintf to # rpl_vasprintf and make sure the replacement function will be built. AC_DEFUN([HW_FUNC_VASPRINTF], [ AC_REQUIRE([HW_FUNC_VSNPRINTF])dnl Our vasprintf(3) calls vsnprintf(3). AC_CHECK_FUNCS([vasprintf], [hw_cv_func_vasprintf=yes], [hw_cv_func_vasprintf=no]) AS_IF([test "$hw_cv_func_vasprintf" = no], [AC_DEFINE([vasprintf], [rpl_vasprintf], [Define to rpl_vasprintf if the replacement function should be used.]) AC_CHECK_HEADERS([stdlib.h]) HW_FUNC_VA_COPY AS_IF([test "$hw_cv_func_va_copy" = no], [HW_FUNC___VA_COPY]) _HW_FUNC_XPRINTF_REPLACE]) ])# HW_FUNC_VASPRINTF # HW_FUNC_ASPRINTF # ---------------- # Set $hw_cv_func_asprintf to "yes" or "no". Define HAVE_ASPRINTF to 1 if # $hw_cv_func_asprintf is set to "yes". Otherwise, define asprintf to # rpl_asprintf and make sure the replacement function will be built. AC_DEFUN([HW_FUNC_ASPRINTF], [ AC_REQUIRE([HW_FUNC_VASPRINTF])dnl Our asprintf(3) calls vasprintf(3). AC_CHECK_FUNCS([asprintf], [hw_cv_func_asprintf=yes], [hw_cv_func_asprintf=no]) AS_IF([test "$hw_cv_func_asprintf" = no], [AC_DEFINE([asprintf], [rpl_asprintf], [Define to rpl_asprintf if the replacement function should be used.]) _HW_FUNC_XPRINTF_REPLACE]) ])# HW_FUNC_ASPRINTF # _HW_FUNC_XPRINTF_REPLACE # ------------------------ # Arrange for building xprintf.c. Must be called if one or more of the # functions provided by xprintf.c are needed. AC_DEFUN([_HW_FUNC_XPRINTF_REPLACE], [ AS_IF([test "x$_hw_cv_func_xprintf_replace_done" != xyes], [AC_C_CONST HW_HEADER_STDARG_H AC_LIBOBJ([xprintf]) _hw_cv_func_xprintf_replace_done=yes]) ])# _HW_FUNC_XPRINTF_REPLACE dnl vim:set joinspaces textwidth=80: nsca-ng-1.6/man/000077500000000000000000000000001344421036200134605ustar00rootroot00000000000000nsca-ng-1.6/man/Makefile.am000066400000000000000000000040461344421036200155200ustar00rootroot00000000000000## Process this file with automake(1) to produce Makefile.in. ## Copyright (c) 2013 Holger Weiss ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1. Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## ## 2. Redistributions in binary form must reproduce the above copyright notice, ## this list of conditions and the following disclaimer in the documentation ## and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE ## LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ## CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF ## SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ## INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ## CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ## ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ## POSSIBILITY OF SUCH DAMAGE. edit = sed \ -e 's|[@]sysconfdir[@]|$(sysconfdir)|g' \ -e 's|[@]localstatedir[@]|$(localstatedir)|g' \ -e 's|[@]version[@]|$(PACKAGE_VERSION)|g' \ -e 's|[@]date[@]|$(RELEASE_DATE)|g' man8_MANS = nsca-ng.man send_nsca.man man5_MANS = nsca-ng.cfg.man send_nsca.cfg.man PDF_FILES = nsca-ng.pdf nsca-ng.cfg.pdf send_nsca.pdf send_nsca.cfg.pdf EXTRA_DIST = nsca-ng.in send_nsca.in nsca-ng.cfg.in send_nsca.cfg.in CLEANFILES = $(man8_MANS) $(man5_MANS) $(PDF_FILES) .in.man: $(AM_V_GEN)$(edit) $< > $@ .man.ps: $(AM_V_GEN)$(top_srcdir)/build-aux/man2ps $< $@ .ps.pdf: $(AM_V_at)ps2pdf $< $@ pdf-local: $(PDF_FILES) nsca-ng-1.6/man/nsca-ng.cfg.in000066400000000000000000000322531344421036200161010ustar00rootroot00000000000000.\" Copyright (c) 2013 Holger Weiss .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. . .TH nsca\-ng.cfg 5 "@date@" "Version @version@" "The NSCA\-ng Manual" . .SH NAME . .B nsca\-ng.cfg \- NSCA\-ng server configuration file . .SH SYNOPSIS . .B @sysconfdir@/nsca\-ng.cfg . .SH DESCRIPTION . The .BR nsca\-ng (8) process reads configuration data from the file specified with .B \-c on the command line or from .IR @sysconfdir@/nsca\-ng.cfg . . .SS File Format . Zero or more global settings and one or more authorizations must be defined in the configuration file (see the .B Global Settings subsection and the .B Authorizations subsection, respectively). They may appear in arbitrary order. An authorization is specified using the .B authorize keyword followed by a (possibly quoted) client identity string and a brace-enclosed block of corresponding authorization settings. However, an authorization setting may also be specified as a global setting outside of these .B authorize sections. In this case, it serves as a global fallback for authorization sections that don't define the setting in question. . .PP Global settings and authorization settings are defined by specifying a variable name followed by an equals sign (\(lq=\(rq) and a value (or possibly a list of values). Values can be strings, integers, or floating-point numbers. Strings have to be enclosed in single or double quotes if they contain whitespace characters, hash mark characters, or literal quotation marks. Otherwise, quoting is optional. To specify a literal single or double quote in a string, either escape it by preceding it with a backslash (\(lq\\\(rq) or quote the string using the other quote character. A literal backslash must be preceded with a second backslash if the string is enclosed in double quotes. . .PP A variable can be set to the value of an environment variable by specifying .BI ${ FOO }, where .I FOO is the name of the environment variable. The same can be done by specifying .BI ${ FOO :\- bar }, except that in this case, the value .I bar will be assigned when the environment variable .I FOO is not set. . .PP Any whitespace surrounding tokens is ignored. Empty lines and comments are also ignored. Comments are introduced with a hash mark character (\(lq#\(rq) and span to the end of the line. If the last character of a line is a backslash (\(lq\\\(rq), the subsequent line is treated as a continuation of the current line (and the backslash is otherwise ignored). . .PP The special directive .BI include(\(dq file \(dq) tells .BR nsca\-ng (8) to treat the contents of the specified .I file as if those contents had appeared at the point where this directive appears. If a directory is specified instead of a .IR file , all files with a .I .cfg or .I .conf extension in this directory and all subdirectories will be included. Symbolic links are followed. . .PP In the following subsections, the type of each value is denoted after an equals sign in angle brackets. . .SS Global Settings . The .BR nsca\-ng (8) server recognizes the following global variables. . .TP \fBchroot\fP\ =\ <\fIstring\fP> . On startup, perform a .BR chroot (2) operation to the specified directory. By default, .BR nsca\-ng (8) does not call .BR chroot (2). If this directive is used, the .BR command_file , .BR pid_file , and .B temp_directory must be specified relative to this directory. . .TP \fBcommand_file\fP\ =\ <\fIstring\fP> . Submit monitoring commands to the specified path name. This should be the named pipe .SM (FIFO) that Nagios (or a compatible monitoring solution) checks for external commands to process. The default is .IR @localstatedir@/nagios/rw/nagios.cmd . The specified value will be overridden if .BR nsca\-ng (8) is called with the .B \-C option. . .TP \fBlisten\fP\ =\ <\fIstring\fP> . Bind to the specified .SM IP address or host name. The default setting is \(lq*\(rq, which tells .BR nsca\-ng (8) to listen on all available interfaces. A colon (\(lq:\(rq) followed by a service name or port number may be appended to override the default port (5668) used by the .BR nsca\-ng (8) server. The specified value will be ignored if .BR nsca\-ng (8) is called with the .B \-b option, of if it is socket activated by .BR systemd (1). . .TP \fBlog_level\fP\ =\ <\fIinteger\fP> . Use the specified log level, which must be an integer value between 0 and 5 inclusive. A value of 0 tells .BR nsca\-ng (8) to generate only fatal error messages, 1 adds non-fatal error messages, 2 adds warnings, 3 additionally spits out every submitted command (plus startup and shutdown notices), 4 also logs each message sent or received at the protocol level, and 5 generates additional debug output. The default log level is 3. The specified value will be overridden if .BR nsca\-ng (8) is called with the .B \-l option. . .TP \fBmax_command_size\fP\ =\ <\fIinteger\fP> . Refuse monitoring commands (including check result submissions) which are longer than the specified number of bytes. Setting this variable to 0 tells .BR nsca\-ng (8) to accept commands of arbitrary length. The default value is 16384. . .TP \fBmax_queue_size\fP\ =\ <\fIinteger\fP> . Don't queue more than the specified number of megabytes worth of monitoring commands while Nagios isn't running (or not reading the command file). When the amount of available data exceeds this threshold, the queued data is thrown away. If this variable is set to 0, .BR nsca\-ng (8) queues an unlimited amount of data (until it exits due to running out of memory). The default value is 1024 (i.e., 1 gigabyte). . .TP \fBpid_file\fP\ =\ <\fIstring\fP> . During startup, try to create and lock the specified file and write the process .SM ID of the .BR nsca\-ng (8) daemon into it. Bail out if another process holds a lock on that file. By default, no such .SM PID file is written. The specified value will be overridden if .BR nsca\-ng (8) is called with the .B \-p option. . .TP \fBtemp_directory\fP\ =\ <\fIstring\fP> . Write temporary files to the specified directory. Temporary files are only written if clients submit very large commands (which cannot be written to the named pipe atomically). It is recommended to specify a directory which resides on a memory file system. By default, .I /tmp is used. . .TP \fBtimeout\fP\ =\ <\fIfloating\-point\fP> . Close the connection if a client didn't show any activity for the specified number of seconds. If this value is set to 0.0, .BR nsca\-ng (8) won't enforce connection timeouts. The default setting is 60.0 seconds. . .TP \fBtls_ciphers\fP\ =\ <\fIstring\fP> . Limit the acceptable .SM TLS-PSK cipher suites to the specified list of ciphers. The format of the string is described in the .BR ciphers (1) manual. By default, the ciphers in the list .SM \f(CWPSK-AES256-CBC-SHA:PSK-AES128-CBC-SHA:PSK-3DES-EDE-CBC-SHA:PSK-RC4-SHA\fP will be accepted. . .TP \fBuser\fP\ =\ <\fIstring\fP> . Switch to the specified user, and to the groups the user belongs to. This is done early on startup: after the configuration file has been read, but before the listening socket and (possibly) the .SM PID file are created. By default, .BR nsca\-ng (8) runs with the privileges of the invoking user. . .SS Authorizations . As mentioned above, an authorization section is introduced with the .B authorize keyword and a client identity field followed by a brace-delimited block of one or more authorization settings. A client provides its identity during the connection handshake. The server uses the provided identity string for looking up the .B authorize section applicable to the client. The corresponding section, if any, defines the authentication and authorization settings for the client in question. If no section explicitly defined for this client identity is found, but a section for the special client identity \(dq*\(dq (including the quotes) is defined, this section is used as a fallback. Note that no other wildcard characters are available, and that the \(lq*\(rq character has no special meaning in the client identity field except when specified exactly as described. . .PP Within the brace-delimited block of an authorization section, values may be assigned to the variables listed below. The pattern strings assigned to the .BR commands , .BR hosts , and .B services variables are .SM POSIX \(lqextended\(rq regular expressions, but with an implicit \(lq^\(rq at the beginning and \(lq$\(rq at the end of the patterns. Multiple patterns can be specified as a brace-enclosed, comma-separated list; check results and commands will then be accepted if they match any of the specified patterns. Commands and check results will be rejected unless these settings authorize the client to submit them. . .TP \fBcommands\fP\ =\ <\fI(list of) string(s)\fP> . Match the specified regular expression(s) against submitted monitoring commands and accept commands that match any of these expressions. The patterns are matched against the full command string supplied by the client, .I except for the leading bracketed timestamp and any whitespace following that timestamp. . .TP \fBhosts\fP\ =\ <\fI(list of) string(s)\fP> . Match the specified regular expression(s) against the \(lqhost name\(rq field of client-supplied .SM PROCESS_HOST_CHECK_RESULT commands and accept such commands if they match any of these expressions. . .TP \fBpassword\fP\ =\ <\fIstring\fP> . Reject connections from clients that don't use the specified password. This setting is mandatory. . .TP \fBservices\fP\ =\ <\fI(list of) string(s)\fP> . Match the specified regular expression(s) against the \(lqservice description\(rq field of client-supplied .SM PROCESS_SERVICE_CHECK_RESULT commands and accept such commands if they match any of these expressions. If a specified string includes one or more at signs (\(lq@\(rq), only the part preceding the last of these at signs is matched against the \(lqservice description\(rq field. The part following this at sign is used as a separate pattern which is matched against the \(lqhost name\(rq field of the same command. A service check result is then accepted only if both matches succeed for a given command. . .SH EXAMPLES . The .B @sysconfdir@/nsca\-ng.cfg file might look similar to the following example. . .PP .RS .nf .ft CW . user = "nagios" chroot = "/var/nagios" # Other paths are relative to this one! command_file = "/rw/nagios.cmd" pid_file = "/run/nsca-ng.pid" temp_directory = "/dev/shm" listen = "monitoring.example.com:5668" tls_ciphers = "PSK-AES256-CBC-SHA" log_level = 3 max_command_size = 65536 max_queue_size = 128 timeout = 15.0 # # Authenticated "root" clients may submit arbitrary check # results and any other monitoring commands (see: # ). # authorize "root" { password = "g3m25sMCUAO4NecZGld1H4xcJ9uDWvhH" commands = ".*" } # # Authenticated "checker" clients may submit arbitrary check # results, but no other commands. # authorize "checker" { password = "ilzNanlE9XjMLdjrMkXnk09XBCTFQrj5" hosts = ".*" services = ".*" } # # Authenticated "web-checker" clients may submit check results # for arbitrary services on hosts whose names begin with "www". # authorize "web-checker" { password = "m2uaIWwiq3AIqN55m3QdjwptkU1Q4Oov" services = ".+@www.*" } # # Authenticated "nsca-checker" clients may talk to the NSCA-ng # server, but may not submit anything to Nagios. # authorize "nsca-checker" { password = "ceOKwxpz14lKXroC4yUjJZbov6VAyKuT" } # # Other authenticated clients may submit check results for the # "disk", "swap", and "load" services on arbitrary hosts. # authorize "*" { password = "awHW5vxr3DcA9EvcUC9T3a90QfEexsWd" services = { "disk", "swap", "load" } } . .ft P .fi .RE . .SH CAVEATS . Please set the permissions appropriately to make sure that only authorized users can access the .B @sysconfdir@/nsca\-ng.cfg file. . .SH "SEE ALSO" . .BR nsca\-ng (8), .BR send_nsca (8), .BR send_nsca.cfg (5), .BR regex (7) . .PP .I http://www.nagios.org/developerinfo/externalcommands/ . .SH AUTHOR . Holger Weiss . .\" vim:set filetype=nroff textwidth=72: nsca-ng-1.6/man/nsca-ng.in000066400000000000000000000133141344421036200153400ustar00rootroot00000000000000.\" Copyright (c) 2013 Holger Weiss .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. . .TH nsca\-ng 8 "@date@" "Version @version@" "The NSCA\-ng Manual" . .SH NAME . .B nsca\-ng \- monitoring command acceptor . .SH SYNOPSIS . .B nsca\-ng .RB [ \-FSs ] .RB [ \-b .IR listen ] .RB [ \-C .IR file ] .RB [ \-c .IR file ] .RB [ \-l .IR level ] .RB [ \-P .IR file ] . .PP .B nsca\-ng .BR \-h " | " \-V . .SH DESCRIPTION . The .B nsca\-ng server makes the Nagios command file accessible from remote systems. This allows for submitting passive check results, downtimes, and many other commands to Nagios (or compatible monitoring solutions). The communication with clients is .SM TLS encrypted and authenticated using pre-shared keys (as per .SM RFC 4279). The .B nsca\-ng server supports per-client passwords and fine-grained authorization control. . .PP The server process rereads its configuration file when it receives a hangup signal .SM (SIGHUP) by executing itself with the name and arguments it was started with. . .PP When compiled with .BR systemd (1) support, the .B nsca\-ng server auto-detects whether it was socket activated. If so, it behaves as if the .BR \-F option was specified, while it ignores the .BR \-b option and the .B listen setting in the .BR nsca\-ng.cfg (5) file. The .B nsca\-ng server supports .BR systemd (1)'s .B notify process startup type as well as the .B WatchdogSec feature (see the .BR systemd.service(5) manual). . .SH OPTIONS . .TP .BI \-b\ listen . Bind to the specified .I listen address or host name. The default setting is \(lq*\(rq, which tells .B nsca\-ng to listen on all available interfaces. A colon (\(lq:\(rq) followed by a service name or port number may be appended in order to override the default port (5668) used by .BR nsca\-ng . If this option is specified, the .B listen setting in the .BR nsca\-ng.cfg (5) file is ignored. . .TP .BI \-C\ file . Submit monitoring commands into the specified .IR file . This should be the named pipe .SM (FIFO) that Nagios checks for external commands to process. By default, .B nsca\-ng submits commands into .IR @localstatedir@/nagios/rw/nagios.cmd . This option takes precedence over the .B command_file setting in the .BR nsca\-ng.cfg (5) file. . .TP .BI \-c\ file . Read the configuration from the specified .I file instead of using the default configuration file .IR @sysconfdir@/nsca\-ng.cfg . If a directory is specified instead of a .IR file , the configuration will be read from all files with a .I .cfg or .I .conf extension in this directory and all subdirectories. Symbolic links are followed. . .TP .B \-F . Don't detach from the controlling terminal, and write all messages to the standard error output (unless the .BR \-s option is specified). . .TP .B \-h . Print usage information to the standard output and exit. . .TP .BI \-l\ level . Use the specified log .IR level , which must be an integer value between 0 and 5 inclusive. A value of 0 tells .B nsca\-ng to generate only fatal error messages, 1 adds non-fatal error messages, 2 adds warnings, 3 additionally spits out every submitted monitoring command (plus startup and shutdown notices), 4 also logs each message sent or received at the protocol level, and 5 generates additional debug output. The default log .I level is 3. If this option is specified, the .B log_level setting in the .BR nsca\-ng.cfg (5) file is ignored. . .TP .BI \-P\ file . During startup, try to create and lock the specified .I file and write the process .SM ID of the .B nsca\-ng daemon into it. Bail out if another process holds a lock on the .IR file . By default, no such .SM PID .I file is written. This option takes precedence over the .B pid_file setting in the .BR nsca\-ng.cfg (5) file. . .TP .B \-S . Write all messages to the standard error output and (with the exception of startup messages) to the system logger. This option may only be specified together with the .B \-F option. . .TP .B \-s . Send all messages to the system logger, except for startup messages. This is the default behaviour (unless the .B \-F option is specified). . .TP .B \-V . Print version information to the standard output and exit. . .SH FILES . .TP .I @sysconfdir@/nsca\-ng.cfg . The .BR nsca\-ng.cfg (5) configuration file. . .SH "SEE ALSO" . .BR nsca\-ng.cfg (5), .BR send_nsca (8), .BR send_nsca.cfg (5) . .PP .I http://www.nagios.org/developerinfo/externalcommands/ . .SH AUTHOR . Holger Weiss . .\" vim:set filetype=nroff textwidth=72: nsca-ng-1.6/man/send_nsca.cfg.in000066400000000000000000000132241344421036200165050ustar00rootroot00000000000000.\" Copyright (c) 2013 Holger Weiss .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. . .TH send_nsca.cfg 5 "@date@" "Version @version@" "The NSCA\-ng Manual" . .SH NAME . .B send_nsca.cfg \- NSCA\-ng client configuration file . .SH SYNOPSIS . .B @sysconfdir@/send_nsca.cfg . .SH DESCRIPTION . The .BR send_nsca (8) process reads configuration data from the file specified with .B \-c on the command line or from .IR @sysconfdir@/send_nsca.cfg . . .SS File Format . Configuration settings are defined by specifying a variable name followed by an equals sign (\(lq=\(rq) and a value, one setting per line. Values can be strings or integers. Strings have to be enclosed in single or double quotes if they contain whitespace characters, hash mark characters, or literal quotation marks. Otherwise, quoting is optional. To specify a literal single or double quote in a string, either escape it by preceding it with a backslash (\(lq\\\(rq) or quote the string using the other quote character. A literal backslash must be preceded with a second backslash. . .PP Any whitespace surrounding tokens is ignored. Empty lines and comments are also ignored. Comments are introduced with a hash mark character (\(lq#\(rq) and span to the end of the line. If the last character of a line is a backslash (\(lq\\\(rq), the subsequent line is treated as a continuation of the current line (and the backslash is otherwise ignored). . .SS Settings . The .BR send_nsca (8) client recognizes the following variables. They may appear in arbitrary order. The type of each value is denoted after an equals sign in angle brackets. . .TP \fBdelay\fP\ =\ <\fIinteger\fP> . Wait for a random number of seconds between 0 and the specified delay before contacting the server. This might be useful to reduce the server load if many .BR send_nsca (8) clients are invoked simultaneously. The default setting is 0, which tells .BR send_nsca (8) to connect to the server immediately. The specified value will be ignored if .BR send_nsca (8) is called with the .B \-D option. . .TP \fBencryption_method\fP\ =\ <\fIstring\fP> . This setting is ignored. It is accepted for compatibility with .SM NSCA 2.x. . .TP \fBidentity\fP\ =\ <\fIstring\fP> . Send the specified client identity to the server. The client identity is used for authentication and authorization. The same identity may be provided by multiple clients. By default, the local host name will be used. . .TP \fBpassword\fP\ =\ <\fIstring\fP> . Use the specified passphrase for authentication and encryption. The default password is \(lqchange-me\(rq. Change it! . .TP \fBport\fP\ =\ <\fIstring\fP> . Connect to the specified service name or port number on the server instead of using the default port (5668). The specified value will be ignored if .BR send_nsca (8) is called with the .B \-p option. . .TP \fBserver\fP\ =\ <\fIstring\fP> . Connect and talk to the specified server address or host name. The default server is \(lqlocalhost\(rq. The specified value will be ignored if .BR send_nsca (8) is called with the .B \-H option. . .TP \fBtimeout\fP\ =\ <\fIinteger\fP> . Close the connection if the server didn't respond for the specified number of seconds. If the timeout is set to 0, .BR send_nsca (8) won't enforce connection timeouts. The default timeout is 15 seconds. The specified value will be ignored if .BR send_nsca (8) is called with the .B \-o option. . .TP \fBtls_ciphers\fP\ =\ <\fIstring\fP> . Limit the cipher suites offered during the .SM TLS negotiation to the specified list of ciphers. The format of the string is described in the .BR ciphers (1) manual. By default, the ciphers in the list .SM \f(CWPSK-AES256-CBC-SHA:PSK-AES128-CBC-SHA:PSK-3DES-EDE-CBC-SHA:PSK-RC4-SHA\fP will be offered. . .SH EXAMPLES . The .B @sysconfdir@/send_nsca.cfg file might look similar to the following example. . .PP .RS .nf .ft CW . identity = "web-checker" password = "djMKCIcurJJLSQGT5qIhCfqCHQLTcvp9" server = "monitoring.example.com" tls_ciphers = "PSK-AES256-CBC-SHA" delay = 2 port = 5668 timeout = 10 . .ft P .fi .RE . .SH CAVEATS . Please set the permissions appropriately to make sure that only authorized users can access the .B @sysconfdir@/send_nsca.cfg file. . .SH "SEE ALSO" . .BR send_nsca (8), .BR nsca\-ng (8), .BR nsca\-ng.cfg (5), . .PP .I http://www.nagios.org/developerinfo/externalcommands/ . .SH AUTHOR . Holger Weiss . .\" vim:set filetype=nroff textwidth=72: nsca-ng-1.6/man/send_nsca.in000066400000000000000000000152011344421036200157440ustar00rootroot00000000000000.\" Copyright (c) 2013 Holger Weiss .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" 1. Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" 2. Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. . .TH send_nsca 8 "@date@" "Version @version@" "The NSCA\-ng Manual" . .SH NAME . .B send_nsca \- send monitoring commands to NSCA\-ng server . .SH SYNOPSIS . .B send_nsca .RB [ \-CSstv ] .RB [ \-c .IR file ] .RB [ \-D .IR delay ] .RB [ \-d .IR delimiter ] .RB [ \-e .IR separator ] .RB [ \-H .IR server ] .RB [ \-o .IR timeout ] .RB [ \-p .IR port ] . .PP .B send_nsca .BR \-h " | " \-V . .SH DESCRIPTION . The .B send_nsca utility transmits one or more check results or monitoring commands to an .BR nsca\-ng (8) server. The communication with the server is .SM TLS encrypted and authenticated using pre-shared keys (as per .SM RFC 4279). By default, .B send_nsca reads host or service check results from the standard input. Multiple check results must be separated with an .SM ASCII ETB character (octal value: 27). Service check results are expected to be in the following format: . .PP .IR host [tab] service [tab] status [tab] message [newline] . .PP where .I host and .I service are the host name and service description as configured in Nagios, .I status is the numeric return code, and .I message is the output string. Host check results are expected to be in the same format, just without the .I service description: . .PP .IR host [tab] status [tab] message [newline] . .PP Note that multiline .IR message s are supported. . .SH OPTIONS . .TP .B \-C . Instead of accepting host or service check results in the format described above, read \(lqraw\(rq monitoring commands for submission to the Nagios command file from the standard input, one command per line. The commands are expected to be in the format described in the Nagios documentation; except that the leading bracketed timestamp may be omitted, in which case the current timestamp is prepended to the provided command by .BR send_nsca . . .TP .BI \-c\ file . Read the configuration from the specified .I file instead of using the default configuration file .IR @sysconfdir@/send_nsca.cfg . . .TP .BI \-D\ delay . Wait for a random number of seconds between 0 and the specified .I delay before contacting the server. This might be useful to reduce the server load if many .B send_nsca clients are invoked simultaneously. The default setting is 0, which tells .B send_nsca to connect to the server immediately. If this option is specified, the .B delay setting in the .BR send_nsca.cfg (5) file is ignored. . .TP .BI \-d\ delimiter . Use the specified .I delimiter instead of a horizontal tab to separate the fields when parsing host or service check results. The .I delimiter must be a single character, a C-style backslash escape sequence, the octal value of a character with a leading zero, or the hexadecimal value of a character prefixed with \(lq0x\(rq. Any .SM ASCII character other than a backslash, newline, .SM ETB, or .SM NUL is allowed. This option is ignored if the .B \-C option is specified. . .TP .BI \-e\ separator . Use the specified .I separator instead of an .SM ASCII ETB character to separate multiple host or service check results. The .I separator must be a single character, a C-style backslash escape sequence, the octal value of a character with a leading zero, or the hexadecimal value of a character prefixed with \(lq0x\(rq. Any .SM ASCII character is allowed, but note that multiline check result messages cannot be submitted if a newline character is used. This option is ignored if the .B \-C option is specified. . .TP .BI \-H\ server . Connect and talk to the specified .I server address or host name. By default, .B send_nsca attempts to communicate with \(lqlocalhost\(rq. This option takes precedence over the .B server setting in the .BR send_nsca.cfg (5) file. . .TP .B \-h . Print usage information to the standard output and exit. . .TP .BI \-o\ timeout . Close the connection if the server didn't respond for the specified number of seconds. If the .I timeout is set to 0, .B send_nsca won't enforce connection timeouts. The default .I timeout is 15 seconds. This option is provided for compatibility with .SM NSCA 2.x. If it's specified, the .B timeout setting in the .BR send_nsca.cfg (5) file is ignored. . .TP .BI \-p\ port . Connect to the specified service name or .I port number instead of using the default .I port (5668). This option takes precedence over the .B port setting in the .BR send_nsca.cfg (5) file. . .TP .B \-S . Write all messages to the standard error output. This is the default behaviour. . .TP .B \-s . Send all messages (except for usage errors) to the system logger. This option may be combined with the .B \-S option. . .TP .B \-t . This option is ignored. It is accepted for compatibility with .SM NSCA 2.x. . .TP .B \-V . Print version information to the standard output and exit. . .TP .B \-v . Generate a message for each check result or monitoring command sent to the .BR nsca\-ng (8) server. This option can be specified up to three times in order to increase the verbosity. . .SH "EXIT STATUS" . The .B send_nsca utility exits 0 on success, and >0 if an error occurs. . .SH FILES . .TP .I @sysconfdir@/send_nsca.cfg . The .BR send_nsca.cfg (5) configuration file. . .SH "SEE ALSO" . .BR send_nsca.cfg (5), .BR nsca\-ng (8), .BR nsca\-ng.cfg (5) . .PP .I http://www.nagios.org/developerinfo/externalcommands/ . .SH AUTHOR . Holger Weiss . .\" vim:set filetype=nroff textwidth=72: nsca-ng-1.6/perl/000077500000000000000000000000001344421036200136475ustar00rootroot00000000000000nsca-ng-1.6/perl/.gitignore000066400000000000000000000001331344421036200156340ustar00rootroot00000000000000*.sw[pqr] *.o *.tar.gz *.tar.bz2 MYMETA.* Makefile.old Client.c Client.bs pm_to_blib blib/ nsca-ng-1.6/perl/Changes000066400000000000000000000020431344421036200151410ustar00rootroot00000000000000Revision history for Perl extension Net::NSCAng::Client. v1.0.0 2016-09-12 - New: provide :rcodes tag to only import return codes - New: version numbering scheme changed to use version->declare() - Doc fix: properly hyperlink to methods by separating method name and argument template. 0.05 2015-10-06 - Fix: use Devel::CheckLib in the build script to verify that the OpenSSL found is actually usable. 0.04 2015-09-27 - Fix: on systems such as OpnBSD that use LibreSSL without support for RFC4279 PSK authentication, try `libeopenssl' (the original) first. - Test: emit warning on threaded perls - CPAN: add MIN_PERL_VERSION and repository info - CPAN: change archive to bzip2 format 0.03 2015-08-31 - Test suite: fix spurious failures on non-English locales 0.02 2015-08-26 - Doc fix: *_results method documentation had wrong arguments - Doc fix: "timeout" tag for the constructor was missing 0.01 2015-08-25 - original version; created by h2xs 1.23 with options -b 5.10.1 -O -A -n Net::NSCAng::Client vim:set noet ts=8: nsca-ng-1.6/perl/Client.xs000066400000000000000000000123631344421036200154460ustar00rootroot00000000000000// vim:set cindent: #include #include #define PERL_NO_GET_CONTEXT #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include "ppport.h" #include "client.h" #define SV_OR_DIE(var) { if(!SvOK(var)) croak("%s must not be undef", #var); } #define SV_OR_NULL(var) (SvOK(var) ? SvPV_nolen(var) : NULL) #define SVdup_OR_NULL(var) (SvOK(var) ? strdup(SvPV_nolen(var)) : NULL) #define FREE_IF_SET(ptr) { if(ptr) free(ptr); } struct nscang_object { nscang_client_t client; int client_initialized; char *host; char *identity; char *psk; char *ciphers; char *node_name; char *svc_description; int port; int timeout; }; typedef struct nscang_object nscang_object_t; typedef nscang_object_t * Net__NSCAng__Client; static char *strdupnull(const char *s) { return NULL == s ? NULL : strdup(s); } #define DUP_OR_RETURN(attr) { \ if(attr) { \ if(!(o->attr = strdupnull(attr))) return 1; \ } else { \ o->attr = NULL; \ }\ } static int init_object( nscang_object_t *o, char *host, int port, char *identity, char *psk, char *ciphers, char *node_name, char * svc_description, int timeout) { o->timeout = timeout; o->port = port; DUP_OR_RETURN(host); DUP_OR_RETURN(identity); DUP_OR_RETURN(psk); DUP_OR_RETURN(ciphers); DUP_OR_RETURN(node_name); DUP_OR_RETURN(svc_description); return 0; } static void init_client(nscang_object_t *o) { // Initialize the client library if(!nscang_client_init(&o->client, o->host, o->port, o->ciphers, o->identity, o->psk)) { char errstr[1024]; nscang_client_free(&o->client); croak("nscang_client_init: %s", nscang_client_errstr(&o->client, errstr, sizeof(errstr)) ); } o->client_initialized = 1; } static void free_object(nscang_object_t *o) { FREE_IF_SET(o->svc_description); FREE_IF_SET(o->node_name); FREE_IF_SET(o->ciphers); FREE_IF_SET(o->psk); FREE_IF_SET(o->identity); FREE_IF_SET(o->host); } MODULE = Net::NSCAng::Client PACKAGE = Net::NSCAng::Client PROTOTYPES: DISABLE BOOT: SSL_library_init(); SSL_load_error_strings(); Net::NSCAng::Client _new(class, host, port, identity, psk, ciphers, node_name, svc_description, timeout) char * class char * host int port char * identity char * psk SV * ciphers SV * node_name SV * svc_description int timeout CODE: // Alloc new object Newxz(RETVAL, 1, nscang_object_t); if(!RETVAL) croak("no memory for %s", class); // Copy/duplicate values to object attributes if(init_object(RETVAL, host, port, identity, psk, SV_OR_NULL(ciphers), SV_OR_NULL(node_name), SV_OR_NULL(svc_description), timeout) ) { free_object(RETVAL); croak("no memory for object"); } init_client(RETVAL); OUTPUT: RETVAL void DESTROY(self) Net::NSCAng::Client self CODE: if(self) { nscang_client_free(&(self->client)); free_object(self); Safefree(self); } SV * _result(self, is_host_result, node_name, svc_description, return_code, plugin_output) Net::NSCAng::Client self int is_host_result SV * node_name SV * svc_description int return_code char * plugin_output CODE: char *cnode_name = self->node_name; char *csvc_description = self->svc_description; char errstr[1024]; nscang_client_t *client = &self->client; if(!self->client_initialized) init_client(self); if(SvOK(node_name)) cnode_name = SvPV_nolen(node_name); if(is_host_result) { csvc_description = NULL; } else { if(SvOK(svc_description)) csvc_description = SvPV_nolen(svc_description); } if(!(is_host_result || csvc_description)) croak("svc_description missing"); if(!cnode_name) croak("node_name missing"); if(nscang_client_send_push(client, cnode_name, csvc_description, return_code, plugin_output, self->timeout)) XSRETURN_UNDEF; if(client->_errno == NSCANG_ERROR_TIMEOUT) { nscang_client_disconnect(client); if(nscang_client_send_push(client, cnode_name, csvc_description, return_code, plugin_output, self->timeout)) XSRETURN_UNDEF; } // Retrieve the error description nscang_client_errstr(client, errstr, sizeof(errstr)); // Remember to reinitialize the client text time through self->client_initialized = 0; nscang_client_free(&(self->client)); RETVAL = newSVpv(errstr, 0); OUTPUT: RETVAL SV * command(self, command) Net::NSCAng::Client self SV * command CODE: char errstr[1024]; char *ccommand; nscang_client_t *client = &self->client; if(!self->client_initialized) init_client(self); if(SvOK(command)) { ccommand = SvPV_nolen(command); } else { croak("command missing"); } if(nscang_client_send_command(client, ccommand, self->timeout)) XSRETURN_UNDEF; if(client->_errno == NSCANG_ERROR_TIMEOUT) nscang_client_disconnect(client); // Retrieve the error description nscang_client_errstr(client, errstr, sizeof(errstr)); // Remember to reinitialize the client text time through self->client_initialized = 0; nscang_client_free(&(self->client)); croak(errstr); nsca-ng-1.6/perl/MANIFEST000066400000000000000000000002531344421036200150000ustar00rootroot00000000000000Changes Client.xs Makefile.PL MANIFEST ppport.h README t/001_load.t t/Net-NSCAng-Client.t t/manifest.t t/pod.t lib/Net/NSCAng/Client.pm client.c client.h typemap uthash.h nsca-ng-1.6/perl/Makefile.PL000066400000000000000000000045511344421036200156260ustar00rootroot00000000000000use 5.010001; use ExtUtils::MakeMaker; use ExtUtils::PkgConfig; use Devel::CheckLib; my %openssl_info = ExtUtils::PkgConfig->find(qw/ eopenssl openssl /); die "OpenSSL must be v1.0 or higher" unless ExtUtils::PkgConfig->atleast_version('openssl', '1.0'); my $libpath = ExtUtils::PkgConfig->libs_only_L($openssl_info{pkg}); $libpath =~ s/-L//g; # If this is not set, non-default paths such as eopenssl's are not found on OpenBSD $ENV{LD_LIBRARY_PATH} //= ''; $ENV{LD_LIBRARY_PATH} .= ':' if length $ENV{LD_LIBRARY_PATH}; $ENV{LD_LIBRARY_PATH} .= $libpath; check_lib( lib => 'ssl', header => 'openssl/ssl.h', libpath => $libpath, function => ' SSL_CTX *ctx; SSL_library_init(); if(!(ctx = SSL_CTX_new(SSLv23_client_method()))) return 1; SSL_CTX_set_psk_client_callback(ctx, (unsigned int (*)(SSL*,const char*,char*,unsigned int,unsigned char*,unsigned int))NULL); return 0; ', ) or do { print STDERR < 'Net::NSCAng::Client', VERSION_FROM => 'lib/Net/NSCAng/Client.pm', MIN_PERL_VERSION => '5.10.1', PREREQ_PM => {}, CONFIGURE_REQUIRES => { 'ExtUtils::MakeMaker' => 6.52, 'ExtUtils::PkgConfig' => 0, 'Devel::CheckLib' => 0, 'version' => 0.77, }, TEST_REQUIRES => { 'Test::Exception' => 0, 'Test::More' => 0, 'Test::Pod' => 0, 'Test::CheckManifest' => 0, }, ABSTRACT_FROM => 'lib/Net/NSCAng/Client.pm', # retrieve abstract from module AUTHOR => 'Matthias Bethke ', LICENSE => 'perl', LIBS => [ ExtUtils::PkgConfig->libs($openssl_info{pkg}) ], DEFINE => '', INC => '-I.', OBJECT => '$(O_FILES)', META_ADD => { repository => { type => 'git', url => 'git@github.com:mbethke/nsca-ng.git', web => 'https://github.com/mbethke/nsca-ng/tree/perl-module/perl', }, }, dist => { COMPRESS => 'bzip2', SUFFIX => 'bz2', }, clean => { FILES => 'Net-NSCAng-Client-*' }, ); nsca-ng-1.6/perl/Makefile.am000066400000000000000000000030511344421036200157020ustar00rootroot00000000000000## Process this file with automake(1) to produce Makefile.in. ## Copyright (c) 2016 Holger Weiss ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1. Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## ## 2. Redistributions in binary form must reproduce the above copyright notice, ## this list of conditions and the following disclaimer in the documentation ## and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE ## LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ## CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF ## SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ## INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ## CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ## ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ## POSSIBILITY OF SUCH DAMAGE. EXTRA_DIST = Changes Client.xs MANIFEST Makefile.PL client.c client.h ppport.h \ typemap uthash.h lib t nsca-ng-1.6/perl/README000066400000000000000000000012111344421036200145220ustar00rootroot00000000000000Net-NSCAng-Client version 0.01 ============================== This is a Perl interface to Alexander Golovko's NSCA-ng client library. INSTALLATION To install this module type the following: perl Makefile.PL make make test make install DEPENDENCIES None. Testing requires Test::Exception though. COPYRIGHT AND LICENCE Copyright (C) 2015 by Matthias Bethke Portions Copyright (C) by Alexander Golovko This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.20.2 or, at your option, any later version of Perl 5 you may have available. nsca-ng-1.6/perl/README.md000077700000000000000000000000001344421036200160012READMEustar00rootroot00000000000000nsca-ng-1.6/perl/client.c000066400000000000000000000277121344421036200153020ustar00rootroot00000000000000/* * Copyright (c) 2014 Alexander Golovko * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include #include #include #include #include "client.h" #include "uthash.h" static nscang_client_t *nscang_client_instances; unsigned int set_psk(SSL *ssl, const char *hint, char *identity, unsigned int max_identity_length, unsigned char *psk, unsigned int max_psk_length) { nscang_client_t *c = NULL; HASH_FIND_PTR(nscang_client_instances, &ssl, c); if (c != NULL) { strncpy(identity, c->identity, max_identity_length); identity[max_identity_length - 1] = 0x00; strncpy((char *)psk, c->psk, max_psk_length); psk[max_psk_length - 1] = 0x00; return strlen((char *)psk); } identity[0] = 0x00; psk[0] = 0x00; return 0; } int nscang_client_init(nscang_client_t *c, char *host, int port, char *ciphers, char *identity, char *psk) { memset(c, 0x00, sizeof(nscang_client_t)); c->ssl_ctx = SSL_CTX_new(SSLv23_client_method()); if (c->ssl_ctx == NULL) { c->_errno = NSCANG_ERROR_SSL_CTX_CREATE; return 0; } if (ciphers != NULL) { if (SSL_CTX_set_cipher_list(c->ssl_ctx, ciphers) != 1) { c->_errno = NSCANG_ERROR_SSL_CIPHERS; return 0; } } SSL_CTX_set_options(c->ssl_ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3); c->bio = BIO_new(BIO_s_connect()); if (c->bio == NULL) { c->_errno = NSCANG_ERROR_SSL_BIO_CREATE; return 0; } BIO_set_conn_hostname(c->bio, host); BIO_set_conn_int_port(c->bio, &port); BIO_set_nbio(c->bio, 1); c->ssl = SSL_new(c->ssl_ctx); if (c->ssl == NULL) { nscang_client_free(c); c->_errno = NSCANG_ERROR_SSL_CREATE; return 0; } SSL_set_bio(c->ssl, c->bio, c->bio); SSL_set_connect_state(c->ssl); SSL_set_psk_client_callback(c->ssl, set_psk); c->identity = malloc(strlen(identity) + 1); c->psk = malloc(strlen(psk) + 1); if ((c->identity == NULL) || (c->psk == NULL)) { c->_errno = NSCANG_ERROR_MALLOC; return 0; } strcpy(c->identity, identity); strcpy(c->psk, psk); HASH_ADD_PTR(nscang_client_instances, ssl, c); c->state = NSCANG_STATE_NEW; return 1; } void nscang_client_free(nscang_client_t *c) { if (c->state != NSCANG_STATE_NONE) nscang_client_disconnect(c); if (c->ssl != NULL) { HASH_DEL(nscang_client_instances, c); } if (c->ssl != NULL) { SSL_free(c->ssl); c->ssl = NULL; c->bio = NULL; } if (c->ssl_ctx != NULL) { SSL_CTX_free(c->ssl_ctx); c->ssl_ctx = NULL; } if (c->identity != NULL) { free(c->identity); c->identity = NULL; } if (c->psk != NULL) { free(c->psk); c->psk = NULL; } c->state = NSCANG_STATE_NONE; } int nscang_client_write(nscang_client_t *c, void *buf, int len, int timeout) { int rc; time_t endtime; fd_set fdset; struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 100000; endtime = time(NULL) + timeout; while (1) { if ((rc = SSL_write(c->ssl, buf, len)) > 0) return 1; if (!BIO_should_retry(c->bio)) { c->_errno = NSCANG_ERROR_SSL; return 0; } if (time(NULL) > endtime) { c->_errno = NSCANG_ERROR_TIMEOUT; return 0; } FD_ZERO(&fdset); FD_SET(BIO_get_fd(c->bio, NULL), &fdset); select(1, NULL, &fdset, NULL, &tv); } } int nscang_client_response(nscang_client_t *c, int timeout) { int rc; time_t endtime; fd_set fdset; char buf[1024]; int was_read = 0; char *ptr = buf; struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 100000; endtime = time(NULL) + timeout; while (1) { rc = SSL_read(c->ssl, ptr, 1024 - was_read); if (rc > 0) { was_read = was_read + rc; ptr = buf + was_read; if (buf[was_read - 1] == '\n') { if (buf[was_read - 2] == '\r') buf[was_read - 2] = 0x00; else buf[was_read - 1] = 0x00; break; } if (was_read == 1024) { c->_errno = NSCANG_ERROR_TOO_LONG_RESPONSE; return 0; } } else if (!BIO_should_retry(c->bio)) { c->_errno = NSCANG_ERROR_SSL; return 0; } if (time(NULL) > endtime) { c->_errno = NSCANG_ERROR_TIMEOUT; return 0; } FD_ZERO(&fdset); FD_SET(BIO_get_fd(c->bio, NULL), &fdset); select(1, &fdset, NULL, NULL, &tv); } if (strncmp(buf, "MOIN", 4) == 0) { if (strcmp(buf, "MOIN 1") == 0) { return NSCANG_RESP_MOIN; } else { c->_errno = NSCANG_ERROR_BAD_PROTO_VERSION; strncpy(c->errstr, buf + 5, sizeof(c->errstr) - 1); c->errstr[sizeof(c->errstr) - 1] = 0x00; return 0; } } else if (strncmp(buf, "OKAY", 4) == 0) { return NSCANG_RESP_OKAY; } else if (strncmp(buf, "FAIL", 4) == 0) { c->_errno = NSCANG_ERROR_FAIL; strncpy(c->errstr, buf + 5, sizeof(c->errstr) - 1); c->errstr[sizeof(c->errstr) - 1] = 0x00; return 0; } else if (strncmp(buf, "BAIL", 4) == 0) { nscang_client_disconnect(c); c->_errno = NSCANG_ERROR_BAIL; strncpy(c->errstr, buf + 5, sizeof(c->errstr) - 1); c->errstr[sizeof(c->errstr) - 1] = 0x00; return 0; } else { char *msg = "BAIL Unknown response!"; nscang_client_write(c, msg, sizeof(msg), 0); nscang_client_disconnect(c); c->_errno = NSCANG_ERROR_UNKNOWN_RESPONSE; strncpy(c->errstr, buf, sizeof(c->errstr) - 1); c->errstr[sizeof(c->errstr) - 1] = 0x00; return 0; } } void nscang_client_disconnect(nscang_client_t *c) { fd_set fdset; struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 100000; if (c->state == NSCANG_STATE_MOIN) nscang_client_send_quit(c); if ((SSL_shutdown(c->ssl) == -1) && BIO_should_retry(c->bio)) { FD_ZERO(&fdset); FD_SET(BIO_get_fd(c->bio, NULL), &fdset); select(1, NULL, &fdset, NULL, &tv); SSL_shutdown(c->ssl); } SSL_clear(c->ssl); BIO_reset(c->bio); c->state = NSCANG_STATE_NEW; } int nscang_client_send_moin(nscang_client_t *c, int timeout) { char cmd[64]; int len, rc; if (c->state == NSCANG_STATE_MOIN) return 1; if (c->state != NSCANG_STATE_NEW) { c->_errno = NSCANG_ERROR_BAD_STATE; return 0; } srandom(time(NULL)); len = snprintf(cmd, sizeof(cmd), "MOIN 1 %08ld%08ld\r\n", random(), random()); if (!nscang_client_write(c, cmd, len, timeout)) return 0; rc = nscang_client_response(c, timeout); if (!rc) return 0; if (rc != NSCANG_RESP_MOIN) { c->_errno = NSCANG_ERROR_PROTOCOL_MISMATCH; return 0; } c->state = NSCANG_STATE_MOIN; return 1; } /* Check whether a string's prefix matches /\[\d{1,9}\]/ * Returns 1 for match, 0 for no match, -1 for incomplete/bad match */ static int has_timestamp_prefix(const char *s) { char *end; if(*s++ != '[') return 0; if((*s < '0') || (*s > '9')) return -1; // counter strtol's skip-whitespace and sign permissiveness (void)strtol(s, &end, 10); // discard result if(errno) return -1; if(*end == ']') return 1; return -1; } int nscang_client_send_command(nscang_client_t *c, const char *command, int timeout) { const int command_len = strlen(command); char command_buf[1024]; char cmd[32]; int rc, len; switch( has_timestamp_prefix(command) ) { case 0 : // There was no timestamp. Add one. snprintf(command_buf, sizeof(command_buf)-1, "[%u] %s", (unsigned int)time(NULL), command); break; case 1 : // Timestamp found, just copy everything strncpy(command_buf, command, sizeof(command_buf)-1); command_buf[sizeof(command_buf)-1] = '\0'; break; default : // Malformed timestamp c->_errno = NSCANG_ERROR_FAIL; snprintf(c->errstr, sizeof(c->errstr), "invalid time stamp format in command `%s'", command); return 0; } /* make sure command_buf is newline-terminated */ len = strlen(command_buf); if(command_buf[len-1] != '\n') { command_buf[len] = '\n'; len++; command_buf[len] = '\0'; } if (!nscang_client_send_moin(c, timeout)) return 0; snprintf(cmd, sizeof(cmd), "PUSH %d\r\n", len); if (!nscang_client_write(c, cmd, strlen(cmd), timeout)) return 0; rc = nscang_client_response(c, timeout); if (!rc) return 0; if (rc != NSCANG_RESP_OKAY) { c->_errno = NSCANG_ERROR_PROTOCOL_MISMATCH; return 0; } if (!nscang_client_write(c, command_buf, len, timeout)) return 0; rc = nscang_client_response(c, timeout); if (!rc) return 0; if (rc != NSCANG_RESP_OKAY) { c->_errno = NSCANG_ERROR_PROTOCOL_MISMATCH; return 0; } return 1; } int nscang_client_send_push(nscang_client_t *c, char *host, char *service, int status, char *message, int timeout) { char command[1024]; if (service == NULL) snprintf(command, sizeof(command) - 1, "PROCESS_HOST_CHECK_RESULT;%s;%d;%s", host, status, message); else snprintf(command, sizeof(command) - 1, "PROCESS_SERVICE_CHECK_RESULT;%s;%s;%d;%s", host, service, status, message); return nscang_client_send_command(c, command, timeout); } int nscang_client_send_quit(nscang_client_t *c) { if (c->state != NSCANG_STATE_MOIN) { c->_errno = NSCANG_ERROR_BAD_STATE; return 0; } if (!nscang_client_write(c, "QUIT\n", 5, 0)) return 0; return 1; } void nscang_client_ssl_error(char *buf, int buf_size, const char *msg) { strncpy(buf, msg, buf_size); buf_size--; strncat(buf, ":", buf_size); strncat(buf, ERR_reason_error_string(ERR_peek_error()), buf_size); } char * nscang_client_errstr(nscang_client_t *c, char *buf, int buf_size) { switch (c->_errno) { case NSCANG_ERROR_SSL_CTX_CREATE: nscang_client_ssl_error(buf, buf_size, "Can't create SSL context"); break; case NSCANG_ERROR_SSL_CIPHERS: nscang_client_ssl_error(buf, buf_size, "Bad ciphers list"); break; case NSCANG_ERROR_SSL_BIO_CREATE: nscang_client_ssl_error(buf, buf_size, "Can't create BIO socket"); break; case NSCANG_ERROR_SSL_CREATE: nscang_client_ssl_error(buf, buf_size, "Can't create SSL"); break; case NSCANG_ERROR_SSL: nscang_client_ssl_error(buf, buf_size, "SSL error"); break; case NSCANG_ERROR_MALLOC: strncpy(buf, "Can't allocate memory", buf_size); break; case NSCANG_ERROR_TIMEOUT: strncpy(buf, "Timeout was reached", buf_size); break; case NSCANG_ERROR_TOO_LONG_RESPONSE: strncpy(buf, "Protocol mismatch - too long response", buf_size); break; case NSCANG_ERROR_BAD_PROTO_VERSION: snprintf(buf, buf_size, "Protocol mismatch - bad version '%s'", c->errstr); break; case NSCANG_ERROR_PROTOCOL_MISMATCH: strncpy(buf, "Protocol mismatch - unexpected server response", buf_size); break; case NSCANG_ERROR_UNKNOWN_RESPONSE: strncpy(buf, "Protocol mismatch - unknown server response", buf_size); break; case NSCANG_ERROR_BAIL: snprintf(buf, buf_size, "BAIL: %s", c->errstr); break; case NSCANG_ERROR_FAIL: snprintf(buf, buf_size, "FAIL: %s", c->errstr); break; case NSCANG_ERROR_BAD_STATE: snprintf(buf, buf_size, "Operation not permitted in state %d", c->state); break; default: buf[0] = 0x00; } buf[buf_size - 1] = 0x00; return buf; } nsca-ng-1.6/perl/client.h000066400000000000000000000057271344421036200153110ustar00rootroot00000000000000/* * Copyright (c) 2014 Alexander Golovko * All rights reserved. * Portions (c) 2015 Matthias Bethke * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef __NSCANG_CLIENT_H #define __NSCANG_CLIENT_H #include #include #include "uthash.h" typedef enum { NSCANG_STATE_NONE=0, NSCANG_STATE_NEW, NSCANG_STATE_MOIN } nscang_state_t; typedef enum { NSCANG_RESP_MOIN=1, NSCANG_RESP_OKAY } nscang_response_t; typedef enum { NSCANG_ERROR_MALLOC=1, NSCANG_ERROR_TIMEOUT, NSCANG_ERROR_TOO_LONG_RESPONSE, NSCANG_ERROR_BAD_PROTO_VERSION, NSCANG_ERROR_PROTOCOL_MISMATCH, NSCANG_ERROR_UNKNOWN_RESPONSE, NSCANG_ERROR_BAIL, NSCANG_ERROR_FAIL, NSCANG_ERROR_BAD_STATE, NSCANG_ERROR_SSL_CTX_CREATE=101, NSCANG_ERROR_SSL_CIPHERS, NSCANG_ERROR_SSL_BIO_CREATE, NSCANG_ERROR_SSL_CREATE, NSCANG_ERROR_SSL } nscang_error_t; typedef struct { SSL_CTX *ssl_ctx; BIO *bio; SSL *ssl; nscang_state_t state; char *identity; char *psk; nscang_error_t _errno; char errstr[1024]; UT_hash_handle hh; } nscang_client_t; int nscang_client_init(nscang_client_t *c, char *host, int port, char *ciphers, char *identity, char *psk); void nscang_client_free(nscang_client_t *c); void nscang_client_disconnect(nscang_client_t *c); int nscang_client_send_moin(nscang_client_t *c, int timeout); int nscang_client_send_command(nscang_client_t *c, const char *command, int timeout); int nscang_client_send_push(nscang_client_t *c, char *host, char *service, int status, char *message, int timeout); int nscang_client_send_quit(nscang_client_t *c); char *nscang_client_errstr(nscang_client_t *c, char *buf, int buf_size); #endif /* __NSCANG_CLIENT_H */ nsca-ng-1.6/perl/lib/000077500000000000000000000000001344421036200144155ustar00rootroot00000000000000nsca-ng-1.6/perl/lib/Net/000077500000000000000000000000001344421036200151435ustar00rootroot00000000000000nsca-ng-1.6/perl/lib/Net/NSCAng/000077500000000000000000000000001344421036200162145ustar00rootroot00000000000000nsca-ng-1.6/perl/lib/Net/NSCAng/Client.pm000066400000000000000000000151551344421036200177770ustar00rootroot00000000000000package Net::NSCAng::Client; use 5.010001; use strict; use warnings; use Carp; require Exporter; our @ISA = qw(Exporter); our %EXPORT_TAGS = ( all => [ qw/ OK WARNING CRITICAL UNKNOWN DEPENDENT / ], rcodes => [ qw/ OK WARNING CRITICAL UNKNOWN DEPENDENT / ], ); our @EXPORT_OK = ( @{ $EXPORT_TAGS{all} } ); use version 0.77; our $VERSION = qv('v2.0.0'); use constant OK => 0; use constant WARNING => 1; use constant CRITICAL => 2; use constant UNKNOWN => 3; use constant DEPENDENT => 4; require XSLoader; XSLoader::load('Net::NSCAng::Client', $VERSION); =head1 NAME Net::NSCAng::Client - Submit host and service monitoring results using the NSCA-ng protocol =head1 SYNOPSIS use Net::NSCAng::Client ':rcodes'; my $c = Net::NSCAng::Client->new('icinga.mydomain.org', 'myid', 's3cr3t', node_name => 'server_name', ); $c->svc_result(WARNING, 'BogusService is bogus!', { svc_description => 'bogus' }); =head1 DESCRIPTION Net::NSCAng::Client provides a means of submitting host or service check results to an L server, and to remote-control your monitoring system using L. It is derived from the Python module written by Alexander Golovko but with a more perlish interface and additional functionality for sending arbitrary external commands. =head2 EXPORT Nothing by default. The standard Nagios return codes C, C, C, C and C are available. If you don't use something like L that exports the same values, use C<:rcodes> as above to import them. The C<:all> tag is currently synonymous with C<:rcodes> but might export more things in te future. =head1 METHODS =head2 new $o = new($host, $identity, $psk, %tags); $o = new("icinga.local", "ID", "s3cr3t", node_name => hostname()); The constructor takes three mandatory positional arguments and a number of optional ones that may be passed as hash-style arguments inline or as a hashref. The mandatory ones: =over 4 =item C<$host>: The host name or IP address of the NSCA-ng server =item C<$identity>: An arbitrary identity string that is used by the server to find the corrent PSK. You can think of this as the "user name" part of a regular login. =item C<$psk>: A pre-shared key configured on the server for C<$identity>. =back The following tags are optional: =over 4 =item C: the TCP port the NSCA-ng server runs on. Defaults to 5668. =item C: A list of ciphers for OpenSSL to use. See ciphers(1) for details and don't mess with this unless you know what you're doing. The default is fine. =item C: The name of the local host as configured in your monitoring system. This is almost always the host name. You may pass this as an argument to any of the result methods, but considering that a single host or service check hardly ever submits results for more than one host, it makes sense to specify this at construction time and not to worry about it later. =item C: The service description as configured in your monitoring system. Same rationale as C above. =item C: The timeout in seconds to wait for server responses and connection setup. Default is 10. =back The constructor dies with an error message if anything should go wrong, so use C, L or the like. =cut sub new { my ($class, $host, $identity, $psk) = splice(@_, 0, 4); my %args = @_%2 ? %{$_[0]} : @_; $class->_new($host, $args{port} // 5668, $identity, $psk, @args{qw/ ciphers node_name svc_description /}, $args{timeout} // 10, ); } =head2 svc_result svc_result($return_code, $plugin_output, %tags); svc_result(WARNING, "Warning: foo is purple!"); Submit a service check result. C<$return_code> is a Nagios-style plugin return code between 0 and 4, and C<$plugin_output> is a human-readable description. The optional arguments may be passed hash-style inline or as a hashref just like for the constructor. The supported keys are C and C, see L for their use. If specified here, the values override anything that may have been set in the constructor. If you haven't set them in the constructor, you MUST set them here though! Errors are signaled by dying with an error message. =cut sub svc_result { my ($self, $return_code, $plugin_output) = splice(@_, 0, 3); my %args = @_%2 ? %{$_[0]} : @_; my $err = $self->_result(0, @args{qw/ node_name svc_description /}, $return_code, $plugin_output ); $err and croak("svc_result: $err"); } =head2 host_result host_result($return_code, $plugin_output, %tags); host_result(OK, "Everything is peachy"); Submit a host check result. This is the same as L, the only exception being that the C argument obviously makes no sense for a host check and is thus not supported. If an C should have been set in the constructor, it is ignored for this call. =cut sub host_result { my ($self, $return_code, $plugin_output) = splice(@_, 0, 3); my %args = @_%2 ? %{$_[0]} : @_; my $err = $self->_result(1, $args{node_name}, '', $return_code, $plugin_output); $err and croak("host_result: $err"); } =head2 command command($cmd); command( sprintf("SCHEDULE_HOST_DOWNTIME;myserver;%d;%d;1;0;0;root;Hooray for NSCA-ng!", 0+time, 3600+time ) ); Submit an arbitrary command to your monitoring host. Commands have to be prefixed by a timestamp in seconds since the Unix epoch enclosed in angle brackets to be accepted by the server; if you leave this off, the method will add it for you. Refer to the Nagios/Icinga documentiation for available commands and the format to follow for each command. =cut 1; __END__ =head1 BUGS This module is not thread safe! Due do a workaround for the godawful OpenSSL API, static data has to be used, and this I cause problems with threads. The original Python library uses pthreads to get around that but due to Perl's different threading model this would probably not work. Using the C macros is a possibility but frankly I'm too lazy to try just for supporting Perl threads that don't work well in the first place. =head1 SEE ALSO L =head1 AUTHOR Matthias Bethke, Ematthias@towiski.deE =head1 COPYRIGHT AND LICENSE Copyright (C) 2015 by Matthias Bethke. Portions Copyright (C) by Alexander Golovko . This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.20.2 or, at your option, any later version of Perl 5 you may have available. =cut nsca-ng-1.6/perl/ppport.h000066400000000000000000005756161344421036200153700ustar00rootroot00000000000000#if 0 <<'SKIP'; #endif /* ---------------------------------------------------------------------- ppport.h -- Perl/Pollution/Portability Version 3.31 Automatically created by Devel::PPPort running under perl 5.020002. Do NOT edit this file directly! -- Edit PPPort_pm.PL and the includes in parts/inc/ instead. Use 'perldoc ppport.h' to view the documentation below. ---------------------------------------------------------------------- SKIP =pod =head1 NAME ppport.h - Perl/Pollution/Portability version 3.31 =head1 SYNOPSIS perl ppport.h [options] [source files] Searches current directory for files if no [source files] are given --help show short help --version show version --patch=file write one patch file with changes --copy=suffix write changed copies with suffix --diff=program use diff program and options --compat-version=version provide compatibility with Perl version --cplusplus accept C++ comments --quiet don't output anything except fatal errors --nodiag don't show diagnostics --nohints don't show hints --nochanges don't suggest changes --nofilter don't filter input files --strip strip all script and doc functionality from ppport.h --list-provided list provided API --list-unsupported list unsupported API --api-info=name show Perl API portability information =head1 COMPATIBILITY This version of F is designed to support operation with Perl installations back to 5.003, and has been tested up to 5.20. =head1 OPTIONS =head2 --help Display a brief usage summary. =head2 --version Display the version of F. =head2 --patch=I If this option is given, a single patch file will be created if any changes are suggested. This requires a working diff program to be installed on your system. =head2 --copy=I If this option is given, a copy of each file will be saved with the given suffix that contains the suggested changes. This does not require any external programs. Note that this does not automagically add a dot between the original filename and the suffix. If you want the dot, you have to include it in the option argument. If neither C<--patch> or C<--copy> are given, the default is to simply print the diffs for each file. This requires either C or a C program to be installed. =head2 --diff=I Manually set the diff program and options to use. The default is to use C, when installed, and output unified context diffs. =head2 --compat-version=I Tell F to check for compatibility with the given Perl version. The default is to check for compatibility with Perl version 5.003. You can use this option to reduce the output of F if you intend to be backward compatible only down to a certain Perl version. =head2 --cplusplus Usually, F will detect C++ style comments and replace them with C style comments for portability reasons. Using this option instructs F to leave C++ comments untouched. =head2 --quiet Be quiet. Don't print anything except fatal errors. =head2 --nodiag Don't output any diagnostic messages. Only portability alerts will be printed. =head2 --nohints Don't output any hints. Hints often contain useful portability notes. Warnings will still be displayed. =head2 --nochanges Don't suggest any changes. Only give diagnostic output and hints unless these are also deactivated. =head2 --nofilter Don't filter the list of input files. By default, files not looking like source code (i.e. not *.xs, *.c, *.cc, *.cpp or *.h) are skipped. =head2 --strip Strip all script and documentation functionality from F. This reduces the size of F dramatically and may be useful if you want to include F in smaller modules without increasing their distribution size too much. The stripped F will have a C<--unstrip> option that allows you to undo the stripping, but only if an appropriate C module is installed. =head2 --list-provided Lists the API elements for which compatibility is provided by F. Also lists if it must be explicitly requested, if it has dependencies, and if there are hints or warnings for it. =head2 --list-unsupported Lists the API elements that are known not to be supported by F and below which version of Perl they probably won't be available or work. =head2 --api-info=I Show portability information for API elements matching I. If I is surrounded by slashes, it is interpreted as a regular expression. =head1 DESCRIPTION In order for a Perl extension (XS) module to be as portable as possible across differing versions of Perl itself, certain steps need to be taken. =over 4 =item * Including this header is the first major one. This alone will give you access to a large part of the Perl API that hasn't been available in earlier Perl releases. Use perl ppport.h --list-provided to see which API elements are provided by ppport.h. =item * You should avoid using deprecated parts of the API. For example, using global Perl variables without the C prefix is deprecated. Also, some API functions used to have a C prefix. Using this form is also deprecated. You can safely use the supported API, as F will provide wrappers for older Perl versions. =item * If you use one of a few functions or variables that were not present in earlier versions of Perl, and that can't be provided using a macro, you have to explicitly request support for these functions by adding one or more C<#define>s in your source code before the inclusion of F. These functions or variables will be marked C in the list shown by C<--list-provided>. Depending on whether you module has a single or multiple files that use such functions or variables, you want either C or global variants. For a C function or variable (used only in a single source file), use: #define NEED_function #define NEED_variable For a global function or variable (used in multiple source files), use: #define NEED_function_GLOBAL #define NEED_variable_GLOBAL Note that you mustn't have more than one global request for the same function or variable in your project. Function / Variable Static Request Global Request ----------------------------------------------------------------------------------------- PL_parser NEED_PL_parser NEED_PL_parser_GLOBAL PL_signals NEED_PL_signals NEED_PL_signals_GLOBAL caller_cx() NEED_caller_cx NEED_caller_cx_GLOBAL eval_pv() NEED_eval_pv NEED_eval_pv_GLOBAL grok_bin() NEED_grok_bin NEED_grok_bin_GLOBAL grok_hex() NEED_grok_hex NEED_grok_hex_GLOBAL grok_number() NEED_grok_number NEED_grok_number_GLOBAL grok_numeric_radix() NEED_grok_numeric_radix NEED_grok_numeric_radix_GLOBAL grok_oct() NEED_grok_oct NEED_grok_oct_GLOBAL load_module() NEED_load_module NEED_load_module_GLOBAL mg_findext() NEED_mg_findext NEED_mg_findext_GLOBAL my_snprintf() NEED_my_snprintf NEED_my_snprintf_GLOBAL my_sprintf() NEED_my_sprintf NEED_my_sprintf_GLOBAL my_strlcat() NEED_my_strlcat NEED_my_strlcat_GLOBAL my_strlcpy() NEED_my_strlcpy NEED_my_strlcpy_GLOBAL newCONSTSUB() NEED_newCONSTSUB NEED_newCONSTSUB_GLOBAL newRV_noinc() NEED_newRV_noinc NEED_newRV_noinc_GLOBAL newSV_type() NEED_newSV_type NEED_newSV_type_GLOBAL newSVpvn_flags() NEED_newSVpvn_flags NEED_newSVpvn_flags_GLOBAL newSVpvn_share() NEED_newSVpvn_share NEED_newSVpvn_share_GLOBAL pv_display() NEED_pv_display NEED_pv_display_GLOBAL pv_escape() NEED_pv_escape NEED_pv_escape_GLOBAL pv_pretty() NEED_pv_pretty NEED_pv_pretty_GLOBAL sv_2pv_flags() NEED_sv_2pv_flags NEED_sv_2pv_flags_GLOBAL sv_2pvbyte() NEED_sv_2pvbyte NEED_sv_2pvbyte_GLOBAL sv_catpvf_mg() NEED_sv_catpvf_mg NEED_sv_catpvf_mg_GLOBAL sv_catpvf_mg_nocontext() NEED_sv_catpvf_mg_nocontext NEED_sv_catpvf_mg_nocontext_GLOBAL sv_pvn_force_flags() NEED_sv_pvn_force_flags NEED_sv_pvn_force_flags_GLOBAL sv_setpvf_mg() NEED_sv_setpvf_mg NEED_sv_setpvf_mg_GLOBAL sv_setpvf_mg_nocontext() NEED_sv_setpvf_mg_nocontext NEED_sv_setpvf_mg_nocontext_GLOBAL sv_unmagicext() NEED_sv_unmagicext NEED_sv_unmagicext_GLOBAL vload_module() NEED_vload_module NEED_vload_module_GLOBAL vnewSVpvf() NEED_vnewSVpvf NEED_vnewSVpvf_GLOBAL warner() NEED_warner NEED_warner_GLOBAL To avoid namespace conflicts, you can change the namespace of the explicitly exported functions / variables using the C macro. Just C<#define> the macro before including C: #define DPPP_NAMESPACE MyOwnNamespace_ #include "ppport.h" The default namespace is C. =back The good thing is that most of the above can be checked by running F on your source code. See the next section for details. =head1 EXAMPLES To verify whether F is needed for your module, whether you should make any changes to your code, and whether any special defines should be used, F can be run as a Perl script to check your source code. Simply say: perl ppport.h The result will usually be a list of patches suggesting changes that should at least be acceptable, if not necessarily the most efficient solution, or a fix for all possible problems. If you know that your XS module uses features only available in newer Perl releases, if you're aware that it uses C++ comments, and if you want all suggestions as a single patch file, you could use something like this: perl ppport.h --compat-version=5.6.0 --cplusplus --patch=test.diff If you only want your code to be scanned without any suggestions for changes, use: perl ppport.h --nochanges You can specify a different C program or options, using the C<--diff> option: perl ppport.h --diff='diff -C 10' This would output context diffs with 10 lines of context. If you want to create patched copies of your files instead, use: perl ppport.h --copy=.new To display portability information for the C function, use: perl ppport.h --api-info=newSVpvn Since the argument to C<--api-info> can be a regular expression, you can use perl ppport.h --api-info=/_nomg$/ to display portability information for all C<_nomg> functions or perl ppport.h --api-info=/./ to display information for all known API elements. =head1 BUGS If this version of F is causing failure during the compilation of this module, please check if newer versions of either this module or C are available on CPAN before sending a bug report. If F was generated using the latest version of C and is causing failure of this module, please file a bug report here: L Please include the following information: =over 4 =item 1. The complete output from running "perl -V" =item 2. This file. =item 3. The name and version of the module you were trying to build. =item 4. A full log of the build that failed. =item 5. Any other information that you think could be relevant. =back For the latest version of this code, please get the C module from CPAN. =head1 COPYRIGHT Version 3.x, Copyright (c) 2004-2013, Marcus Holland-Moritz. Version 2.x, Copyright (C) 2001, Paul Marquess. Version 1.x, Copyright (C) 1999, Kenneth Albanowski. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =head1 SEE ALSO See L. =cut use strict; # Disable broken TRIE-optimization BEGIN { eval '${^RE_TRIE_MAXBUF} = -1' if $] >= 5.009004 && $] <= 5.009005 } my $VERSION = 3.31; my %opt = ( quiet => 0, diag => 1, hints => 1, changes => 1, cplusplus => 0, filter => 1, strip => 0, version => 0, ); my($ppport) = $0 =~ /([\w.]+)$/; my $LF = '(?:\r\n|[\r\n])'; # line feed my $HS = "[ \t]"; # horizontal whitespace # Never use C comments in this file! my $ccs = '/'.'*'; my $cce = '*'.'/'; my $rccs = quotemeta $ccs; my $rcce = quotemeta $cce; eval { require Getopt::Long; Getopt::Long::GetOptions(\%opt, qw( help quiet diag! filter! hints! changes! cplusplus strip version patch=s copy=s diff=s compat-version=s list-provided list-unsupported api-info=s )) or usage(); }; if ($@ and grep /^-/, @ARGV) { usage() if "@ARGV" =~ /^--?h(?:elp)?$/; die "Getopt::Long not found. Please don't use any options.\n"; } if ($opt{version}) { print "This is $0 $VERSION.\n"; exit 0; } usage() if $opt{help}; strip() if $opt{strip}; if (exists $opt{'compat-version'}) { my($r,$v,$s) = eval { parse_version($opt{'compat-version'}) }; if ($@) { die "Invalid version number format: '$opt{'compat-version'}'\n"; } die "Only Perl 5 is supported\n" if $r != 5; die "Invalid version number: $opt{'compat-version'}\n" if $v >= 1000 || $s >= 1000; $opt{'compat-version'} = sprintf "%d.%03d%03d", $r, $v, $s; } else { $opt{'compat-version'} = 5; } my %API = map { /^(\w+)\|([^|]*)\|([^|]*)\|(\w*)$/ ? ( $1 => { ($2 ? ( base => $2 ) : ()), ($3 ? ( todo => $3 ) : ()), (index($4, 'v') >= 0 ? ( varargs => 1 ) : ()), (index($4, 'p') >= 0 ? ( provided => 1 ) : ()), (index($4, 'n') >= 0 ? ( nothxarg => 1 ) : ()), } ) : die "invalid spec: $_" } qw( ASCII_TO_NEED||5.007001|n AvFILLp|5.004050||p AvFILL||| BhkDISABLE||5.021008| BhkENABLE||5.021008| BhkENTRY_set||5.021008| BhkENTRY||| BhkFLAGS||| CALL_BLOCK_HOOKS||| CLASS|||n CPERLscope|5.005000||p CX_CURPAD_SAVE||| CX_CURPAD_SV||| CopFILEAV|5.006000||p CopFILEGV_set|5.006000||p CopFILEGV|5.006000||p CopFILESV|5.006000||p CopFILE_set|5.006000||p CopFILE|5.006000||p CopSTASHPV_set|5.006000||p CopSTASHPV|5.006000||p CopSTASH_eq|5.006000||p CopSTASH_set|5.006000||p CopSTASH|5.006000||p CopyD|5.009002|5.004050|p Copy||| CvPADLIST||5.008001| CvSTASH||| CvWEAKOUTSIDE||| DEFSV_set|5.010001||p DEFSV|5.004050||p END_EXTERN_C|5.005000||p ENTER||| ERRSV|5.004050||p EXTEND||| EXTERN_C|5.005000||p F0convert|||n FREETMPS||| GIMME_V||5.004000|n GIMME|||n GROK_NUMERIC_RADIX|5.007002||p G_ARRAY||| G_DISCARD||| G_EVAL||| G_METHOD|5.006001||p G_NOARGS||| G_SCALAR||| G_VOID||5.004000| GetVars||| GvAV||| GvCV||| GvHV||| GvSVn|5.009003||p GvSV||| Gv_AMupdate||5.011000| HEf_SVKEY|5.003070||p HeHASH||5.003070| HeKEY||5.003070| HeKLEN||5.003070| HePV||5.004000| HeSVKEY_force||5.003070| HeSVKEY_set||5.004000| HeSVKEY||5.003070| HeUTF8|5.010001|5.008000|p HeVAL||5.003070| HvENAMELEN||5.015004| HvENAMEUTF8||5.015004| HvENAME||5.013007| HvNAMELEN_get|5.009003||p HvNAMELEN||5.015004| HvNAMEUTF8||5.015004| HvNAME_get|5.009003||p HvNAME||| INT2PTR|5.006000||p IN_LOCALE_COMPILETIME|5.007002||p IN_LOCALE_RUNTIME|5.007002||p IN_LOCALE|5.007002||p IN_PERL_COMPILETIME|5.008001||p IS_NUMBER_GREATER_THAN_UV_MAX|5.007002||p IS_NUMBER_INFINITY|5.007002||p IS_NUMBER_IN_UV|5.007002||p IS_NUMBER_NAN|5.007003||p IS_NUMBER_NEG|5.007002||p IS_NUMBER_NOT_INT|5.007002||p IVSIZE|5.006000||p IVTYPE|5.006000||p IVdf|5.006000||p LEAVE||| LINKLIST||5.013006| LVRET||| MARK||| MULTICALL||5.021008| MUTABLE_PTR|5.010001||p MUTABLE_SV|5.010001||p MY_CXT_CLONE|5.009002||p MY_CXT_INIT|5.007003||p MY_CXT|5.007003||p MoveD|5.009002|5.004050|p Move||| NATIVE_TO_NEED||5.007001|n NOOP|5.005000||p NUM2PTR|5.006000||p NVTYPE|5.006000||p NVef|5.006001||p NVff|5.006001||p NVgf|5.006001||p Newxc|5.009003||p Newxz|5.009003||p Newx|5.009003||p Nullav||| Nullch||| Nullcv||| Nullhv||| Nullsv||| OP_CLASS||5.013007| OP_DESC||5.007003| OP_NAME||5.007003| OP_TYPE_IS_OR_WAS||5.019010| OP_TYPE_IS||5.019007| ORIGMARK||| OpHAS_SIBLING||5.021007| OpSIBLING_set||5.021007| OpSIBLING||5.021007| PAD_BASE_SV||| PAD_CLONE_VARS||| PAD_COMPNAME_FLAGS||| PAD_COMPNAME_GEN_set||| PAD_COMPNAME_GEN||| PAD_COMPNAME_OURSTASH||| PAD_COMPNAME_PV||| PAD_COMPNAME_TYPE||| PAD_RESTORE_LOCAL||| PAD_SAVE_LOCAL||| PAD_SAVE_SETNULLPAD||| PAD_SETSV||| PAD_SET_CUR_NOSAVE||| PAD_SET_CUR||| PAD_SVl||| PAD_SV||| PERLIO_FUNCS_CAST|5.009003||p PERLIO_FUNCS_DECL|5.009003||p PERL_ABS|5.008001||p PERL_BCDVERSION|5.021008||p PERL_GCC_BRACE_GROUPS_FORBIDDEN|5.008001||p PERL_HASH|5.003070||p PERL_INT_MAX|5.003070||p PERL_INT_MIN|5.003070||p PERL_LONG_MAX|5.003070||p PERL_LONG_MIN|5.003070||p PERL_MAGIC_arylen|5.007002||p PERL_MAGIC_backref|5.007002||p PERL_MAGIC_bm|5.007002||p PERL_MAGIC_collxfrm|5.007002||p PERL_MAGIC_dbfile|5.007002||p PERL_MAGIC_dbline|5.007002||p PERL_MAGIC_defelem|5.007002||p PERL_MAGIC_envelem|5.007002||p PERL_MAGIC_env|5.007002||p PERL_MAGIC_ext|5.007002||p PERL_MAGIC_fm|5.007002||p PERL_MAGIC_glob|5.021008||p PERL_MAGIC_isaelem|5.007002||p PERL_MAGIC_isa|5.007002||p PERL_MAGIC_mutex|5.021008||p PERL_MAGIC_nkeys|5.007002||p PERL_MAGIC_overload_elem|5.021008||p PERL_MAGIC_overload_table|5.007002||p PERL_MAGIC_overload|5.021008||p PERL_MAGIC_pos|5.007002||p PERL_MAGIC_qr|5.007002||p PERL_MAGIC_regdata|5.007002||p PERL_MAGIC_regdatum|5.007002||p PERL_MAGIC_regex_global|5.007002||p PERL_MAGIC_shared_scalar|5.007003||p PERL_MAGIC_shared|5.007003||p PERL_MAGIC_sigelem|5.007002||p PERL_MAGIC_sig|5.007002||p PERL_MAGIC_substr|5.007002||p PERL_MAGIC_sv|5.007002||p PERL_MAGIC_taint|5.007002||p PERL_MAGIC_tiedelem|5.007002||p PERL_MAGIC_tiedscalar|5.007002||p PERL_MAGIC_tied|5.007002||p PERL_MAGIC_utf8|5.008001||p PERL_MAGIC_uvar_elem|5.007003||p PERL_MAGIC_uvar|5.007002||p PERL_MAGIC_vec|5.007002||p PERL_MAGIC_vstring|5.008001||p PERL_PV_ESCAPE_ALL|5.009004||p PERL_PV_ESCAPE_FIRSTCHAR|5.009004||p PERL_PV_ESCAPE_NOBACKSLASH|5.009004||p PERL_PV_ESCAPE_NOCLEAR|5.009004||p PERL_PV_ESCAPE_QUOTE|5.009004||p PERL_PV_ESCAPE_RE|5.009005||p PERL_PV_ESCAPE_UNI_DETECT|5.009004||p PERL_PV_ESCAPE_UNI|5.009004||p PERL_PV_PRETTY_DUMP|5.009004||p PERL_PV_PRETTY_ELLIPSES|5.010000||p PERL_PV_PRETTY_LTGT|5.009004||p PERL_PV_PRETTY_NOCLEAR|5.010000||p PERL_PV_PRETTY_QUOTE|5.009004||p PERL_PV_PRETTY_REGPROP|5.009004||p PERL_QUAD_MAX|5.003070||p PERL_QUAD_MIN|5.003070||p PERL_REVISION|5.006000||p PERL_SCAN_ALLOW_UNDERSCORES|5.007003||p PERL_SCAN_DISALLOW_PREFIX|5.007003||p PERL_SCAN_GREATER_THAN_UV_MAX|5.007003||p PERL_SCAN_SILENT_ILLDIGIT|5.008001||p PERL_SHORT_MAX|5.003070||p PERL_SHORT_MIN|5.003070||p PERL_SIGNALS_UNSAFE_FLAG|5.008001||p PERL_SUBVERSION|5.006000||p PERL_SYS_INIT3||5.006000| PERL_SYS_INIT||| PERL_SYS_TERM||5.021008| PERL_UCHAR_MAX|5.003070||p PERL_UCHAR_MIN|5.003070||p PERL_UINT_MAX|5.003070||p PERL_UINT_MIN|5.003070||p PERL_ULONG_MAX|5.003070||p PERL_ULONG_MIN|5.003070||p PERL_UNUSED_ARG|5.009003||p PERL_UNUSED_CONTEXT|5.009004||p PERL_UNUSED_DECL|5.007002||p PERL_UNUSED_VAR|5.007002||p PERL_UQUAD_MAX|5.003070||p PERL_UQUAD_MIN|5.003070||p PERL_USE_GCC_BRACE_GROUPS|5.009004||p PERL_USHORT_MAX|5.003070||p PERL_USHORT_MIN|5.003070||p PERL_VERSION|5.006000||p PL_DBsignal|5.005000||p PL_DBsingle|||pn PL_DBsub|||pn PL_DBtrace|||pn PL_Sv|5.005000||p PL_bufend|5.021008||p PL_bufptr|5.021008||p PL_check||5.006000| PL_compiling|5.004050||p PL_comppad_name||5.017004| PL_comppad||5.008001| PL_copline|5.021008||p PL_curcop|5.004050||p PL_curpad||5.005000| PL_curstash|5.004050||p PL_debstash|5.004050||p PL_defgv|5.004050||p PL_diehook|5.004050||p PL_dirty|5.004050||p PL_dowarn|||pn PL_errgv|5.004050||p PL_error_count|5.021008||p PL_expect|5.021008||p PL_hexdigit|5.005000||p PL_hints|5.005000||p PL_in_my_stash|5.021008||p PL_in_my|5.021008||p PL_keyword_plugin||5.011002| PL_last_in_gv|||n PL_laststatval|5.005000||p PL_lex_state|5.021008||p PL_lex_stuff|5.021008||p PL_linestr|5.021008||p PL_modglobal||5.005000|n PL_na|5.004050||pn PL_no_modify|5.006000||p PL_ofsgv|||n PL_opfreehook||5.011000|n PL_parser|5.009005||p PL_peepp||5.007003|n PL_perl_destruct_level|5.004050||p PL_perldb|5.004050||p PL_ppaddr|5.006000||p PL_rpeepp||5.013005|n PL_rsfp_filters|5.021008||p PL_rsfp|5.021008||p PL_rs|||n PL_signals|5.008001||p PL_stack_base|5.004050||p PL_stack_sp|5.004050||p PL_statcache|5.005000||p PL_stdingv|5.004050||p PL_sv_arenaroot|5.004050||p PL_sv_no|5.004050||pn PL_sv_undef|5.004050||pn PL_sv_yes|5.004050||pn PL_tainted|5.004050||p PL_tainting|5.004050||p PL_tokenbuf|5.021008||p POP_MULTICALL||5.021008| POPi|||n POPl|||n POPn|||n POPpbytex||5.007001|n POPpx||5.005030|n POPp|||n POPs|||n PTR2IV|5.006000||p PTR2NV|5.006000||p PTR2UV|5.006000||p PTR2nat|5.009003||p PTR2ul|5.007001||p PTRV|5.006000||p PUSHMARK||| PUSH_MULTICALL||5.021008| PUSHi||| PUSHmortal|5.009002||p PUSHn||| PUSHp||| PUSHs||| PUSHu|5.004000||p PUTBACK||| PadARRAY||5.021008| PadMAX||5.021008| PadlistARRAY||5.021008| PadlistMAX||5.021008| PadlistNAMESARRAY||5.021008| PadlistNAMESMAX||5.021008| PadlistNAMES||5.021008| PadlistREFCNT||5.017004| PadnameIsOUR||| PadnameIsSTATE||| PadnameLEN||5.021008| PadnameOURSTASH||| PadnameOUTER||| PadnamePV||5.021008| PadnameREFCNT_dec||5.021008| PadnameREFCNT||5.021008| PadnameSV||5.021008| PadnameTYPE||| PadnameUTF8||5.021007| PadnamelistARRAY||5.021008| PadnamelistMAX||5.021008| PadnamelistREFCNT_dec||5.021008| PadnamelistREFCNT||5.021008| PerlIO_clearerr||5.007003| PerlIO_close||5.007003| PerlIO_context_layers||5.009004| PerlIO_eof||5.007003| PerlIO_error||5.007003| PerlIO_fileno||5.007003| PerlIO_fill||5.007003| PerlIO_flush||5.007003| PerlIO_get_base||5.007003| PerlIO_get_bufsiz||5.007003| PerlIO_get_cnt||5.007003| PerlIO_get_ptr||5.007003| PerlIO_read||5.007003| PerlIO_restore_errno||| PerlIO_save_errno||| PerlIO_seek||5.007003| PerlIO_set_cnt||5.007003| PerlIO_set_ptrcnt||5.007003| PerlIO_setlinebuf||5.007003| PerlIO_stderr||5.007003| PerlIO_stdin||5.007003| PerlIO_stdout||5.007003| PerlIO_tell||5.007003| PerlIO_unread||5.007003| PerlIO_write||5.007003| Perl_signbit||5.009005|n PoisonFree|5.009004||p PoisonNew|5.009004||p PoisonWith|5.009004||p Poison|5.008000||p READ_XDIGIT||5.017006| RETVAL|||n Renewc||| Renew||| SAVECLEARSV||| SAVECOMPPAD||| SAVEPADSV||| SAVETMPS||| SAVE_DEFSV|5.004050||p SPAGAIN||| SP||| START_EXTERN_C|5.005000||p START_MY_CXT|5.007003||p STMT_END|||p STMT_START|||p STR_WITH_LEN|5.009003||p ST||| SV_CONST_RETURN|5.009003||p SV_COW_DROP_PV|5.008001||p SV_COW_SHARED_HASH_KEYS|5.009005||p SV_GMAGIC|5.007002||p SV_HAS_TRAILING_NUL|5.009004||p SV_IMMEDIATE_UNREF|5.007001||p SV_MUTABLE_RETURN|5.009003||p SV_NOSTEAL|5.009002||p SV_SMAGIC|5.009003||p SV_UTF8_NO_ENCODING|5.008001||p SVfARG|5.009005||p SVf_UTF8|5.006000||p SVf|5.006000||p SVt_INVLIST||5.019002| SVt_IV||| SVt_NULL||| SVt_NV||| SVt_PVAV||| SVt_PVCV||| SVt_PVFM||| SVt_PVGV||| SVt_PVHV||| SVt_PVIO||| SVt_PVIV||| SVt_PVLV||| SVt_PVMG||| SVt_PVNV||| SVt_PV||| SVt_REGEXP||5.011000| Safefree||| Slab_Alloc||| Slab_Free||| Slab_to_ro||| Slab_to_rw||| StructCopy||| SvCUR_set||| SvCUR||| SvEND||| SvGAMAGIC||5.006001| SvGETMAGIC|5.004050||p SvGROW||| SvIOK_UV||5.006000| SvIOK_notUV||5.006000| SvIOK_off||| SvIOK_only_UV||5.006000| SvIOK_only||| SvIOK_on||| SvIOKp||| SvIOK||| SvIVX||| SvIV_nomg|5.009001||p SvIV_set||| SvIVx||| SvIV||| SvIsCOW_shared_hash||5.008003| SvIsCOW||5.008003| SvLEN_set||| SvLEN||| SvLOCK||5.007003| SvMAGIC_set|5.009003||p SvNIOK_off||| SvNIOKp||| SvNIOK||| SvNOK_off||| SvNOK_only||| SvNOK_on||| SvNOKp||| SvNOK||| SvNVX||| SvNV_nomg||5.013002| SvNV_set||| SvNVx||| SvNV||| SvOK||| SvOOK_offset||5.011000| SvOOK||| SvPOK_off||| SvPOK_only_UTF8||5.006000| SvPOK_only||| SvPOK_on||| SvPOKp||| SvPOK||| SvPVX_const|5.009003||p SvPVX_mutable|5.009003||p SvPVX||| SvPV_const|5.009003||p SvPV_flags_const_nolen|5.009003||p SvPV_flags_const|5.009003||p SvPV_flags_mutable|5.009003||p SvPV_flags|5.007002||p SvPV_force_flags_mutable|5.009003||p SvPV_force_flags_nolen|5.009003||p SvPV_force_flags|5.007002||p SvPV_force_mutable|5.009003||p SvPV_force_nolen|5.009003||p SvPV_force_nomg_nolen|5.009003||p SvPV_force_nomg|5.007002||p SvPV_force|||p SvPV_mutable|5.009003||p SvPV_nolen_const|5.009003||p SvPV_nolen|5.006000||p SvPV_nomg_const_nolen|5.009003||p SvPV_nomg_const|5.009003||p SvPV_nomg_nolen|5.013007||p SvPV_nomg|5.007002||p SvPV_renew|5.009003||p SvPV_set||| SvPVbyte_force||5.009002| SvPVbyte_nolen||5.006000| SvPVbytex_force||5.006000| SvPVbytex||5.006000| SvPVbyte|5.006000||p SvPVutf8_force||5.006000| SvPVutf8_nolen||5.006000| SvPVutf8x_force||5.006000| SvPVutf8x||5.006000| SvPVutf8||5.006000| SvPVx||| SvPV||| SvREFCNT_dec_NN||5.017007| SvREFCNT_dec||| SvREFCNT_inc_NN|5.009004||p SvREFCNT_inc_simple_NN|5.009004||p SvREFCNT_inc_simple_void_NN|5.009004||p SvREFCNT_inc_simple_void|5.009004||p SvREFCNT_inc_simple|5.009004||p SvREFCNT_inc_void_NN|5.009004||p SvREFCNT_inc_void|5.009004||p SvREFCNT_inc|||p SvREFCNT||| SvROK_off||| SvROK_on||| SvROK||| SvRV_set|5.009003||p SvRV||| SvRXOK||5.009005| SvRX||5.009005| SvSETMAGIC||| SvSHARED_HASH|5.009003||p SvSHARE||5.007003| SvSTASH_set|5.009003||p SvSTASH||| SvSetMagicSV_nosteal||5.004000| SvSetMagicSV||5.004000| SvSetSV_nosteal||5.004000| SvSetSV||| SvTAINTED_off||5.004000| SvTAINTED_on||5.004000| SvTAINTED||5.004000| SvTAINT||| SvTHINKFIRST||| SvTRUE_nomg||5.013006| SvTRUE||| SvTYPE||| SvUNLOCK||5.007003| SvUOK|5.007001|5.006000|p SvUPGRADE||| SvUTF8_off||5.006000| SvUTF8_on||5.006000| SvUTF8||5.006000| SvUVXx|5.004000||p SvUVX|5.004000||p SvUV_nomg|5.009001||p SvUV_set|5.009003||p SvUVx|5.004000||p SvUV|5.004000||p SvVOK||5.008001| SvVSTRING_mg|5.009004||p THIS|||n UNDERBAR|5.009002||p UTF8_MAXBYTES|5.009002||p UVSIZE|5.006000||p UVTYPE|5.006000||p UVXf|5.007001||p UVof|5.006000||p UVuf|5.006000||p UVxf|5.006000||p WARN_ALL|5.006000||p WARN_AMBIGUOUS|5.006000||p WARN_ASSERTIONS|5.021008||p WARN_BAREWORD|5.006000||p WARN_CLOSED|5.006000||p WARN_CLOSURE|5.006000||p WARN_DEBUGGING|5.006000||p WARN_DEPRECATED|5.006000||p WARN_DIGIT|5.006000||p WARN_EXEC|5.006000||p WARN_EXITING|5.006000||p WARN_GLOB|5.006000||p WARN_INPLACE|5.006000||p WARN_INTERNAL|5.006000||p WARN_IO|5.006000||p WARN_LAYER|5.008000||p WARN_MALLOC|5.006000||p WARN_MISC|5.006000||p WARN_NEWLINE|5.006000||p WARN_NUMERIC|5.006000||p WARN_ONCE|5.006000||p WARN_OVERFLOW|5.006000||p WARN_PACK|5.006000||p WARN_PARENTHESIS|5.006000||p WARN_PIPE|5.006000||p WARN_PORTABLE|5.006000||p WARN_PRECEDENCE|5.006000||p WARN_PRINTF|5.006000||p WARN_PROTOTYPE|5.006000||p WARN_QW|5.006000||p WARN_RECURSION|5.006000||p WARN_REDEFINE|5.006000||p WARN_REGEXP|5.006000||p WARN_RESERVED|5.006000||p WARN_SEMICOLON|5.006000||p WARN_SEVERE|5.006000||p WARN_SIGNAL|5.006000||p WARN_SUBSTR|5.006000||p WARN_SYNTAX|5.006000||p WARN_TAINT|5.006000||p WARN_THREADS|5.008000||p WARN_UNINITIALIZED|5.006000||p WARN_UNOPENED|5.006000||p WARN_UNPACK|5.006000||p WARN_UNTIE|5.006000||p WARN_UTF8|5.006000||p WARN_VOID|5.006000||p WIDEST_UTYPE|5.015004||p XCPT_CATCH|5.009002||p XCPT_RETHROW|5.009002||p XCPT_TRY_END|5.009002||p XCPT_TRY_START|5.009002||p XPUSHi||| XPUSHmortal|5.009002||p XPUSHn||| XPUSHp||| XPUSHs||| XPUSHu|5.004000||p XSPROTO|5.010000||p XSRETURN_EMPTY||| XSRETURN_IV||| XSRETURN_NO||| XSRETURN_NV||| XSRETURN_PV||| XSRETURN_UNDEF||| XSRETURN_UV|5.008001||p XSRETURN_YES||| XSRETURN|||p XST_mIV||| XST_mNO||| XST_mNV||| XST_mPV||| XST_mUNDEF||| XST_mUV|5.008001||p XST_mYES||| XS_APIVERSION_BOOTCHECK||5.021008| XS_EXTERNAL||5.021008| XS_INTERNAL||5.021008| XS_VERSION_BOOTCHECK||5.021008| XS_VERSION||| XSprePUSH|5.006000||p XS||| XopDISABLE||5.021008| XopENABLE||5.021008| XopENTRYCUSTOM||5.021008| XopENTRY_set||5.021008| XopENTRY||5.021008| XopFLAGS||5.013007| ZeroD|5.009002||p Zero||| _aMY_CXT|5.007003||p _add_range_to_invlist||| _append_range_to_invlist||| _core_swash_init||| _get_encoding||| _get_regclass_nonbitmap_data||| _get_swash_invlist||| _invlist_array_init|||n _invlist_contains_cp|||n _invlist_contents||| _invlist_dump||| _invlist_intersection_maybe_complement_2nd||| _invlist_intersection||| _invlist_invert||| _invlist_len|||n _invlist_populate_swatch|||n _invlist_search|||n _invlist_subtract||| _invlist_union_maybe_complement_2nd||| _invlist_union||| _is_cur_LC_category_utf8||| _is_in_locale_category||5.021001| _is_uni_FOO||5.017008| _is_uni_perl_idcont||5.017008| _is_uni_perl_idstart||5.017007| _is_utf8_FOO||5.017008| _is_utf8_char_slow||5.021001|n _is_utf8_idcont||5.021001| _is_utf8_idstart||5.021001| _is_utf8_mark||5.017008| _is_utf8_perl_idcont||5.017008| _is_utf8_perl_idstart||5.017007| _is_utf8_xidcont||5.021001| _is_utf8_xidstart||5.021001| _load_PL_utf8_foldclosures||| _make_exactf_invlist||| _new_invlist_C_array||| _new_invlist||| _pMY_CXT|5.007003||p _setup_canned_invlist||| _swash_inversion_hash||| _swash_to_invlist||| _to_fold_latin1||| _to_uni_fold_flags||5.014000| _to_upper_title_latin1||| _to_utf8_fold_flags||5.019009| _to_utf8_lower_flags||5.019009| _to_utf8_title_flags||5.019009| _to_utf8_upper_flags||5.019009| _warn_problematic_locale|||n aMY_CXT_|5.007003||p aMY_CXT|5.007003||p aTHXR_|5.021008||p aTHXR|5.021008||p aTHX_|5.006000||p aTHX|5.006000||p aassign_common_vars||| add_above_Latin1_folds||| add_cp_to_invlist||| add_data|||n add_multi_match||| add_utf16_textfilter||| adjust_size_and_find_bucket|||n advance_one_SB||| advance_one_WB||| alloc_maybe_populate_EXACT||| alloccopstash||| allocmy||| amagic_call||| amagic_cmp_locale||| amagic_cmp||| amagic_deref_call||5.013007| amagic_i_ncmp||| amagic_is_enabled||| amagic_ncmp||| anonymise_cv_maybe||| any_dup||| ao||| append_utf8_from_native_byte||5.019004|n apply_attrs_my||| apply_attrs_string||5.006001| apply_attrs||| apply||| assert_uft8_cache_coherent||| assignment_type||| atfork_lock||5.007003|n atfork_unlock||5.007003|n av_arylen_p||5.009003| av_clear||| av_create_and_push||5.009005| av_create_and_unshift_one||5.009005| av_delete||5.006000| av_exists||5.006000| av_extend_guts||| av_extend||| av_fetch||| av_fill||| av_iter_p||5.011000| av_len||| av_make||| av_pop||| av_push||| av_reify||| av_shift||| av_store||| av_tindex||5.017009| av_top_index||5.017009| av_undef||| av_unshift||| ax|||n backup_one_SB||| backup_one_WB||| bad_type_gv||| bad_type_pv||| bind_match||| block_end||5.004000| block_gimme||5.004000| block_start||5.004000| blockhook_register||5.013003| boolSV|5.004000||p boot_core_PerlIO||| boot_core_UNIVERSAL||| boot_core_mro||| bytes_cmp_utf8||5.013007| bytes_from_utf8||5.007001| bytes_to_utf8||5.006001| call_argv|5.006000||p call_atexit||5.006000| call_list||5.004000| call_method|5.006000||p call_pv|5.006000||p call_sv|5.006000||p caller_cx|5.013005|5.006000|p calloc||5.007002|n cando||| cast_i32||5.006000|n cast_iv||5.006000|n cast_ulong||5.006000|n cast_uv||5.006000|n check_locale_boundary_crossing||| check_type_and_open||| check_uni||| check_utf8_print||| checkcomma||| ckWARN|5.006000||p ck_entersub_args_core||| ck_entersub_args_list||5.013006| ck_entersub_args_proto_or_list||5.013006| ck_entersub_args_proto||5.013006| ck_warner_d||5.011001|v ck_warner||5.011001|v ckwarn_common||| ckwarn_d||5.009003| ckwarn||5.009003| clear_placeholders||| clear_special_blocks||| clone_params_del|||n clone_params_new|||n closest_cop||| cntrl_to_mnemonic|||n compute_EXACTish|||n construct_ahocorasick_from_trie||| cop_fetch_label||5.015001| cop_free||| cop_hints_2hv||5.013007| cop_hints_fetch_pvn||5.013007| cop_hints_fetch_pvs||5.013007| cop_hints_fetch_pv||5.013007| cop_hints_fetch_sv||5.013007| cop_store_label||5.015001| cophh_2hv||5.013007| cophh_copy||5.013007| cophh_delete_pvn||5.013007| cophh_delete_pvs||5.013007| cophh_delete_pv||5.013007| cophh_delete_sv||5.013007| cophh_fetch_pvn||5.013007| cophh_fetch_pvs||5.013007| cophh_fetch_pv||5.013007| cophh_fetch_sv||5.013007| cophh_free||5.013007| cophh_new_empty||5.021008| cophh_store_pvn||5.013007| cophh_store_pvs||5.013007| cophh_store_pv||5.013007| cophh_store_sv||5.013007| core_prototype||| coresub_op||| could_it_be_a_POSIX_class|||n cr_textfilter||| create_eval_scope||| croak_memory_wrap||5.019003|n croak_no_mem|||n croak_no_modify||5.013003|n croak_nocontext|||vn croak_popstack|||n croak_sv||5.013001| croak_xs_usage||5.010001|n croak|||v csighandler||5.009003|n current_re_engine||| curse||| custom_op_desc||5.007003| custom_op_get_field||| custom_op_name||5.007003| custom_op_register||5.013007| custom_op_xop||5.013007| cv_ckproto_len_flags||| cv_clone_into||| cv_clone||| cv_const_sv_or_av|||n cv_const_sv||5.003070|n cv_dump||| cv_forget_slab||| cv_get_call_checker||5.013006| cv_name||5.021005| cv_set_call_checker_flags||5.021004| cv_set_call_checker||5.013006| cv_undef_flags||| cv_undef||| cvgv_from_hek||| cvgv_set||| cvstash_set||| cx_dump||5.005000| cx_dup||| cxinc||| dAXMARK|5.009003||p dAX|5.007002||p dITEMS|5.007002||p dMARK||| dMULTICALL||5.009003| dMY_CXT_SV|5.007003||p dMY_CXT|5.007003||p dNOOP|5.006000||p dORIGMARK||| dSP||| dTHR|5.004050||p dTHXR|5.021008||p dTHXa|5.006000||p dTHXoa|5.006000||p dTHX|5.006000||p dUNDERBAR|5.009002||p dVAR|5.009003||p dXCPT|5.009002||p dXSARGS||| dXSI32||| dXSTARG|5.006000||p deb_curcv||| deb_nocontext|||vn deb_stack_all||| deb_stack_n||| debop||5.005000| debprofdump||5.005000| debprof||| debstackptrs||5.007003| debstack||5.007003| debug_start_match||| deb||5.007003|v defelem_target||| del_sv||| delete_eval_scope||| delimcpy||5.004000|n deprecate_commaless_var_list||| despatch_signals||5.007001| destroy_matcher||| die_nocontext|||vn die_sv||5.013001| die_unwind||| die|||v dirp_dup||| div128||| djSP||| do_aexec5||| do_aexec||| do_aspawn||| do_binmode||5.004050| do_chomp||| do_close||| do_delete_local||| do_dump_pad||| do_eof||| do_exec3||| do_execfree||| do_exec||| do_gv_dump||5.006000| do_gvgv_dump||5.006000| do_hv_dump||5.006000| do_ipcctl||| do_ipcget||| do_join||| do_magic_dump||5.006000| do_msgrcv||| do_msgsnd||| do_ncmp||| do_oddball||| do_op_dump||5.006000| do_open6||| do_open9||5.006000| do_open_raw||| do_openn||5.007001| do_open||5.003070| do_pmop_dump||5.006000| do_print||| do_readline||| do_seek||| do_semop||| do_shmio||| do_smartmatch||| do_spawn_nowait||| do_spawn||| do_sprintf||| do_sv_dump||5.006000| do_sysseek||| do_tell||| do_trans_complex_utf8||| do_trans_complex||| do_trans_count_utf8||| do_trans_count||| do_trans_simple_utf8||| do_trans_simple||| do_trans||| do_vecget||| do_vecset||| do_vop||| docatch||| doeval||| dofile||| dofindlabel||| doform||| doing_taint||5.008001|n dooneliner||| doopen_pm||| doparseform||| dopoptoeval||| dopoptogiven||| dopoptolabel||| dopoptoloop||| dopoptosub_at||| dopoptowhen||| doref||5.009003| dounwind||| dowantarray||| drand48_init_r|||n drand48_r|||n dump_all_perl||| dump_all||5.006000| dump_c_backtrace||| dump_eval||5.006000| dump_exec_pos||| dump_form||5.006000| dump_indent||5.006000|v dump_mstats||| dump_packsubs_perl||| dump_packsubs||5.006000| dump_sub_perl||| dump_sub||5.006000| dump_sv_child||| dump_trie_interim_list||| dump_trie_interim_table||| dump_trie||| dump_vindent||5.006000| dumpuntil||| dup_attrlist||| emulate_cop_io||| eval_pv|5.006000||p eval_sv|5.006000||p exec_failed||| expect_number||| fbm_compile||5.005000| fbm_instr||5.005000| feature_is_enabled||| filter_add||| filter_del||| filter_gets||| filter_read||| finalize_optree||| finalize_op||| find_and_forget_pmops||| find_array_subscript||| find_beginning||| find_byclass||| find_default_stash||| find_hash_subscript||| find_in_my_stash||| find_lexical_cv||| find_runcv_where||| find_runcv||5.008001| find_rundefsv2||| find_rundefsvoffset||5.009002| find_rundefsv||5.013002| find_script||| find_uninit_var||| first_symbol|||n fixup_errno_string||| foldEQ_latin1||5.013008|n foldEQ_locale||5.013002|n foldEQ_utf8_flags||5.013010| foldEQ_utf8||5.013002| foldEQ||5.013002|n fold_constants||| forbid_setid||| force_ident_maybe_lex||| force_ident||| force_list||| force_next||| force_strict_version||| force_version||| force_word||| forget_pmop||| form_nocontext|||vn form_short_octal_warning||| form||5.004000|v fp_dup||| fprintf_nocontext|||vn free_c_backtrace||| free_global_struct||| free_tied_hv_pool||| free_tmps||| gen_constant_list||| get_ANYOF_cp_list_for_ssc||| get_and_check_backslash_N_name||| get_aux_mg||| get_av|5.006000||p get_c_backtrace_dump||| get_c_backtrace||| get_context||5.006000|n get_cvn_flags|5.009005||p get_cvs|5.011000||p get_cv|5.006000||p get_db_sub||| get_debug_opts||| get_hash_seed||| get_hv|5.006000||p get_invlist_iter_addr|||n get_invlist_offset_addr|||n get_invlist_previous_index_addr|||n get_mstats||| get_no_modify||| get_num||| get_op_descs||5.005000| get_op_names||5.005000| get_opargs||| get_ppaddr||5.006000| get_re_arg||| get_sv|5.006000||p get_vtbl||5.005030| getcwd_sv||5.007002| getenv_len||| glob_2number||| glob_assign_glob||| gp_dup||| gp_free||| gp_ref||| grok_atoUV|||n grok_bin|5.007003||p grok_bslash_N||| grok_bslash_c||| grok_bslash_o||| grok_bslash_x||| grok_hex|5.007003||p grok_infnan||5.021004| grok_number_flags||5.021002| grok_number|5.007002||p grok_numeric_radix|5.007002||p grok_oct|5.007003||p group_end||| gv_AVadd||| gv_HVadd||| gv_IOadd||| gv_SVadd||| gv_add_by_type||5.011000| gv_autoload4||5.004000| gv_autoload_pvn||5.015004| gv_autoload_pv||5.015004| gv_autoload_sv||5.015004| gv_check||| gv_const_sv||5.009003| gv_dump||5.006000| gv_efullname3||5.003070| gv_efullname4||5.006001| gv_efullname||| gv_fetchfile_flags||5.009005| gv_fetchfile||| gv_fetchmeth_autoload||5.007003| gv_fetchmeth_internal||| gv_fetchmeth_pv_autoload||5.015004| gv_fetchmeth_pvn_autoload||5.015004| gv_fetchmeth_pvn||5.015004| gv_fetchmeth_pv||5.015004| gv_fetchmeth_sv_autoload||5.015004| gv_fetchmeth_sv||5.015004| gv_fetchmethod_autoload||5.004000| gv_fetchmethod_pv_flags||5.015004| gv_fetchmethod_pvn_flags||5.015004| gv_fetchmethod_sv_flags||5.015004| gv_fetchmethod||| gv_fetchmeth||| gv_fetchpvn_flags|5.009002||p gv_fetchpvs|5.009004||p gv_fetchpv||| gv_fetchsv|5.009002||p gv_fullname3||5.003070| gv_fullname4||5.006001| gv_fullname||| gv_handler||5.007001| gv_init_pvn||5.015004| gv_init_pv||5.015004| gv_init_svtype||| gv_init_sv||5.015004| gv_init||| gv_is_in_main||| gv_magicalize_isa||| gv_magicalize||| gv_name_set||5.009004| gv_override||| gv_setref||| gv_stashpvn_internal||| gv_stashpvn|5.003070||p gv_stashpvs|5.009003||p gv_stashpv||| gv_stashsvpvn_cached||| gv_stashsv||| gv_try_downgrade||| handle_regex_sets||| he_dup||| hek_dup||| hfree_next_entry||| hfreeentries||| hsplit||| hv_assert||| hv_auxinit_internal|||n hv_auxinit||| hv_backreferences_p||| hv_clear_placeholders||5.009001| hv_clear||| hv_common_key_len||5.010000| hv_common||5.010000| hv_copy_hints_hv||5.009004| hv_delayfree_ent||5.004000| hv_delete_common||| hv_delete_ent||5.003070| hv_delete||| hv_eiter_p||5.009003| hv_eiter_set||5.009003| hv_ename_add||| hv_ename_delete||| hv_exists_ent||5.003070| hv_exists||| hv_fetch_ent||5.003070| hv_fetchs|5.009003||p hv_fetch||| hv_fill||5.013002| hv_free_ent_ret||| hv_free_ent||5.004000| hv_iterinit||| hv_iterkeysv||5.003070| hv_iterkey||| hv_iternext_flags||5.008000| hv_iternextsv||| hv_iternext||| hv_iterval||| hv_kill_backrefs||| hv_ksplit||5.003070| hv_magic_check|||n hv_magic||| hv_name_set||5.009003| hv_notallowed||| hv_placeholders_get||5.009003| hv_placeholders_p||| hv_placeholders_set||5.009003| hv_rand_set||5.018000| hv_riter_p||5.009003| hv_riter_set||5.009003| hv_scalar||5.009001| hv_store_ent||5.003070| hv_store_flags||5.008000| hv_stores|5.009004||p hv_store||| hv_undef_flags||| hv_undef||| ibcmp_locale||5.004000| ibcmp_utf8||5.007003| ibcmp||| incline||| incpush_if_exists||| incpush_use_sep||| incpush||| ingroup||| init_argv_symbols||| init_constants||| init_dbargs||| init_debugger||| init_global_struct||| init_i18nl10n||5.006000| init_i18nl14n||5.006000| init_ids||| init_interp||| init_main_stash||| init_perllib||| init_postdump_symbols||| init_predump_symbols||| init_stacks||5.005000| init_tm||5.007002| inplace_aassign||| instr|||n intro_my||5.004000| intuit_method||| intuit_more||| invert||| invlist_array|||n invlist_clone||| invlist_extend||| invlist_highest|||n invlist_is_iterating|||n invlist_iterfinish|||n invlist_iterinit|||n invlist_iternext|||n invlist_max|||n invlist_previous_index|||n invlist_set_len||| invlist_set_previous_index|||n invlist_trim|||n invoke_exception_hook||| io_close||| isALNUMC|5.006000||p isALNUM_lazy||5.021001| isALPHANUMERIC||5.017008| isALPHA||| isASCII|5.006000||p isBLANK|5.006001||p isCNTRL|5.006000||p isDIGIT||| isFOO_lc||| isFOO_utf8_lc||| isGCB|||n isGRAPH|5.006000||p isGV_with_GP|5.009004||p isIDCONT||5.017008| isIDFIRST_lazy||5.021001| isIDFIRST||| isLOWER||| isOCTAL||5.013005| isPRINT|5.004000||p isPSXSPC|5.006001||p isPUNCT|5.006000||p isSB||| isSPACE||| isUPPER||| isUTF8_CHAR||5.021001| isWB||| isWORDCHAR||5.013006| isXDIGIT|5.006000||p is_an_int||| is_ascii_string||5.011000| is_handle_constructor|||n is_invariant_string||5.021007|n is_lvalue_sub||5.007001| is_safe_syscall||5.019004| is_ssc_worth_it|||n is_uni_alnum_lc||5.006000| is_uni_alnumc_lc||5.017007| is_uni_alnumc||5.017007| is_uni_alnum||5.006000| is_uni_alpha_lc||5.006000| is_uni_alpha||5.006000| is_uni_ascii_lc||5.006000| is_uni_ascii||5.006000| is_uni_blank_lc||5.017002| is_uni_blank||5.017002| is_uni_cntrl_lc||5.006000| is_uni_cntrl||5.006000| is_uni_digit_lc||5.006000| is_uni_digit||5.006000| is_uni_graph_lc||5.006000| is_uni_graph||5.006000| is_uni_idfirst_lc||5.006000| is_uni_idfirst||5.006000| is_uni_lower_lc||5.006000| is_uni_lower||5.006000| is_uni_print_lc||5.006000| is_uni_print||5.006000| is_uni_punct_lc||5.006000| is_uni_punct||5.006000| is_uni_space_lc||5.006000| is_uni_space||5.006000| is_uni_upper_lc||5.006000| is_uni_upper||5.006000| is_uni_xdigit_lc||5.006000| is_uni_xdigit||5.006000| is_utf8_alnumc||5.017007| is_utf8_alnum||5.006000| is_utf8_alpha||5.006000| is_utf8_ascii||5.006000| is_utf8_blank||5.017002| is_utf8_char_buf||5.015008|n is_utf8_char||5.006000|n is_utf8_cntrl||5.006000| is_utf8_common||| is_utf8_digit||5.006000| is_utf8_graph||5.006000| is_utf8_idcont||5.008000| is_utf8_idfirst||5.006000| is_utf8_lower||5.006000| is_utf8_mark||5.006000| is_utf8_perl_space||5.011001| is_utf8_perl_word||5.011001| is_utf8_posix_digit||5.011001| is_utf8_print||5.006000| is_utf8_punct||5.006000| is_utf8_space||5.006000| is_utf8_string_loclen||5.009003|n is_utf8_string_loc||5.008001|n is_utf8_string||5.006001|n is_utf8_upper||5.006000| is_utf8_xdigit||5.006000| is_utf8_xidcont||5.013010| is_utf8_xidfirst||5.013010| isa_lookup||| isinfnansv||| isinfnan||5.021004|n items|||n ix|||n jmaybe||| join_exact||| keyword_plugin_standard||| keyword||| leave_common||| leave_scope||| lex_bufutf8||5.011002| lex_discard_to||5.011002| lex_grow_linestr||5.011002| lex_next_chunk||5.011002| lex_peek_unichar||5.011002| lex_read_space||5.011002| lex_read_to||5.011002| lex_read_unichar||5.011002| lex_start||5.009005| lex_stuff_pvn||5.011002| lex_stuff_pvs||5.013005| lex_stuff_pv||5.013006| lex_stuff_sv||5.011002| lex_unstuff||5.011002| listkids||| list||| load_module_nocontext|||vn load_module|5.006000||pv localize||| looks_like_bool||| looks_like_number||| lop||| mPUSHi|5.009002||p mPUSHn|5.009002||p mPUSHp|5.009002||p mPUSHs|5.010001||p mPUSHu|5.009002||p mXPUSHi|5.009002||p mXPUSHn|5.009002||p mXPUSHp|5.009002||p mXPUSHs|5.010001||p mXPUSHu|5.009002||p magic_clear_all_env||| magic_cleararylen_p||| magic_clearenv||| magic_clearhints||| magic_clearhint||| magic_clearisa||| magic_clearpack||| magic_clearsig||| magic_copycallchecker||| magic_dump||5.006000| magic_existspack||| magic_freearylen_p||| magic_freeovrld||| magic_getarylen||| magic_getdebugvar||| magic_getdefelem||| magic_getnkeys||| magic_getpack||| magic_getpos||| magic_getsig||| magic_getsubstr||| magic_gettaint||| magic_getuvar||| magic_getvec||| magic_get||| magic_killbackrefs||| magic_methcall1||| magic_methcall|||v magic_methpack||| magic_nextpack||| magic_regdata_cnt||| magic_regdatum_get||| magic_regdatum_set||| magic_scalarpack||| magic_set_all_env||| magic_setarylen||| magic_setcollxfrm||| magic_setdbline||| magic_setdebugvar||| magic_setdefelem||| magic_setenv||| magic_sethint||| magic_setisa||| magic_setlvref||| magic_setmglob||| magic_setnkeys||| magic_setpack||| magic_setpos||| magic_setregexp||| magic_setsig||| magic_setsubstr||| magic_settaint||| magic_setutf8||| magic_setuvar||| magic_setvec||| magic_set||| magic_sizepack||| magic_wipepack||| make_matcher||| make_trie||| malloc_good_size|||n malloced_size|||n malloc||5.007002|n markstack_grow||5.021001| matcher_matches_sv||| maybe_multimagic_gv||| mayberelocate||| measure_struct||| memEQs|5.009005||p memEQ|5.004000||p memNEs|5.009005||p memNE|5.004000||p mem_collxfrm||| mem_log_common|||n mess_alloc||| mess_nocontext|||vn mess_sv||5.013001| mess||5.006000|v mfree||5.007002|n mg_clear||| mg_copy||| mg_dup||| mg_find_mglob||| mg_findext|5.013008||pn mg_find|||n mg_free_type||5.013006| mg_free||| mg_get||| mg_length||5.005000| mg_localize||| mg_magical|||n mg_set||| mg_size||5.005000| mini_mktime||5.007002|n minus_v||| missingterm||| mode_from_discipline||| modkids||| more_bodies||| more_sv||| moreswitches||| move_proto_attr||| mro_clean_isarev||| mro_gather_and_rename||| mro_get_from_name||5.010001| mro_get_linear_isa_dfs||| mro_get_linear_isa||5.009005| mro_get_private_data||5.010001| mro_isa_changed_in||| mro_meta_dup||| mro_meta_init||| mro_method_changed_in||5.009005| mro_package_moved||| mro_register||5.010001| mro_set_mro||5.010001| mro_set_private_data||5.010001| mul128||| mulexp10|||n multideref_stringify||| my_atof2||5.007002| my_atof||5.006000| my_attrs||| my_bcopy|||n my_bytes_to_utf8|||n my_bzero|||n my_chsize||| my_clearenv||| my_cxt_index||| my_cxt_init||| my_dirfd||5.009005|n my_exit_jump||| my_exit||| my_failure_exit||5.004000| my_fflush_all||5.006000| my_fork||5.007003|n my_kid||| my_lstat_flags||| my_lstat||5.021008| my_memcmp|||n my_memset|||n my_pclose||5.003070| my_popen_list||5.007001| my_popen||5.003070| my_setenv||| my_setlocale||| my_snprintf|5.009004||pvn my_socketpair||5.007003|n my_sprintf|5.009003||pvn my_stat_flags||| my_stat||5.021008| my_strerror||5.021001| my_strftime||5.007002| my_strlcat|5.009004||pn my_strlcpy|5.009004||pn my_unexec||| my_vsnprintf||5.009004|n need_utf8|||n newANONATTRSUB||5.006000| newANONHASH||| newANONLIST||| newANONSUB||| newASSIGNOP||| newATTRSUB_x||| newATTRSUB||5.006000| newAVREF||| newAV||| newBINOP||| newCONDOP||| newCONSTSUB_flags||5.015006| newCONSTSUB|5.004050||p newCVREF||| newDEFSVOP||5.021006| newFORM||| newFOROP||5.013007| newGIVENOP||5.009003| newGIVWHENOP||| newGP||| newGVOP||| newGVREF||| newGVgen_flags||5.015004| newGVgen||| newHVREF||| newHVhv||5.005000| newHV||| newIO||| newLISTOP||| newLOGOP||| newLOOPEX||| newLOOPOP||| newMETHOP_internal||| newMETHOP_named||5.021005| newMETHOP||5.021005| newMYSUB||5.017004| newNULLLIST||| newOP||| newPADNAMELIST||5.021007|n newPADNAMEouter||5.021007|n newPADNAMEpvn||5.021007|n newPADOP||| newPMOP||| newPROG||| newPVOP||| newRANGE||| newRV_inc|5.004000||p newRV_noinc|5.004000||p newRV||| newSLICEOP||| newSTATEOP||| newSTUB||| newSUB||| newSVOP||| newSVREF||| newSV_type|5.009005||p newSVavdefelem||| newSVhek||5.009003| newSViv||| newSVnv||| newSVpadname||5.017004| newSVpv_share||5.013006| newSVpvf_nocontext|||vn newSVpvf||5.004000|v newSVpvn_flags|5.010001||p newSVpvn_share|5.007001||p newSVpvn_utf8|5.010001||p newSVpvn|5.004050||p newSVpvs_flags|5.010001||p newSVpvs_share|5.009003||p newSVpvs|5.009003||p newSVpv||| newSVrv||| newSVsv||| newSVuv|5.006000||p newSV||| newUNOP_AUX||5.021007| newUNOP||| newWHENOP||5.009003| newWHILEOP||5.013007| newXS_deffile||| newXS_flags||5.009004| newXS_len_flags||| newXSproto||5.006000| newXS||5.006000| new_collate||5.006000| new_constant||| new_ctype||5.006000| new_he||| new_logop||| new_numeric||5.006000| new_stackinfo||5.005000| new_version||5.009000| new_warnings_bitfield||| next_symbol||| nextargv||| nextchar||| ninstr|||n no_bareword_allowed||| no_fh_allowed||| no_op||| noperl_die|||vn not_a_number||| not_incrementable||| nothreadhook||5.008000| nuke_stacks||| num_overflow|||n oopsAV||| oopsHV||| op_append_elem||5.013006| op_append_list||5.013006| op_clear||| op_contextualize||5.013006| op_convert_list||5.021006| op_dump||5.006000| op_free||| op_integerize||| op_linklist||5.013006| op_lvalue_flags||| op_lvalue||5.013007| op_null||5.007002| op_parent||5.021002|n op_prepend_elem||5.013006| op_refcnt_dec||| op_refcnt_inc||| op_refcnt_lock||5.009002| op_refcnt_unlock||5.009002| op_relocate_sv||| op_scope||5.013007| op_sibling_splice||5.021002|n op_std_init||| op_unscope||| open_script||| openn_cleanup||| openn_setup||| opmethod_stash||| opslab_force_free||| opslab_free_nopad||| opslab_free||| pMY_CXT_|5.007003||p pMY_CXT|5.007003||p pTHX_|5.006000||p pTHX|5.006000||p packWARN|5.007003||p pack_cat||5.007003| pack_rec||| package_version||| package||| packlist||5.008001| pad_add_anon||5.008001| pad_add_name_pvn||5.015001| pad_add_name_pvs||5.015001| pad_add_name_pv||5.015001| pad_add_name_sv||5.015001| pad_add_weakref||| pad_alloc_name||| pad_alloc||| pad_block_start||| pad_check_dup||| pad_compname_type||5.009003| pad_findlex||| pad_findmy_pvn||5.015001| pad_findmy_pvs||5.015001| pad_findmy_pv||5.015001| pad_findmy_sv||5.015001| pad_fixup_inner_anons||| pad_free||| pad_leavemy||| pad_new||5.008001| pad_push||| pad_reset||| pad_setsv||| pad_sv||| pad_swipe||| pad_tidy||5.008001| padlist_dup||| padlist_store||| padname_dup||| padname_free||| padnamelist_dup||| padnamelist_fetch||5.021007|n padnamelist_free||| padnamelist_store||5.021007| parse_arithexpr||5.013008| parse_barestmt||5.013007| parse_block||5.013007| parse_body||| parse_fullexpr||5.013008| parse_fullstmt||5.013005| parse_gv_stash_name||| parse_ident||| parse_label||5.013007| parse_listexpr||5.013008| parse_lparen_question_flags||| parse_stmtseq||5.013006| parse_subsignature||| parse_termexpr||5.013008| parse_unicode_opts||| parser_dup||| parser_free_nexttoke_ops||| parser_free||| path_is_searchable|||n peep||| pending_ident||| perl_alloc_using|||n perl_alloc|||n perl_clone_using|||n perl_clone|||n perl_construct|||n perl_destruct||5.007003|n perl_free|||n perl_parse||5.006000|n perl_run|||n pidgone||| pm_description||| pmop_dump||5.006000| pmruntime||| pmtrans||| pop_scope||| populate_ANYOF_from_invlist||| populate_isa|||v pregcomp||5.009005| pregexec||| pregfree2||5.011000| pregfree||| prescan_version||5.011004| printbuf||| printf_nocontext|||vn process_special_blocks||| ptr_hash|||n ptr_table_clear||5.009005| ptr_table_fetch||5.009005| ptr_table_find|||n ptr_table_free||5.009005| ptr_table_new||5.009005| ptr_table_split||5.009005| ptr_table_store||5.009005| push_scope||| put_charclass_bitmap_innards||| put_code_point||| put_range||| pv_display|5.006000||p pv_escape|5.009004||p pv_pretty|5.009004||p pv_uni_display||5.007003| qerror||| qsortsvu||| quadmath_format_needed|||n quadmath_format_single|||n re_compile||5.009005| re_croak2||| re_dup_guts||| re_intuit_start||5.019001| re_intuit_string||5.006000| re_op_compile||| realloc||5.007002|n reentrant_free||5.021008| reentrant_init||5.021008| reentrant_retry||5.021008|vn reentrant_size||5.021008| ref_array_or_hash||| refcounted_he_chain_2hv||| refcounted_he_fetch_pvn||| refcounted_he_fetch_pvs||| refcounted_he_fetch_pv||| refcounted_he_fetch_sv||| refcounted_he_free||| refcounted_he_inc||| refcounted_he_new_pvn||| refcounted_he_new_pvs||| refcounted_he_new_pv||| refcounted_he_new_sv||| refcounted_he_value||| refkids||| refto||| ref||5.021008| reg2Lanode||| reg_check_named_buff_matched|||n reg_named_buff_all||5.009005| reg_named_buff_exists||5.009005| reg_named_buff_fetch||5.009005| reg_named_buff_firstkey||5.009005| reg_named_buff_iter||| reg_named_buff_nextkey||5.009005| reg_named_buff_scalar||5.009005| reg_named_buff||| reg_node||| reg_numbered_buff_fetch||| reg_numbered_buff_length||| reg_numbered_buff_store||| reg_qr_package||| reg_recode||| reg_scan_name||| reg_skipcomment|||n reg_temp_copy||| reganode||| regatom||| regbranch||| regclass_swash||5.009004| regclass||| regcppop||| regcppush||| regcurly|||n regdump_extflags||| regdump_intflags||| regdump||5.005000| regdupe_internal||| regexec_flags||5.005000| regfree_internal||5.009005| reghop3|||n reghop4|||n reghopmaybe3|||n reginclass||| reginitcolors||5.006000| reginsert||| regmatch||| regnext||5.005000| regnode_guts||| regpatws|||n regpiece||| regpposixcc||| regprop||| regrepeat||| regtail_study||| regtail||| regtry||| reg||| repeatcpy|||n report_evil_fh||| report_redefined_cv||| report_uninit||| report_wrongway_fh||| require_pv||5.006000| require_tie_mod||| restore_magic||| rninstr|||n rpeep||| rsignal_restore||| rsignal_save||| rsignal_state||5.004000| rsignal||5.004000| run_body||| run_user_filter||| runops_debug||5.005000| runops_standard||5.005000| rv2cv_op_cv||5.013006| rvpv_dup||| rxres_free||| rxres_restore||| rxres_save||| safesyscalloc||5.006000|n safesysfree||5.006000|n safesysmalloc||5.006000|n safesysrealloc||5.006000|n same_dirent||| save_I16||5.004000| save_I32||| save_I8||5.006000| save_adelete||5.011000| save_aelem_flags||5.011000| save_aelem||5.004050| save_aliased_sv||| save_alloc||5.006000| save_aptr||| save_ary||| save_bool||5.008001| save_clearsv||| save_delete||| save_destructor_x||5.006000| save_destructor||5.006000| save_freeop||| save_freepv||| save_freesv||| save_generic_pvref||5.006001| save_generic_svref||5.005030| save_gp||5.004000| save_hash||| save_hdelete||5.011000| save_hek_flags|||n save_helem_flags||5.011000| save_helem||5.004050| save_hints||5.010001| save_hptr||| save_int||| save_item||| save_iv||5.005000| save_lines||| save_list||| save_long||| save_magic_flags||| save_mortalizesv||5.007001| save_nogv||| save_op||5.005000| save_padsv_and_mortalize||5.010001| save_pptr||| save_pushi32ptr||5.010001| save_pushptri32ptr||| save_pushptrptr||5.010001| save_pushptr||5.010001| save_re_context||5.006000| save_scalar_at||| save_scalar||| save_set_svflags||5.009000| save_shared_pvref||5.007003| save_sptr||| save_strlen||| save_svref||| save_vptr||5.006000| savepvn||| savepvs||5.009003| savepv||| savesharedpvn||5.009005| savesharedpvs||5.013006| savesharedpv||5.007003| savesharedsvpv||5.013006| savestack_grow_cnt||5.008001| savestack_grow||| savesvpv||5.009002| sawparens||| scalar_mod_type|||n scalarboolean||| scalarkids||| scalarseq||| scalarvoid||| scalar||| scan_bin||5.006000| scan_commit||| scan_const||| scan_formline||| scan_heredoc||| scan_hex||| scan_ident||| scan_inputsymbol||| scan_num||5.007001| scan_oct||| scan_pat||| scan_str||| scan_subst||| scan_trans||| scan_version||5.009001| scan_vstring||5.009005| scan_word||| search_const||| seed||5.008001| sequence_num||| set_ANYOF_arg||| set_caret_X||| set_context||5.006000|n set_numeric_local||5.006000| set_numeric_radix||5.006000| set_numeric_standard||5.006000| set_padlist|||n setdefout||| share_hek_flags||| share_hek||5.004000| should_warn_nl|||n si_dup||| sighandler|||n simplify_sort||| skipspace_flags||| softref2xv||| sortcv_stacked||| sortcv_xsub||| sortcv||| sortsv_flags||5.009003| sortsv||5.007003| space_join_names_mortal||| ss_dup||| ssc_add_range||| ssc_and||| ssc_anything||| ssc_clear_locale|||n ssc_cp_and||| ssc_finalize||| ssc_init||| ssc_intersection||| ssc_is_anything|||n ssc_is_cp_posixl_init|||n ssc_or||| ssc_union||| stack_grow||| start_glob||| start_subparse||5.004000| stdize_locale||| strEQ||| strGE||| strGT||| strLE||| strLT||| strNE||| str_to_version||5.006000| strip_return||| strnEQ||| strnNE||| study_chunk||| sub_crush_depth||| sublex_done||| sublex_push||| sublex_start||| sv_2bool_flags||5.013006| sv_2bool||| sv_2cv||| sv_2io||| sv_2iuv_common||| sv_2iuv_non_preserve||| sv_2iv_flags||5.009001| sv_2iv||| sv_2mortal||| sv_2num||| sv_2nv_flags||5.013001| sv_2pv_flags|5.007002||p sv_2pv_nolen|5.006000||p sv_2pvbyte_nolen|5.006000||p sv_2pvbyte|5.006000||p sv_2pvutf8_nolen||5.006000| sv_2pvutf8||5.006000| sv_2pv||| sv_2uv_flags||5.009001| sv_2uv|5.004000||p sv_add_arena||| sv_add_backref||| sv_backoff|||n sv_bless||| sv_buf_to_ro||| sv_buf_to_rw||| sv_cat_decode||5.008001| sv_catpv_flags||5.013006| sv_catpv_mg|5.004050||p sv_catpv_nomg||5.013006| sv_catpvf_mg_nocontext|||pvn sv_catpvf_mg|5.006000|5.004000|pv sv_catpvf_nocontext|||vn sv_catpvf||5.004000|v sv_catpvn_flags||5.007002| sv_catpvn_mg|5.004050||p sv_catpvn_nomg|5.007002||p sv_catpvn||| sv_catpvs_flags||5.013006| sv_catpvs_mg||5.013006| sv_catpvs_nomg||5.013006| sv_catpvs|5.009003||p sv_catpv||| sv_catsv_flags||5.007002| sv_catsv_mg|5.004050||p sv_catsv_nomg|5.007002||p sv_catsv||| sv_chop||| sv_clean_all||| sv_clean_objs||| sv_clear||| sv_cmp_flags||5.013006| sv_cmp_locale_flags||5.013006| sv_cmp_locale||5.004000| sv_cmp||| sv_collxfrm_flags||5.013006| sv_collxfrm||| sv_copypv_flags||5.017002| sv_copypv_nomg||5.017002| sv_copypv||| sv_dec_nomg||5.013002| sv_dec||| sv_del_backref||| sv_derived_from_pvn||5.015004| sv_derived_from_pv||5.015004| sv_derived_from_sv||5.015004| sv_derived_from||5.004000| sv_destroyable||5.010000| sv_display||| sv_does_pvn||5.015004| sv_does_pv||5.015004| sv_does_sv||5.015004| sv_does||5.009004| sv_dump||| sv_dup_common||| sv_dup_inc_multiple||| sv_dup_inc||| sv_dup||| sv_eq_flags||5.013006| sv_eq||| sv_exp_grow||| sv_force_normal_flags||5.007001| sv_force_normal||5.006000| sv_free2||| sv_free_arenas||| sv_free||| sv_get_backrefs||5.021008|n sv_gets||5.003070| sv_grow||| sv_i_ncmp||| sv_inc_nomg||5.013002| sv_inc||| sv_insert_flags||5.010001| sv_insert||| sv_isa||| sv_isobject||| sv_iv||5.005000| sv_kill_backrefs||| sv_len_utf8_nomg||| sv_len_utf8||5.006000| sv_len||| sv_magic_portable|5.021008|5.004000|p sv_magicext_mglob||| sv_magicext||5.007003| sv_magic||| sv_mortalcopy_flags||| sv_mortalcopy||| sv_ncmp||| sv_newmortal||| sv_newref||| sv_nolocking||5.007003| sv_nosharing||5.007003| sv_nounlocking||| sv_nv||5.005000| sv_only_taint_gmagic|||n sv_or_pv_pos_u2b||| sv_peek||5.005000| sv_pos_b2u_flags||5.019003| sv_pos_b2u_midway||| sv_pos_b2u||5.006000| sv_pos_u2b_cached||| sv_pos_u2b_flags||5.011005| sv_pos_u2b_forwards|||n sv_pos_u2b_midway|||n sv_pos_u2b||5.006000| sv_pvbyten_force||5.006000| sv_pvbyten||5.006000| sv_pvbyte||5.006000| sv_pvn_force_flags|5.007002||p sv_pvn_force||| sv_pvn_nomg|5.007003|5.005000|p sv_pvn||5.005000| sv_pvutf8n_force||5.006000| sv_pvutf8n||5.006000| sv_pvutf8||5.006000| sv_pv||5.006000| sv_recode_to_utf8||5.007003| sv_reftype||| sv_ref||| sv_release_COW||| sv_replace||| sv_report_used||| sv_resetpvn||| sv_reset||| sv_rvweaken||5.006000| sv_sethek||| sv_setiv_mg|5.004050||p sv_setiv||| sv_setnv_mg|5.006000||p sv_setnv||| sv_setpv_mg|5.004050||p sv_setpvf_mg_nocontext|||pvn sv_setpvf_mg|5.006000|5.004000|pv sv_setpvf_nocontext|||vn sv_setpvf||5.004000|v sv_setpviv_mg||5.008001| sv_setpviv||5.008001| sv_setpvn_mg|5.004050||p sv_setpvn||| sv_setpvs_mg||5.013006| sv_setpvs|5.009004||p sv_setpv||| sv_setref_iv||| sv_setref_nv||| sv_setref_pvn||| sv_setref_pvs||5.021008| sv_setref_pv||| sv_setref_uv||5.007001| sv_setsv_cow||| sv_setsv_flags||5.007002| sv_setsv_mg|5.004050||p sv_setsv_nomg|5.007002||p sv_setsv||| sv_setuv_mg|5.004050||p sv_setuv|5.004000||p sv_tainted||5.004000| sv_taint||5.004000| sv_true||5.005000| sv_unglob||| sv_uni_display||5.007003| sv_unmagicext|5.013008||p sv_unmagic||| sv_unref_flags||5.007001| sv_unref||| sv_untaint||5.004000| sv_upgrade||| sv_usepvn_flags||5.009004| sv_usepvn_mg|5.004050||p sv_usepvn||| sv_utf8_decode||5.006000| sv_utf8_downgrade||5.006000| sv_utf8_encode||5.006000| sv_utf8_upgrade_flags_grow||5.011000| sv_utf8_upgrade_flags||5.007002| sv_utf8_upgrade_nomg||5.007002| sv_utf8_upgrade||5.007001| sv_uv|5.005000||p sv_vcatpvf_mg|5.006000|5.004000|p sv_vcatpvfn_flags||5.017002| sv_vcatpvfn||5.004000| sv_vcatpvf|5.006000|5.004000|p sv_vsetpvf_mg|5.006000|5.004000|p sv_vsetpvfn||5.004000| sv_vsetpvf|5.006000|5.004000|p svtype||| swallow_bom||| swash_fetch||5.007002| swash_init||5.006000| swash_scan_list_line||| swatch_get||| sync_locale||5.021004| sys_init3||5.010000|n sys_init||5.010000|n sys_intern_clear||| sys_intern_dup||| sys_intern_init||| sys_term||5.010000|n taint_env||| taint_proper||| tied_method|||v tmps_grow_p||| toFOLD_uni||5.007003| toFOLD_utf8||5.019001| toFOLD||5.019001| toLOWER_L1||5.019001| toLOWER_LC||5.004000| toLOWER_uni||5.007003| toLOWER_utf8||5.015007| toLOWER||| toTITLE_uni||5.007003| toTITLE_utf8||5.015007| toTITLE||5.019001| toUPPER_uni||5.007003| toUPPER_utf8||5.015007| toUPPER||| to_byte_substr||| to_lower_latin1|||n to_uni_fold||5.007003| to_uni_lower_lc||5.006000| to_uni_lower||5.007003| to_uni_title_lc||5.006000| to_uni_title||5.007003| to_uni_upper_lc||5.006000| to_uni_upper||5.007003| to_utf8_case||5.007003| to_utf8_fold||5.015007| to_utf8_lower||5.015007| to_utf8_substr||| to_utf8_title||5.015007| to_utf8_upper||5.015007| tokenize_use||| tokeq||| tokereport||| too_few_arguments_pv||| too_many_arguments_pv||| translate_substr_offsets|||n try_amagic_bin||| try_amagic_un||| uiv_2buf|||n unlnk||| unpack_rec||| unpack_str||5.007003| unpackstring||5.008001| unreferenced_to_tmp_stack||| unshare_hek_or_pvn||| unshare_hek||| unsharepvn||5.003070| unwind_handler_stack||| update_debugger_info||| upg_version||5.009005| usage||| utf16_textfilter||| utf16_to_utf8_reversed||5.006001| utf16_to_utf8||5.006001| utf8_distance||5.006000| utf8_hop||5.006000|n utf8_length||5.007001| utf8_mg_len_cache_update||| utf8_mg_pos_cache_update||| utf8_to_bytes||5.006001| utf8_to_uvchr_buf||5.015009| utf8_to_uvchr||5.007001| utf8_to_uvuni_buf||5.015009| utf8_to_uvuni||5.007001| utf8n_to_uvchr||5.007001| utf8n_to_uvuni||5.007001| utilize||| uvchr_to_utf8_flags||5.007003| uvchr_to_utf8||5.007001| uvoffuni_to_utf8_flags||5.019004| uvuni_to_utf8_flags||5.007003| uvuni_to_utf8||5.007001| valid_utf8_to_uvchr||5.015009| valid_utf8_to_uvuni||5.015009| validate_proto||| validate_suid||| varname||| vcmp||5.009000| vcroak||5.006000| vdeb||5.007003| vform||5.006000| visit||| vivify_defelem||| vivify_ref||| vload_module|5.006000||p vmess||5.006000| vnewSVpvf|5.006000|5.004000|p vnormal||5.009002| vnumify||5.009000| vstringify||5.009000| vverify||5.009003| vwarner||5.006000| vwarn||5.006000| wait4pid||| warn_nocontext|||vn warn_sv||5.013001| warner_nocontext|||vn warner|5.006000|5.004000|pv warn|||v was_lvalue_sub||| watch||| whichsig_pvn||5.015004| whichsig_pv||5.015004| whichsig_sv||5.015004| whichsig||| win32_croak_not_implemented|||n with_queued_errors||| wrap_op_checker||5.015008| write_to_stderr||| xs_boot_epilog||| xs_handshake|||vn xs_version_bootcheck||| yyerror_pvn||| yyerror_pv||| yyerror||| yylex||| yyparse||| yyunlex||| yywarn||| ); if (exists $opt{'list-unsupported'}) { my $f; for $f (sort { lc $a cmp lc $b } keys %API) { next unless $API{$f}{todo}; print "$f ", '.'x(40-length($f)), " ", format_version($API{$f}{todo}), "\n"; } exit 0; } # Scan for possible replacement candidates my(%replace, %need, %hints, %warnings, %depends); my $replace = 0; my($hint, $define, $function); sub find_api { my $code = shift; $code =~ s{ / (?: \*[^*]*\*+(?:[^$ccs][^*]*\*+)* / | /[^\r\n]*) | "[^"\\]*(?:\\.[^"\\]*)*" | '[^'\\]*(?:\\.[^'\\]*)*' }{}egsx; grep { exists $API{$_} } $code =~ /(\w+)/mg; } while () { if ($hint) { my $h = $hint->[0] eq 'Hint' ? \%hints : \%warnings; if (m{^\s*\*\s(.*?)\s*$}) { for (@{$hint->[1]}) { $h->{$_} ||= ''; # suppress warning with older perls $h->{$_} .= "$1\n"; } } else { undef $hint } } $hint = [$1, [split /,?\s+/, $2]] if m{^\s*$rccs\s+(Hint|Warning):\s+(\w+(?:,?\s+\w+)*)\s*$}; if ($define) { if ($define->[1] =~ /\\$/) { $define->[1] .= $_; } else { if (exists $API{$define->[0]} && $define->[1] !~ /^DPPP_\(/) { my @n = find_api($define->[1]); push @{$depends{$define->[0]}}, @n if @n } undef $define; } } $define = [$1, $2] if m{^\s*#\s*define\s+(\w+)(?:\([^)]*\))?\s+(.*)}; if ($function) { if (/^}/) { if (exists $API{$function->[0]}) { my @n = find_api($function->[1]); push @{$depends{$function->[0]}}, @n if @n } undef $function; } else { $function->[1] .= $_; } } $function = [$1, ''] if m{^DPPP_\(my_(\w+)\)}; $replace = $1 if m{^\s*$rccs\s+Replace:\s+(\d+)\s+$rcce\s*$}; $replace{$2} = $1 if $replace and m{^\s*#\s*define\s+(\w+)(?:\([^)]*\))?\s+(\w+)}; $replace{$2} = $1 if m{^\s*#\s*define\s+(\w+)(?:\([^)]*\))?\s+(\w+).*$rccs\s+Replace\s+$rcce}; $replace{$1} = $2 if m{^\s*$rccs\s+Replace (\w+) with (\w+)\s+$rcce\s*$}; if (m{^\s*$rccs\s+(\w+(\s*,\s*\w+)*)\s+depends\s+on\s+(\w+(\s*,\s*\w+)*)\s+$rcce\s*$}) { my @deps = map { s/\s+//g; $_ } split /,/, $3; my $d; for $d (map { s/\s+//g; $_ } split /,/, $1) { push @{$depends{$d}}, @deps; } } $need{$1} = 1 if m{^#if\s+defined\(NEED_(\w+)(?:_GLOBAL)?\)}; } for (values %depends) { my %s; $_ = [sort grep !$s{$_}++, @$_]; } if (exists $opt{'api-info'}) { my $f; my $count = 0; my $match = $opt{'api-info'} =~ m!^/(.*)/$! ? $1 : "^\Q$opt{'api-info'}\E\$"; for $f (sort { lc $a cmp lc $b } keys %API) { next unless $f =~ /$match/; print "\n=== $f ===\n\n"; my $info = 0; if ($API{$f}{base} || $API{$f}{todo}) { my $base = format_version($API{$f}{base} || $API{$f}{todo}); print "Supported at least starting from perl-$base.\n"; $info++; } if ($API{$f}{provided}) { my $todo = $API{$f}{todo} ? format_version($API{$f}{todo}) : "5.003"; print "Support by $ppport provided back to perl-$todo.\n"; print "Support needs to be explicitly requested by NEED_$f.\n" if exists $need{$f}; print "Depends on: ", join(', ', @{$depends{$f}}), ".\n" if exists $depends{$f}; print "\n$hints{$f}" if exists $hints{$f}; print "\nWARNING:\n$warnings{$f}" if exists $warnings{$f}; $info++; } print "No portability information available.\n" unless $info; $count++; } $count or print "Found no API matching '$opt{'api-info'}'."; print "\n"; exit 0; } if (exists $opt{'list-provided'}) { my $f; for $f (sort { lc $a cmp lc $b } keys %API) { next unless $API{$f}{provided}; my @flags; push @flags, 'explicit' if exists $need{$f}; push @flags, 'depend' if exists $depends{$f}; push @flags, 'hint' if exists $hints{$f}; push @flags, 'warning' if exists $warnings{$f}; my $flags = @flags ? ' ['.join(', ', @flags).']' : ''; print "$f$flags\n"; } exit 0; } my @files; my @srcext = qw( .xs .c .h .cc .cpp -c.inc -xs.inc ); my $srcext = join '|', map { quotemeta $_ } @srcext; if (@ARGV) { my %seen; for (@ARGV) { if (-e) { if (-f) { push @files, $_ unless $seen{$_}++; } else { warn "'$_' is not a file.\n" } } else { my @new = grep { -f } glob $_ or warn "'$_' does not exist.\n"; push @files, grep { !$seen{$_}++ } @new; } } } else { eval { require File::Find; File::Find::find(sub { $File::Find::name =~ /($srcext)$/i and push @files, $File::Find::name; }, '.'); }; if ($@) { @files = map { glob "*$_" } @srcext; } } if (!@ARGV || $opt{filter}) { my(@in, @out); my %xsc = map { /(.*)\.xs$/ ? ("$1.c" => 1, "$1.cc" => 1) : () } @files; for (@files) { my $out = exists $xsc{$_} || /\b\Q$ppport\E$/i || !/($srcext)$/i; push @{ $out ? \@out : \@in }, $_; } if (@ARGV && @out) { warning("Skipping the following files (use --nofilter to avoid this):\n| ", join "\n| ", @out); } @files = @in; } die "No input files given!\n" unless @files; my(%files, %global, %revreplace); %revreplace = reverse %replace; my $filename; my $patch_opened = 0; for $filename (@files) { unless (open IN, "<$filename") { warn "Unable to read from $filename: $!\n"; next; } info("Scanning $filename ..."); my $c = do { local $/; }; close IN; my %file = (orig => $c, changes => 0); # Temporarily remove C/XS comments and strings from the code my @ccom; $c =~ s{ ( ^$HS*\#$HS*include\b[^\r\n]+\b(?:\Q$ppport\E|XSUB\.h)\b[^\r\n]* | ^$HS*\#$HS*(?:define|elif|if(?:def)?)\b[^\r\n]* ) | ( ^$HS*\#[^\r\n]* | "[^"\\]*(?:\\.[^"\\]*)*" | '[^'\\]*(?:\\.[^'\\]*)*' | / (?: \*[^*]*\*+(?:[^$ccs][^*]*\*+)* / | /[^\r\n]* ) ) }{ defined $2 and push @ccom, $2; defined $1 ? $1 : "$ccs$#ccom$cce" }mgsex; $file{ccom} = \@ccom; $file{code} = $c; $file{has_inc_ppport} = $c =~ /^$HS*#$HS*include[^\r\n]+\b\Q$ppport\E\b/m; my $func; for $func (keys %API) { my $match = $func; $match .= "|$revreplace{$func}" if exists $revreplace{$func}; if ($c =~ /\b(?:Perl_)?($match)\b/) { $file{uses_replace}{$1}++ if exists $revreplace{$func} && $1 eq $revreplace{$func}; $file{uses_Perl}{$func}++ if $c =~ /\bPerl_$func\b/; if (exists $API{$func}{provided}) { $file{uses_provided}{$func}++; if (!exists $API{$func}{base} || $API{$func}{base} > $opt{'compat-version'}) { $file{uses}{$func}++; my @deps = rec_depend($func); if (@deps) { $file{uses_deps}{$func} = \@deps; for (@deps) { $file{uses}{$_} = 0 unless exists $file{uses}{$_}; } } for ($func, @deps) { $file{needs}{$_} = 'static' if exists $need{$_}; } } } if (exists $API{$func}{todo} && $API{$func}{todo} > $opt{'compat-version'}) { if ($c =~ /\b$func\b/) { $file{uses_todo}{$func}++; } } } } while ($c =~ /^$HS*#$HS*define$HS+(NEED_(\w+?)(_GLOBAL)?)\b/mg) { if (exists $need{$2}) { $file{defined $3 ? 'needed_global' : 'needed_static'}{$2}++; } else { warning("Possibly wrong #define $1 in $filename") } } for (qw(uses needs uses_todo needed_global needed_static)) { for $func (keys %{$file{$_}}) { push @{$global{$_}{$func}}, $filename; } } $files{$filename} = \%file; } # Globally resolve NEED_'s my $need; for $need (keys %{$global{needs}}) { if (@{$global{needs}{$need}} > 1) { my @targets = @{$global{needs}{$need}}; my @t = grep $files{$_}{needed_global}{$need}, @targets; @targets = @t if @t; @t = grep /\.xs$/i, @targets; @targets = @t if @t; my $target = shift @targets; $files{$target}{needs}{$need} = 'global'; for (@{$global{needs}{$need}}) { $files{$_}{needs}{$need} = 'extern' if $_ ne $target; } } } for $filename (@files) { exists $files{$filename} or next; info("=== Analyzing $filename ==="); my %file = %{$files{$filename}}; my $func; my $c = $file{code}; my $warnings = 0; for $func (sort keys %{$file{uses_Perl}}) { if ($API{$func}{varargs}) { unless ($API{$func}{nothxarg}) { my $changes = ($c =~ s{\b(Perl_$func\s*\(\s*)(?!aTHX_?)(\)|[^\s)]*\))} { $1 . ($2 eq ')' ? 'aTHX' : 'aTHX_ ') . $2 }ge); if ($changes) { warning("Doesn't pass interpreter argument aTHX to Perl_$func"); $file{changes} += $changes; } } } else { warning("Uses Perl_$func instead of $func"); $file{changes} += ($c =~ s{\bPerl_$func(\s*)\((\s*aTHX_?)?\s*} {$func$1(}g); } } for $func (sort keys %{$file{uses_replace}}) { warning("Uses $func instead of $replace{$func}"); $file{changes} += ($c =~ s/\b$func\b/$replace{$func}/g); } for $func (sort keys %{$file{uses_provided}}) { if ($file{uses}{$func}) { if (exists $file{uses_deps}{$func}) { diag("Uses $func, which depends on ", join(', ', @{$file{uses_deps}{$func}})); } else { diag("Uses $func"); } } $warnings += hint($func); } unless ($opt{quiet}) { for $func (sort keys %{$file{uses_todo}}) { print "*** WARNING: Uses $func, which may not be portable below perl ", format_version($API{$func}{todo}), ", even with '$ppport'\n"; $warnings++; } } for $func (sort keys %{$file{needed_static}}) { my $message = ''; if (not exists $file{uses}{$func}) { $message = "No need to define NEED_$func if $func is never used"; } elsif (exists $file{needs}{$func} && $file{needs}{$func} ne 'static') { $message = "No need to define NEED_$func when already needed globally"; } if ($message) { diag($message); $file{changes} += ($c =~ s/^$HS*#$HS*define$HS+NEED_$func\b.*$LF//mg); } } for $func (sort keys %{$file{needed_global}}) { my $message = ''; if (not exists $global{uses}{$func}) { $message = "No need to define NEED_${func}_GLOBAL if $func is never used"; } elsif (exists $file{needs}{$func}) { if ($file{needs}{$func} eq 'extern') { $message = "No need to define NEED_${func}_GLOBAL when already needed globally"; } elsif ($file{needs}{$func} eq 'static') { $message = "No need to define NEED_${func}_GLOBAL when only used in this file"; } } if ($message) { diag($message); $file{changes} += ($c =~ s/^$HS*#$HS*define$HS+NEED_${func}_GLOBAL\b.*$LF//mg); } } $file{needs_inc_ppport} = keys %{$file{uses}}; if ($file{needs_inc_ppport}) { my $pp = ''; for $func (sort keys %{$file{needs}}) { my $type = $file{needs}{$func}; next if $type eq 'extern'; my $suffix = $type eq 'global' ? '_GLOBAL' : ''; unless (exists $file{"needed_$type"}{$func}) { if ($type eq 'global') { diag("Files [@{$global{needs}{$func}}] need $func, adding global request"); } else { diag("File needs $func, adding static request"); } $pp .= "#define NEED_$func$suffix\n"; } } if ($pp && ($c =~ s/^(?=$HS*#$HS*define$HS+NEED_\w+)/$pp/m)) { $pp = ''; $file{changes}++; } unless ($file{has_inc_ppport}) { diag("Needs to include '$ppport'"); $pp .= qq(#include "$ppport"\n) } if ($pp) { $file{changes} += ($c =~ s/^($HS*#$HS*define$HS+NEED_\w+.*?)^/$1$pp/ms) || ($c =~ s/^(?=$HS*#$HS*include.*\Q$ppport\E)/$pp/m) || ($c =~ s/^($HS*#$HS*include.*XSUB.*\s*?)^/$1$pp/m) || ($c =~ s/^/$pp/); } } else { if ($file{has_inc_ppport}) { diag("No need to include '$ppport'"); $file{changes} += ($c =~ s/^$HS*?#$HS*include.*\Q$ppport\E.*?$LF//m); } } # put back in our C comments my $ix; my $cppc = 0; my @ccom = @{$file{ccom}}; for $ix (0 .. $#ccom) { if (!$opt{cplusplus} && $ccom[$ix] =~ s!^//!!) { $cppc++; $file{changes} += $c =~ s/$rccs$ix$rcce/$ccs$ccom[$ix] $cce/; } else { $c =~ s/$rccs$ix$rcce/$ccom[$ix]/; } } if ($cppc) { my $s = $cppc != 1 ? 's' : ''; warning("Uses $cppc C++ style comment$s, which is not portable"); } my $s = $warnings != 1 ? 's' : ''; my $warn = $warnings ? " ($warnings warning$s)" : ''; info("Analysis completed$warn"); if ($file{changes}) { if (exists $opt{copy}) { my $newfile = "$filename$opt{copy}"; if (-e $newfile) { error("'$newfile' already exists, refusing to write copy of '$filename'"); } else { local *F; if (open F, ">$newfile") { info("Writing copy of '$filename' with changes to '$newfile'"); print F $c; close F; } else { error("Cannot open '$newfile' for writing: $!"); } } } elsif (exists $opt{patch} || $opt{changes}) { if (exists $opt{patch}) { unless ($patch_opened) { if (open PATCH, ">$opt{patch}") { $patch_opened = 1; } else { error("Cannot open '$opt{patch}' for writing: $!"); delete $opt{patch}; $opt{changes} = 1; goto fallback; } } mydiff(\*PATCH, $filename, $c); } else { fallback: info("Suggested changes:"); mydiff(\*STDOUT, $filename, $c); } } else { my $s = $file{changes} == 1 ? '' : 's'; info("$file{changes} potentially required change$s detected"); } } else { info("Looks good"); } } close PATCH if $patch_opened; exit 0; sub try_use { eval "use @_;"; return $@ eq '' } sub mydiff { local *F = shift; my($file, $str) = @_; my $diff; if (exists $opt{diff}) { $diff = run_diff($opt{diff}, $file, $str); } if (!defined $diff and try_use('Text::Diff')) { $diff = Text::Diff::diff($file, \$str, { STYLE => 'Unified' }); $diff = <
$tmp") { print F $str; close F; if (open F, "$prog $file $tmp |") { while () { s/\Q$tmp\E/$file.patched/; $diff .= $_; } close F; unlink $tmp; return $diff; } unlink $tmp; } else { error("Cannot open '$tmp' for writing: $!"); } return undef; } sub rec_depend { my($func, $seen) = @_; return () unless exists $depends{$func}; $seen = {%{$seen||{}}}; return () if $seen->{$func}++; my %s; grep !$s{$_}++, map { ($_, rec_depend($_, $seen)) } @{$depends{$func}}; } sub parse_version { my $ver = shift; if ($ver =~ /^(\d+)\.(\d+)\.(\d+)$/) { return ($1, $2, $3); } elsif ($ver !~ /^\d+\.[\d_]+$/) { die "cannot parse version '$ver'\n"; } $ver =~ s/_//g; $ver =~ s/$/000000/; my($r,$v,$s) = $ver =~ /(\d+)\.(\d{3})(\d{3})/; $v = int $v; $s = int $s; if ($r < 5 || ($r == 5 && $v < 6)) { if ($s % 10) { die "cannot parse version '$ver'\n"; } } return ($r, $v, $s); } sub format_version { my $ver = shift; $ver =~ s/$/000000/; my($r,$v,$s) = $ver =~ /(\d+)\.(\d{3})(\d{3})/; $v = int $v; $s = int $s; if ($r < 5 || ($r == 5 && $v < 6)) { if ($s % 10) { die "invalid version '$ver'\n"; } $s /= 10; $ver = sprintf "%d.%03d", $r, $v; $s > 0 and $ver .= sprintf "_%02d", $s; return $ver; } return sprintf "%d.%d.%d", $r, $v, $s; } sub info { $opt{quiet} and return; print @_, "\n"; } sub diag { $opt{quiet} and return; $opt{diag} and print @_, "\n"; } sub warning { $opt{quiet} and return; print "*** ", @_, "\n"; } sub error { print "*** ERROR: ", @_, "\n"; } my %given_hints; my %given_warnings; sub hint { $opt{quiet} and return; my $func = shift; my $rv = 0; if (exists $warnings{$func} && !$given_warnings{$func}++) { my $warn = $warnings{$func}; $warn =~ s!^!*** !mg; print "*** WARNING: $func\n", $warn; $rv++; } if ($opt{hints} && exists $hints{$func} && !$given_hints{$func}++) { my $hint = $hints{$func}; $hint =~ s/^/ /mg; print " --- hint for $func ---\n", $hint; } $rv; } sub usage { my($usage) = do { local(@ARGV,$/)=($0); <> } =~ /^=head\d$HS+SYNOPSIS\s*^(.*?)\s*^=/ms; my %M = ( 'I' => '*' ); $usage =~ s/^\s*perl\s+\S+/$^X $0/; $usage =~ s/([A-Z])<([^>]+)>/$M{$1}$2$M{$1}/g; print < }; my($copy) = $self =~ /^=head\d\s+COPYRIGHT\s*^(.*?)^=\w+/ms; $copy =~ s/^(?=\S+)/ /gms; $self =~ s/^$HS+Do NOT edit.*?(?=^-)/$copy/ms; $self =~ s/^SKIP.*(?=^__DATA__)/SKIP if (\@ARGV && \$ARGV[0] eq '--unstrip') { eval { require Devel::PPPort }; \$@ and die "Cannot require Devel::PPPort, please install.\\n"; if (eval \$Devel::PPPort::VERSION < $VERSION) { die "$0 was originally generated with Devel::PPPort $VERSION.\\n" . "Your Devel::PPPort is only version \$Devel::PPPort::VERSION.\\n" . "Please install a newer version, or --unstrip will not work.\\n"; } Devel::PPPort::WriteFile(\$0); exit 0; } print <$0" or die "cannot strip $0: $!\n"; print OUT "$pl$c\n"; exit 0; } __DATA__ */ #ifndef _P_P_PORTABILITY_H_ #define _P_P_PORTABILITY_H_ #ifndef DPPP_NAMESPACE # define DPPP_NAMESPACE DPPP_ #endif #define DPPP_CAT2(x,y) CAT2(x,y) #define DPPP_(name) DPPP_CAT2(DPPP_NAMESPACE, name) #ifndef PERL_REVISION # if !defined(__PATCHLEVEL_H_INCLUDED__) && !(defined(PATCHLEVEL) && defined(SUBVERSION)) # define PERL_PATCHLEVEL_H_IMPLICIT # include # endif # if !(defined(PERL_VERSION) || (defined(SUBVERSION) && defined(PATCHLEVEL))) # include # endif # ifndef PERL_REVISION # define PERL_REVISION (5) /* Replace: 1 */ # define PERL_VERSION PATCHLEVEL # define PERL_SUBVERSION SUBVERSION /* Replace PERL_PATCHLEVEL with PERL_VERSION */ /* Replace: 0 */ # endif #endif #define _dpppDEC2BCD(dec) ((((dec)/100)<<8)|((((dec)%100)/10)<<4)|((dec)%10)) #define PERL_BCDVERSION ((_dpppDEC2BCD(PERL_REVISION)<<24)|(_dpppDEC2BCD(PERL_VERSION)<<12)|_dpppDEC2BCD(PERL_SUBVERSION)) /* It is very unlikely that anyone will try to use this with Perl 6 (or greater), but who knows. */ #if PERL_REVISION != 5 # error ppport.h only works with Perl version 5 #endif /* PERL_REVISION != 5 */ #ifndef dTHR # define dTHR dNOOP #endif #ifndef dTHX # define dTHX dNOOP #endif #ifndef dTHXa # define dTHXa(x) dNOOP #endif #ifndef pTHX # define pTHX void #endif #ifndef pTHX_ # define pTHX_ #endif #ifndef aTHX # define aTHX #endif #ifndef aTHX_ # define aTHX_ #endif #if (PERL_BCDVERSION < 0x5006000) # ifdef USE_THREADS # define aTHXR thr # define aTHXR_ thr, # else # define aTHXR # define aTHXR_ # endif # define dTHXR dTHR #else # define aTHXR aTHX # define aTHXR_ aTHX_ # define dTHXR dTHX #endif #ifndef dTHXoa # define dTHXoa(x) dTHXa(x) #endif #ifdef I_LIMITS # include #endif #ifndef PERL_UCHAR_MIN # define PERL_UCHAR_MIN ((unsigned char)0) #endif #ifndef PERL_UCHAR_MAX # ifdef UCHAR_MAX # define PERL_UCHAR_MAX ((unsigned char)UCHAR_MAX) # else # ifdef MAXUCHAR # define PERL_UCHAR_MAX ((unsigned char)MAXUCHAR) # else # define PERL_UCHAR_MAX ((unsigned char)~(unsigned)0) # endif # endif #endif #ifndef PERL_USHORT_MIN # define PERL_USHORT_MIN ((unsigned short)0) #endif #ifndef PERL_USHORT_MAX # ifdef USHORT_MAX # define PERL_USHORT_MAX ((unsigned short)USHORT_MAX) # else # ifdef MAXUSHORT # define PERL_USHORT_MAX ((unsigned short)MAXUSHORT) # else # ifdef USHRT_MAX # define PERL_USHORT_MAX ((unsigned short)USHRT_MAX) # else # define PERL_USHORT_MAX ((unsigned short)~(unsigned)0) # endif # endif # endif #endif #ifndef PERL_SHORT_MAX # ifdef SHORT_MAX # define PERL_SHORT_MAX ((short)SHORT_MAX) # else # ifdef MAXSHORT /* Often used in */ # define PERL_SHORT_MAX ((short)MAXSHORT) # else # ifdef SHRT_MAX # define PERL_SHORT_MAX ((short)SHRT_MAX) # else # define PERL_SHORT_MAX ((short) (PERL_USHORT_MAX >> 1)) # endif # endif # endif #endif #ifndef PERL_SHORT_MIN # ifdef SHORT_MIN # define PERL_SHORT_MIN ((short)SHORT_MIN) # else # ifdef MINSHORT # define PERL_SHORT_MIN ((short)MINSHORT) # else # ifdef SHRT_MIN # define PERL_SHORT_MIN ((short)SHRT_MIN) # else # define PERL_SHORT_MIN (-PERL_SHORT_MAX - ((3 & -1) == 3)) # endif # endif # endif #endif #ifndef PERL_UINT_MAX # ifdef UINT_MAX # define PERL_UINT_MAX ((unsigned int)UINT_MAX) # else # ifdef MAXUINT # define PERL_UINT_MAX ((unsigned int)MAXUINT) # else # define PERL_UINT_MAX (~(unsigned int)0) # endif # endif #endif #ifndef PERL_UINT_MIN # define PERL_UINT_MIN ((unsigned int)0) #endif #ifndef PERL_INT_MAX # ifdef INT_MAX # define PERL_INT_MAX ((int)INT_MAX) # else # ifdef MAXINT /* Often used in */ # define PERL_INT_MAX ((int)MAXINT) # else # define PERL_INT_MAX ((int)(PERL_UINT_MAX >> 1)) # endif # endif #endif #ifndef PERL_INT_MIN # ifdef INT_MIN # define PERL_INT_MIN ((int)INT_MIN) # else # ifdef MININT # define PERL_INT_MIN ((int)MININT) # else # define PERL_INT_MIN (-PERL_INT_MAX - ((3 & -1) == 3)) # endif # endif #endif #ifndef PERL_ULONG_MAX # ifdef ULONG_MAX # define PERL_ULONG_MAX ((unsigned long)ULONG_MAX) # else # ifdef MAXULONG # define PERL_ULONG_MAX ((unsigned long)MAXULONG) # else # define PERL_ULONG_MAX (~(unsigned long)0) # endif # endif #endif #ifndef PERL_ULONG_MIN # define PERL_ULONG_MIN ((unsigned long)0L) #endif #ifndef PERL_LONG_MAX # ifdef LONG_MAX # define PERL_LONG_MAX ((long)LONG_MAX) # else # ifdef MAXLONG # define PERL_LONG_MAX ((long)MAXLONG) # else # define PERL_LONG_MAX ((long) (PERL_ULONG_MAX >> 1)) # endif # endif #endif #ifndef PERL_LONG_MIN # ifdef LONG_MIN # define PERL_LONG_MIN ((long)LONG_MIN) # else # ifdef MINLONG # define PERL_LONG_MIN ((long)MINLONG) # else # define PERL_LONG_MIN (-PERL_LONG_MAX - ((3 & -1) == 3)) # endif # endif #endif #if defined(HAS_QUAD) && (defined(convex) || defined(uts)) # ifndef PERL_UQUAD_MAX # ifdef ULONGLONG_MAX # define PERL_UQUAD_MAX ((unsigned long long)ULONGLONG_MAX) # else # ifdef MAXULONGLONG # define PERL_UQUAD_MAX ((unsigned long long)MAXULONGLONG) # else # define PERL_UQUAD_MAX (~(unsigned long long)0) # endif # endif # endif # ifndef PERL_UQUAD_MIN # define PERL_UQUAD_MIN ((unsigned long long)0L) # endif # ifndef PERL_QUAD_MAX # ifdef LONGLONG_MAX # define PERL_QUAD_MAX ((long long)LONGLONG_MAX) # else # ifdef MAXLONGLONG # define PERL_QUAD_MAX ((long long)MAXLONGLONG) # else # define PERL_QUAD_MAX ((long long) (PERL_UQUAD_MAX >> 1)) # endif # endif # endif # ifndef PERL_QUAD_MIN # ifdef LONGLONG_MIN # define PERL_QUAD_MIN ((long long)LONGLONG_MIN) # else # ifdef MINLONGLONG # define PERL_QUAD_MIN ((long long)MINLONGLONG) # else # define PERL_QUAD_MIN (-PERL_QUAD_MAX - ((3 & -1) == 3)) # endif # endif # endif #endif /* This is based on code from 5.003 perl.h */ #ifdef HAS_QUAD # ifdef cray #ifndef IVTYPE # define IVTYPE int #endif #ifndef IV_MIN # define IV_MIN PERL_INT_MIN #endif #ifndef IV_MAX # define IV_MAX PERL_INT_MAX #endif #ifndef UV_MIN # define UV_MIN PERL_UINT_MIN #endif #ifndef UV_MAX # define UV_MAX PERL_UINT_MAX #endif # ifdef INTSIZE #ifndef IVSIZE # define IVSIZE INTSIZE #endif # endif # else # if defined(convex) || defined(uts) #ifndef IVTYPE # define IVTYPE long long #endif #ifndef IV_MIN # define IV_MIN PERL_QUAD_MIN #endif #ifndef IV_MAX # define IV_MAX PERL_QUAD_MAX #endif #ifndef UV_MIN # define UV_MIN PERL_UQUAD_MIN #endif #ifndef UV_MAX # define UV_MAX PERL_UQUAD_MAX #endif # ifdef LONGLONGSIZE #ifndef IVSIZE # define IVSIZE LONGLONGSIZE #endif # endif # else #ifndef IVTYPE # define IVTYPE long #endif #ifndef IV_MIN # define IV_MIN PERL_LONG_MIN #endif #ifndef IV_MAX # define IV_MAX PERL_LONG_MAX #endif #ifndef UV_MIN # define UV_MIN PERL_ULONG_MIN #endif #ifndef UV_MAX # define UV_MAX PERL_ULONG_MAX #endif # ifdef LONGSIZE #ifndef IVSIZE # define IVSIZE LONGSIZE #endif # endif # endif # endif #ifndef IVSIZE # define IVSIZE 8 #endif #ifndef LONGSIZE # define LONGSIZE 8 #endif #ifndef PERL_QUAD_MIN # define PERL_QUAD_MIN IV_MIN #endif #ifndef PERL_QUAD_MAX # define PERL_QUAD_MAX IV_MAX #endif #ifndef PERL_UQUAD_MIN # define PERL_UQUAD_MIN UV_MIN #endif #ifndef PERL_UQUAD_MAX # define PERL_UQUAD_MAX UV_MAX #endif #else #ifndef IVTYPE # define IVTYPE long #endif #ifndef LONGSIZE # define LONGSIZE 4 #endif #ifndef IV_MIN # define IV_MIN PERL_LONG_MIN #endif #ifndef IV_MAX # define IV_MAX PERL_LONG_MAX #endif #ifndef UV_MIN # define UV_MIN PERL_ULONG_MIN #endif #ifndef UV_MAX # define UV_MAX PERL_ULONG_MAX #endif #endif #ifndef IVSIZE # ifdef LONGSIZE # define IVSIZE LONGSIZE # else # define IVSIZE 4 /* A bold guess, but the best we can make. */ # endif #endif #ifndef UVTYPE # define UVTYPE unsigned IVTYPE #endif #ifndef UVSIZE # define UVSIZE IVSIZE #endif #ifndef sv_setuv # define sv_setuv(sv, uv) \ STMT_START { \ UV TeMpUv = uv; \ if (TeMpUv <= IV_MAX) \ sv_setiv(sv, TeMpUv); \ else \ sv_setnv(sv, (double)TeMpUv); \ } STMT_END #endif #ifndef newSVuv # define newSVuv(uv) ((uv) <= IV_MAX ? newSViv((IV)uv) : newSVnv((NV)uv)) #endif #ifndef sv_2uv # define sv_2uv(sv) ((PL_Sv = (sv)), (UV) (SvNOK(PL_Sv) ? SvNV(PL_Sv) : sv_2nv(PL_Sv))) #endif #ifndef SvUVX # define SvUVX(sv) ((UV)SvIVX(sv)) #endif #ifndef SvUVXx # define SvUVXx(sv) SvUVX(sv) #endif #ifndef SvUV # define SvUV(sv) (SvIOK(sv) ? SvUVX(sv) : sv_2uv(sv)) #endif #ifndef SvUVx # define SvUVx(sv) ((PL_Sv = (sv)), SvUV(PL_Sv)) #endif /* Hint: sv_uv * Always use the SvUVx() macro instead of sv_uv(). */ #ifndef sv_uv # define sv_uv(sv) SvUVx(sv) #endif #if !defined(SvUOK) && defined(SvIOK_UV) # define SvUOK(sv) SvIOK_UV(sv) #endif #ifndef XST_mUV # define XST_mUV(i,v) (ST(i) = sv_2mortal(newSVuv(v)) ) #endif #ifndef XSRETURN_UV # define XSRETURN_UV(v) STMT_START { XST_mUV(0,v); XSRETURN(1); } STMT_END #endif #ifndef PUSHu # define PUSHu(u) STMT_START { sv_setuv(TARG, (UV)(u)); PUSHTARG; } STMT_END #endif #ifndef XPUSHu # define XPUSHu(u) STMT_START { sv_setuv(TARG, (UV)(u)); XPUSHTARG; } STMT_END #endif #ifdef HAS_MEMCMP #ifndef memNE # define memNE(s1,s2,l) (memcmp(s1,s2,l)) #endif #ifndef memEQ # define memEQ(s1,s2,l) (!memcmp(s1,s2,l)) #endif #else #ifndef memNE # define memNE(s1,s2,l) (bcmp(s1,s2,l)) #endif #ifndef memEQ # define memEQ(s1,s2,l) (!bcmp(s1,s2,l)) #endif #endif #ifndef memEQs # define memEQs(s1, l, s2) \ (sizeof(s2)-1 == l && memEQ(s1, (s2 ""), (sizeof(s2)-1))) #endif #ifndef memNEs # define memNEs(s1, l, s2) !memEQs(s1, l, s2) #endif #ifndef MoveD # define MoveD(s,d,n,t) memmove((char*)(d),(char*)(s), (n) * sizeof(t)) #endif #ifndef CopyD # define CopyD(s,d,n,t) memcpy((char*)(d),(char*)(s), (n) * sizeof(t)) #endif #ifdef HAS_MEMSET #ifndef ZeroD # define ZeroD(d,n,t) memzero((char*)(d), (n) * sizeof(t)) #endif #else #ifndef ZeroD # define ZeroD(d,n,t) ((void)memzero((char*)(d), (n) * sizeof(t)), d) #endif #endif #ifndef PoisonWith # define PoisonWith(d,n,t,b) (void)memset((char*)(d), (U8)(b), (n) * sizeof(t)) #endif #ifndef PoisonNew # define PoisonNew(d,n,t) PoisonWith(d,n,t,0xAB) #endif #ifndef PoisonFree # define PoisonFree(d,n,t) PoisonWith(d,n,t,0xEF) #endif #ifndef Poison # define Poison(d,n,t) PoisonFree(d,n,t) #endif #ifndef Newx # define Newx(v,n,t) New(0,v,n,t) #endif #ifndef Newxc # define Newxc(v,n,t,c) Newc(0,v,n,t,c) #endif #ifndef Newxz # define Newxz(v,n,t) Newz(0,v,n,t) #endif #ifndef PERL_UNUSED_DECL # ifdef HASATTRIBUTE # if (defined(__GNUC__) && defined(__cplusplus)) || defined(__INTEL_COMPILER) # define PERL_UNUSED_DECL # else # define PERL_UNUSED_DECL __attribute__((unused)) # endif # else # define PERL_UNUSED_DECL # endif #endif #ifndef PERL_UNUSED_ARG # if defined(lint) && defined(S_SPLINT_S) /* www.splint.org */ # include # define PERL_UNUSED_ARG(x) NOTE(ARGUNUSED(x)) # else # define PERL_UNUSED_ARG(x) ((void)x) # endif #endif #ifndef PERL_UNUSED_VAR # define PERL_UNUSED_VAR(x) ((void)x) #endif #ifndef PERL_UNUSED_CONTEXT # ifdef USE_ITHREADS # define PERL_UNUSED_CONTEXT PERL_UNUSED_ARG(my_perl) # else # define PERL_UNUSED_CONTEXT # endif #endif #ifndef NOOP # define NOOP /*EMPTY*/(void)0 #endif #ifndef dNOOP # define dNOOP extern int /*@unused@*/ Perl___notused PERL_UNUSED_DECL #endif #ifndef NVTYPE # if defined(USE_LONG_DOUBLE) && defined(HAS_LONG_DOUBLE) # define NVTYPE long double # else # define NVTYPE double # endif typedef NVTYPE NV; #endif #ifndef INT2PTR # if (IVSIZE == PTRSIZE) && (UVSIZE == PTRSIZE) # define PTRV UV # define INT2PTR(any,d) (any)(d) # else # if PTRSIZE == LONGSIZE # define PTRV unsigned long # else # define PTRV unsigned # endif # define INT2PTR(any,d) (any)(PTRV)(d) # endif #endif #ifndef PTR2ul # if PTRSIZE == LONGSIZE # define PTR2ul(p) (unsigned long)(p) # else # define PTR2ul(p) INT2PTR(unsigned long,p) # endif #endif #ifndef PTR2nat # define PTR2nat(p) (PTRV)(p) #endif #ifndef NUM2PTR # define NUM2PTR(any,d) (any)PTR2nat(d) #endif #ifndef PTR2IV # define PTR2IV(p) INT2PTR(IV,p) #endif #ifndef PTR2UV # define PTR2UV(p) INT2PTR(UV,p) #endif #ifndef PTR2NV # define PTR2NV(p) NUM2PTR(NV,p) #endif #undef START_EXTERN_C #undef END_EXTERN_C #undef EXTERN_C #ifdef __cplusplus # define START_EXTERN_C extern "C" { # define END_EXTERN_C } # define EXTERN_C extern "C" #else # define START_EXTERN_C # define END_EXTERN_C # define EXTERN_C extern #endif #if defined(PERL_GCC_PEDANTIC) # ifndef PERL_GCC_BRACE_GROUPS_FORBIDDEN # define PERL_GCC_BRACE_GROUPS_FORBIDDEN # endif #endif #if defined(__GNUC__) && !defined(PERL_GCC_BRACE_GROUPS_FORBIDDEN) && !defined(__cplusplus) # ifndef PERL_USE_GCC_BRACE_GROUPS # define PERL_USE_GCC_BRACE_GROUPS # endif #endif #undef STMT_START #undef STMT_END #ifdef PERL_USE_GCC_BRACE_GROUPS # define STMT_START (void)( /* gcc supports ``({ STATEMENTS; })'' */ # define STMT_END ) #else # if defined(VOIDFLAGS) && (VOIDFLAGS) && (defined(sun) || defined(__sun__)) && !defined(__GNUC__) # define STMT_START if (1) # define STMT_END else (void)0 # else # define STMT_START do # define STMT_END while (0) # endif #endif #ifndef boolSV # define boolSV(b) ((b) ? &PL_sv_yes : &PL_sv_no) #endif /* DEFSV appears first in 5.004_56 */ #ifndef DEFSV # define DEFSV GvSV(PL_defgv) #endif #ifndef SAVE_DEFSV # define SAVE_DEFSV SAVESPTR(GvSV(PL_defgv)) #endif #ifndef DEFSV_set # define DEFSV_set(sv) (DEFSV = (sv)) #endif /* Older perls (<=5.003) lack AvFILLp */ #ifndef AvFILLp # define AvFILLp AvFILL #endif #ifndef ERRSV # define ERRSV get_sv("@",FALSE) #endif /* Hint: gv_stashpvn * This function's backport doesn't support the length parameter, but * rather ignores it. Portability can only be ensured if the length * parameter is used for speed reasons, but the length can always be * correctly computed from the string argument. */ #ifndef gv_stashpvn # define gv_stashpvn(str,len,create) gv_stashpv(str,create) #endif /* Replace: 1 */ #ifndef get_cv # define get_cv perl_get_cv #endif #ifndef get_sv # define get_sv perl_get_sv #endif #ifndef get_av # define get_av perl_get_av #endif #ifndef get_hv # define get_hv perl_get_hv #endif /* Replace: 0 */ #ifndef dUNDERBAR # define dUNDERBAR dNOOP #endif #ifndef UNDERBAR # define UNDERBAR DEFSV #endif #ifndef dAX # define dAX I32 ax = MARK - PL_stack_base + 1 #endif #ifndef dITEMS # define dITEMS I32 items = SP - MARK #endif #ifndef dXSTARG # define dXSTARG SV * targ = sv_newmortal() #endif #ifndef dAXMARK # define dAXMARK I32 ax = POPMARK; \ register SV ** const mark = PL_stack_base + ax++ #endif #ifndef XSprePUSH # define XSprePUSH (sp = PL_stack_base + ax - 1) #endif #if (PERL_BCDVERSION < 0x5005000) # undef XSRETURN # define XSRETURN(off) \ STMT_START { \ PL_stack_sp = PL_stack_base + ax + ((off) - 1); \ return; \ } STMT_END #endif #ifndef XSPROTO # define XSPROTO(name) void name(pTHX_ CV* cv) #endif #ifndef SVfARG # define SVfARG(p) ((void*)(p)) #endif #ifndef PERL_ABS # define PERL_ABS(x) ((x) < 0 ? -(x) : (x)) #endif #ifndef dVAR # define dVAR dNOOP #endif #ifndef SVf # define SVf "_" #endif #ifndef UTF8_MAXBYTES # define UTF8_MAXBYTES UTF8_MAXLEN #endif #ifndef CPERLscope # define CPERLscope(x) x #endif #ifndef PERL_HASH # define PERL_HASH(hash,str,len) \ STMT_START { \ const char *s_PeRlHaSh = str; \ I32 i_PeRlHaSh = len; \ U32 hash_PeRlHaSh = 0; \ while (i_PeRlHaSh--) \ hash_PeRlHaSh = hash_PeRlHaSh * 33 + *s_PeRlHaSh++; \ (hash) = hash_PeRlHaSh; \ } STMT_END #endif #ifndef PERLIO_FUNCS_DECL # ifdef PERLIO_FUNCS_CONST # define PERLIO_FUNCS_DECL(funcs) const PerlIO_funcs funcs # define PERLIO_FUNCS_CAST(funcs) (PerlIO_funcs*)(funcs) # else # define PERLIO_FUNCS_DECL(funcs) PerlIO_funcs funcs # define PERLIO_FUNCS_CAST(funcs) (funcs) # endif #endif /* provide these typedefs for older perls */ #if (PERL_BCDVERSION < 0x5009003) # ifdef ARGSproto typedef OP* (CPERLscope(*Perl_ppaddr_t))(ARGSproto); # else typedef OP* (CPERLscope(*Perl_ppaddr_t))(pTHX); # endif typedef OP* (CPERLscope(*Perl_check_t)) (pTHX_ OP*); #endif #ifndef isPSXSPC # define isPSXSPC(c) (isSPACE(c) || (c) == '\v') #endif #ifndef isBLANK # define isBLANK(c) ((c) == ' ' || (c) == '\t') #endif #ifdef EBCDIC #ifndef isALNUMC # define isALNUMC(c) isalnum(c) #endif #ifndef isASCII # define isASCII(c) isascii(c) #endif #ifndef isCNTRL # define isCNTRL(c) iscntrl(c) #endif #ifndef isGRAPH # define isGRAPH(c) isgraph(c) #endif #ifndef isPRINT # define isPRINT(c) isprint(c) #endif #ifndef isPUNCT # define isPUNCT(c) ispunct(c) #endif #ifndef isXDIGIT # define isXDIGIT(c) isxdigit(c) #endif #else # if (PERL_BCDVERSION < 0x5010000) /* Hint: isPRINT * The implementation in older perl versions includes all of the * isSPACE() characters, which is wrong. The version provided by * Devel::PPPort always overrides a present buggy version. */ # undef isPRINT # endif #ifdef HAS_QUAD # ifdef U64TYPE # define WIDEST_UTYPE U64TYPE # else # define WIDEST_UTYPE Quad_t # endif #else # define WIDEST_UTYPE U32 #endif #ifndef isALNUMC # define isALNUMC(c) (isALPHA(c) || isDIGIT(c)) #endif #ifndef isASCII # define isASCII(c) ((WIDEST_UTYPE) (c) <= 127) #endif #ifndef isCNTRL # define isCNTRL(c) ((WIDEST_UTYPE) (c) < ' ' || (c) == 127) #endif #ifndef isGRAPH # define isGRAPH(c) (isALNUM(c) || isPUNCT(c)) #endif #ifndef isPRINT # define isPRINT(c) (((c) >= 32 && (c) < 127)) #endif #ifndef isPUNCT # define isPUNCT(c) (((c) >= 33 && (c) <= 47) || ((c) >= 58 && (c) <= 64) || ((c) >= 91 && (c) <= 96) || ((c) >= 123 && (c) <= 126)) #endif #ifndef isXDIGIT # define isXDIGIT(c) (isDIGIT(c) || ((c) >= 'a' && (c) <= 'f') || ((c) >= 'A' && (c) <= 'F')) #endif #endif /* Until we figure out how to support this in older perls... */ #if (PERL_BCDVERSION >= 0x5008000) #ifndef HeUTF8 # define HeUTF8(he) ((HeKLEN(he) == HEf_SVKEY) ? \ SvUTF8(HeKEY_sv(he)) : \ (U32)HeKUTF8(he)) #endif #endif #ifndef PERL_SIGNALS_UNSAFE_FLAG #define PERL_SIGNALS_UNSAFE_FLAG 0x0001 #if (PERL_BCDVERSION < 0x5008000) # define D_PPP_PERL_SIGNALS_INIT PERL_SIGNALS_UNSAFE_FLAG #else # define D_PPP_PERL_SIGNALS_INIT 0 #endif #if defined(NEED_PL_signals) static U32 DPPP_(my_PL_signals) = D_PPP_PERL_SIGNALS_INIT; #elif defined(NEED_PL_signals_GLOBAL) U32 DPPP_(my_PL_signals) = D_PPP_PERL_SIGNALS_INIT; #else extern U32 DPPP_(my_PL_signals); #endif #define PL_signals DPPP_(my_PL_signals) #endif /* Hint: PL_ppaddr * Calling an op via PL_ppaddr requires passing a context argument * for threaded builds. Since the context argument is different for * 5.005 perls, you can use aTHXR (supplied by ppport.h), which will * automatically be defined as the correct argument. */ #if (PERL_BCDVERSION <= 0x5005005) /* Replace: 1 */ # define PL_ppaddr ppaddr # define PL_no_modify no_modify /* Replace: 0 */ #endif #if (PERL_BCDVERSION <= 0x5004005) /* Replace: 1 */ # define PL_DBsignal DBsignal # define PL_DBsingle DBsingle # define PL_DBsub DBsub # define PL_DBtrace DBtrace # define PL_Sv Sv # define PL_bufend bufend # define PL_bufptr bufptr # define PL_compiling compiling # define PL_copline copline # define PL_curcop curcop # define PL_curstash curstash # define PL_debstash debstash # define PL_defgv defgv # define PL_diehook diehook # define PL_dirty dirty # define PL_dowarn dowarn # define PL_errgv errgv # define PL_error_count error_count # define PL_expect expect # define PL_hexdigit hexdigit # define PL_hints hints # define PL_in_my in_my # define PL_laststatval laststatval # define PL_lex_state lex_state # define PL_lex_stuff lex_stuff # define PL_linestr linestr # define PL_na na # define PL_perl_destruct_level perl_destruct_level # define PL_perldb perldb # define PL_rsfp_filters rsfp_filters # define PL_rsfp rsfp # define PL_stack_base stack_base # define PL_stack_sp stack_sp # define PL_statcache statcache # define PL_stdingv stdingv # define PL_sv_arenaroot sv_arenaroot # define PL_sv_no sv_no # define PL_sv_undef sv_undef # define PL_sv_yes sv_yes # define PL_tainted tainted # define PL_tainting tainting # define PL_tokenbuf tokenbuf /* Replace: 0 */ #endif /* Warning: PL_parser * For perl versions earlier than 5.9.5, this is an always * non-NULL dummy. Also, it cannot be dereferenced. Don't * use it if you can avoid is and unless you absolutely know * what you're doing. * If you always check that PL_parser is non-NULL, you can * define DPPP_PL_parser_NO_DUMMY to avoid the creation of * a dummy parser structure. */ #if (PERL_BCDVERSION >= 0x5009005) # ifdef DPPP_PL_parser_NO_DUMMY # define D_PPP_my_PL_parser_var(var) ((PL_parser ? PL_parser : \ (croak("panic: PL_parser == NULL in %s:%d", \ __FILE__, __LINE__), (yy_parser *) NULL))->var) # else # ifdef DPPP_PL_parser_NO_DUMMY_WARNING # define D_PPP_parser_dummy_warning(var) # else # define D_PPP_parser_dummy_warning(var) \ warn("warning: dummy PL_" #var " used in %s:%d", __FILE__, __LINE__), # endif # define D_PPP_my_PL_parser_var(var) ((PL_parser ? PL_parser : \ (D_PPP_parser_dummy_warning(var) &DPPP_(dummy_PL_parser)))->var) #if defined(NEED_PL_parser) static yy_parser DPPP_(dummy_PL_parser); #elif defined(NEED_PL_parser_GLOBAL) yy_parser DPPP_(dummy_PL_parser); #else extern yy_parser DPPP_(dummy_PL_parser); #endif # endif /* PL_expect, PL_copline, PL_rsfp, PL_rsfp_filters, PL_linestr, PL_bufptr, PL_bufend, PL_lex_state, PL_lex_stuff, PL_tokenbuf depends on PL_parser */ /* Warning: PL_expect, PL_copline, PL_rsfp, PL_rsfp_filters, PL_linestr, PL_bufptr, PL_bufend, PL_lex_state, PL_lex_stuff, PL_tokenbuf * Do not use this variable unless you know exactly what you're * doint. It is internal to the perl parser and may change or even * be removed in the future. As of perl 5.9.5, you have to check * for (PL_parser != NULL) for this variable to have any effect. * An always non-NULL PL_parser dummy is provided for earlier * perl versions. * If PL_parser is NULL when you try to access this variable, a * dummy is being accessed instead and a warning is issued unless * you define DPPP_PL_parser_NO_DUMMY_WARNING. * If DPPP_PL_parser_NO_DUMMY is defined, the code trying to access * this variable will croak with a panic message. */ # define PL_expect D_PPP_my_PL_parser_var(expect) # define PL_copline D_PPP_my_PL_parser_var(copline) # define PL_rsfp D_PPP_my_PL_parser_var(rsfp) # define PL_rsfp_filters D_PPP_my_PL_parser_var(rsfp_filters) # define PL_linestr D_PPP_my_PL_parser_var(linestr) # define PL_bufptr D_PPP_my_PL_parser_var(bufptr) # define PL_bufend D_PPP_my_PL_parser_var(bufend) # define PL_lex_state D_PPP_my_PL_parser_var(lex_state) # define PL_lex_stuff D_PPP_my_PL_parser_var(lex_stuff) # define PL_tokenbuf D_PPP_my_PL_parser_var(tokenbuf) # define PL_in_my D_PPP_my_PL_parser_var(in_my) # define PL_in_my_stash D_PPP_my_PL_parser_var(in_my_stash) # define PL_error_count D_PPP_my_PL_parser_var(error_count) #else /* ensure that PL_parser != NULL and cannot be dereferenced */ # define PL_parser ((void *) 1) #endif #ifndef mPUSHs # define mPUSHs(s) PUSHs(sv_2mortal(s)) #endif #ifndef PUSHmortal # define PUSHmortal PUSHs(sv_newmortal()) #endif #ifndef mPUSHp # define mPUSHp(p,l) sv_setpvn(PUSHmortal, (p), (l)) #endif #ifndef mPUSHn # define mPUSHn(n) sv_setnv(PUSHmortal, (NV)(n)) #endif #ifndef mPUSHi # define mPUSHi(i) sv_setiv(PUSHmortal, (IV)(i)) #endif #ifndef mPUSHu # define mPUSHu(u) sv_setuv(PUSHmortal, (UV)(u)) #endif #ifndef mXPUSHs # define mXPUSHs(s) XPUSHs(sv_2mortal(s)) #endif #ifndef XPUSHmortal # define XPUSHmortal XPUSHs(sv_newmortal()) #endif #ifndef mXPUSHp # define mXPUSHp(p,l) STMT_START { EXTEND(sp,1); sv_setpvn(PUSHmortal, (p), (l)); } STMT_END #endif #ifndef mXPUSHn # define mXPUSHn(n) STMT_START { EXTEND(sp,1); sv_setnv(PUSHmortal, (NV)(n)); } STMT_END #endif #ifndef mXPUSHi # define mXPUSHi(i) STMT_START { EXTEND(sp,1); sv_setiv(PUSHmortal, (IV)(i)); } STMT_END #endif #ifndef mXPUSHu # define mXPUSHu(u) STMT_START { EXTEND(sp,1); sv_setuv(PUSHmortal, (UV)(u)); } STMT_END #endif /* Replace: 1 */ #ifndef call_sv # define call_sv perl_call_sv #endif #ifndef call_pv # define call_pv perl_call_pv #endif #ifndef call_argv # define call_argv perl_call_argv #endif #ifndef call_method # define call_method perl_call_method #endif #ifndef eval_sv # define eval_sv perl_eval_sv #endif /* Replace: 0 */ #ifndef PERL_LOADMOD_DENY # define PERL_LOADMOD_DENY 0x1 #endif #ifndef PERL_LOADMOD_NOIMPORT # define PERL_LOADMOD_NOIMPORT 0x2 #endif #ifndef PERL_LOADMOD_IMPORT_OPS # define PERL_LOADMOD_IMPORT_OPS 0x4 #endif #ifndef G_METHOD # define G_METHOD 64 # ifdef call_sv # undef call_sv # endif # if (PERL_BCDVERSION < 0x5006000) # define call_sv(sv, flags) ((flags) & G_METHOD ? perl_call_method((char *) SvPV_nolen_const(sv), \ (flags) & ~G_METHOD) : perl_call_sv(sv, flags)) # else # define call_sv(sv, flags) ((flags) & G_METHOD ? Perl_call_method(aTHX_ (char *) SvPV_nolen_const(sv), \ (flags) & ~G_METHOD) : Perl_call_sv(aTHX_ sv, flags)) # endif #endif /* Replace perl_eval_pv with eval_pv */ #ifndef eval_pv #if defined(NEED_eval_pv) static SV* DPPP_(my_eval_pv)(char *p, I32 croak_on_error); static #else extern SV* DPPP_(my_eval_pv)(char *p, I32 croak_on_error); #endif #ifdef eval_pv # undef eval_pv #endif #define eval_pv(a,b) DPPP_(my_eval_pv)(aTHX_ a,b) #define Perl_eval_pv DPPP_(my_eval_pv) #if defined(NEED_eval_pv) || defined(NEED_eval_pv_GLOBAL) SV* DPPP_(my_eval_pv)(char *p, I32 croak_on_error) { dSP; SV* sv = newSVpv(p, 0); PUSHMARK(sp); eval_sv(sv, G_SCALAR); SvREFCNT_dec(sv); SPAGAIN; sv = POPs; PUTBACK; if (croak_on_error && SvTRUE(GvSV(errgv))) croak(SvPVx(GvSV(errgv), na)); return sv; } #endif #endif #ifndef vload_module #if defined(NEED_vload_module) static void DPPP_(my_vload_module)(U32 flags, SV *name, SV *ver, va_list *args); static #else extern void DPPP_(my_vload_module)(U32 flags, SV *name, SV *ver, va_list *args); #endif #ifdef vload_module # undef vload_module #endif #define vload_module(a,b,c,d) DPPP_(my_vload_module)(aTHX_ a,b,c,d) #define Perl_vload_module DPPP_(my_vload_module) #if defined(NEED_vload_module) || defined(NEED_vload_module_GLOBAL) void DPPP_(my_vload_module)(U32 flags, SV *name, SV *ver, va_list *args) { dTHR; dVAR; OP *veop, *imop; OP * const modname = newSVOP(OP_CONST, 0, name); /* 5.005 has a somewhat hacky force_normal that doesn't croak on SvREADONLY() if PL_compling is true. Current perls take care in ck_require() to correctly turn off SvREADONLY before calling force_normal_flags(). This seems a better fix than fudging PL_compling */ SvREADONLY_off(((SVOP*)modname)->op_sv); modname->op_private |= OPpCONST_BARE; if (ver) { veop = newSVOP(OP_CONST, 0, ver); } else veop = NULL; if (flags & PERL_LOADMOD_NOIMPORT) { imop = sawparens(newNULLLIST()); } else if (flags & PERL_LOADMOD_IMPORT_OPS) { imop = va_arg(*args, OP*); } else { SV *sv; imop = NULL; sv = va_arg(*args, SV*); while (sv) { imop = append_elem(OP_LIST, imop, newSVOP(OP_CONST, 0, sv)); sv = va_arg(*args, SV*); } } { const line_t ocopline = PL_copline; COP * const ocurcop = PL_curcop; const int oexpect = PL_expect; #if (PERL_BCDVERSION >= 0x5004000) utilize(!(flags & PERL_LOADMOD_DENY), start_subparse(FALSE, 0), veop, modname, imop); #elif (PERL_BCDVERSION > 0x5003000) utilize(!(flags & PERL_LOADMOD_DENY), start_subparse(), veop, modname, imop); #else utilize(!(flags & PERL_LOADMOD_DENY), start_subparse(), modname, imop); #endif PL_expect = oexpect; PL_copline = ocopline; PL_curcop = ocurcop; } } #endif #endif #ifndef load_module #if defined(NEED_load_module) static void DPPP_(my_load_module)(U32 flags, SV *name, SV *ver, ...); static #else extern void DPPP_(my_load_module)(U32 flags, SV *name, SV *ver, ...); #endif #ifdef load_module # undef load_module #endif #define load_module DPPP_(my_load_module) #define Perl_load_module DPPP_(my_load_module) #if defined(NEED_load_module) || defined(NEED_load_module_GLOBAL) void DPPP_(my_load_module)(U32 flags, SV *name, SV *ver, ...) { va_list args; va_start(args, ver); vload_module(flags, name, ver, &args); va_end(args); } #endif #endif #ifndef newRV_inc # define newRV_inc(sv) newRV(sv) /* Replace */ #endif #ifndef newRV_noinc #if defined(NEED_newRV_noinc) static SV * DPPP_(my_newRV_noinc)(SV *sv); static #else extern SV * DPPP_(my_newRV_noinc)(SV *sv); #endif #ifdef newRV_noinc # undef newRV_noinc #endif #define newRV_noinc(a) DPPP_(my_newRV_noinc)(aTHX_ a) #define Perl_newRV_noinc DPPP_(my_newRV_noinc) #if defined(NEED_newRV_noinc) || defined(NEED_newRV_noinc_GLOBAL) SV * DPPP_(my_newRV_noinc)(SV *sv) { SV *rv = (SV *)newRV(sv); SvREFCNT_dec(sv); return rv; } #endif #endif /* Hint: newCONSTSUB * Returns a CV* as of perl-5.7.1. This return value is not supported * by Devel::PPPort. */ /* newCONSTSUB from IO.xs is in the core starting with 5.004_63 */ #if (PERL_BCDVERSION < 0x5004063) && (PERL_BCDVERSION != 0x5004005) #if defined(NEED_newCONSTSUB) static void DPPP_(my_newCONSTSUB)(HV *stash, const char *name, SV *sv); static #else extern void DPPP_(my_newCONSTSUB)(HV *stash, const char *name, SV *sv); #endif #ifdef newCONSTSUB # undef newCONSTSUB #endif #define newCONSTSUB(a,b,c) DPPP_(my_newCONSTSUB)(aTHX_ a,b,c) #define Perl_newCONSTSUB DPPP_(my_newCONSTSUB) #if defined(NEED_newCONSTSUB) || defined(NEED_newCONSTSUB_GLOBAL) /* This is just a trick to avoid a dependency of newCONSTSUB on PL_parser */ /* (There's no PL_parser in perl < 5.005, so this is completely safe) */ #define D_PPP_PL_copline PL_copline void DPPP_(my_newCONSTSUB)(HV *stash, const char *name, SV *sv) { U32 oldhints = PL_hints; HV *old_cop_stash = PL_curcop->cop_stash; HV *old_curstash = PL_curstash; line_t oldline = PL_curcop->cop_line; PL_curcop->cop_line = D_PPP_PL_copline; PL_hints &= ~HINT_BLOCK_SCOPE; if (stash) PL_curstash = PL_curcop->cop_stash = stash; newSUB( #if (PERL_BCDVERSION < 0x5003022) start_subparse(), #elif (PERL_BCDVERSION == 0x5003022) start_subparse(0), #else /* 5.003_23 onwards */ start_subparse(FALSE, 0), #endif newSVOP(OP_CONST, 0, newSVpv((char *) name, 0)), newSVOP(OP_CONST, 0, &PL_sv_no), /* SvPV(&PL_sv_no) == "" -- GMB */ newSTATEOP(0, Nullch, newSVOP(OP_CONST, 0, sv)) ); PL_hints = oldhints; PL_curcop->cop_stash = old_cop_stash; PL_curstash = old_curstash; PL_curcop->cop_line = oldline; } #endif #endif /* * Boilerplate macros for initializing and accessing interpreter-local * data from C. All statics in extensions should be reworked to use * this, if you want to make the extension thread-safe. See ext/re/re.xs * for an example of the use of these macros. * * Code that uses these macros is responsible for the following: * 1. #define MY_CXT_KEY to a unique string, e.g. "DynaLoader_guts" * 2. Declare a typedef named my_cxt_t that is a structure that contains * all the data that needs to be interpreter-local. * 3. Use the START_MY_CXT macro after the declaration of my_cxt_t. * 4. Use the MY_CXT_INIT macro such that it is called exactly once * (typically put in the BOOT: section). * 5. Use the members of the my_cxt_t structure everywhere as * MY_CXT.member. * 6. Use the dMY_CXT macro (a declaration) in all the functions that * access MY_CXT. */ #if defined(MULTIPLICITY) || defined(PERL_OBJECT) || \ defined(PERL_CAPI) || defined(PERL_IMPLICIT_CONTEXT) #ifndef START_MY_CXT /* This must appear in all extensions that define a my_cxt_t structure, * right after the definition (i.e. at file scope). The non-threads * case below uses it to declare the data as static. */ #define START_MY_CXT #if (PERL_BCDVERSION < 0x5004068) /* Fetches the SV that keeps the per-interpreter data. */ #define dMY_CXT_SV \ SV *my_cxt_sv = get_sv(MY_CXT_KEY, FALSE) #else /* >= perl5.004_68 */ #define dMY_CXT_SV \ SV *my_cxt_sv = *hv_fetch(PL_modglobal, MY_CXT_KEY, \ sizeof(MY_CXT_KEY)-1, TRUE) #endif /* < perl5.004_68 */ /* This declaration should be used within all functions that use the * interpreter-local data. */ #define dMY_CXT \ dMY_CXT_SV; \ my_cxt_t *my_cxtp = INT2PTR(my_cxt_t*,SvUV(my_cxt_sv)) /* Creates and zeroes the per-interpreter data. * (We allocate my_cxtp in a Perl SV so that it will be released when * the interpreter goes away.) */ #define MY_CXT_INIT \ dMY_CXT_SV; \ /* newSV() allocates one more than needed */ \ my_cxt_t *my_cxtp = (my_cxt_t*)SvPVX(newSV(sizeof(my_cxt_t)-1));\ Zero(my_cxtp, 1, my_cxt_t); \ sv_setuv(my_cxt_sv, PTR2UV(my_cxtp)) /* This macro must be used to access members of the my_cxt_t structure. * e.g. MYCXT.some_data */ #define MY_CXT (*my_cxtp) /* Judicious use of these macros can reduce the number of times dMY_CXT * is used. Use is similar to pTHX, aTHX etc. */ #define pMY_CXT my_cxt_t *my_cxtp #define pMY_CXT_ pMY_CXT, #define _pMY_CXT ,pMY_CXT #define aMY_CXT my_cxtp #define aMY_CXT_ aMY_CXT, #define _aMY_CXT ,aMY_CXT #endif /* START_MY_CXT */ #ifndef MY_CXT_CLONE /* Clones the per-interpreter data. */ #define MY_CXT_CLONE \ dMY_CXT_SV; \ my_cxt_t *my_cxtp = (my_cxt_t*)SvPVX(newSV(sizeof(my_cxt_t)-1));\ Copy(INT2PTR(my_cxt_t*, SvUV(my_cxt_sv)), my_cxtp, 1, my_cxt_t);\ sv_setuv(my_cxt_sv, PTR2UV(my_cxtp)) #endif #else /* single interpreter */ #ifndef START_MY_CXT #define START_MY_CXT static my_cxt_t my_cxt; #define dMY_CXT_SV dNOOP #define dMY_CXT dNOOP #define MY_CXT_INIT NOOP #define MY_CXT my_cxt #define pMY_CXT void #define pMY_CXT_ #define _pMY_CXT #define aMY_CXT #define aMY_CXT_ #define _aMY_CXT #endif /* START_MY_CXT */ #ifndef MY_CXT_CLONE #define MY_CXT_CLONE NOOP #endif #endif #ifndef IVdf # if IVSIZE == LONGSIZE # define IVdf "ld" # define UVuf "lu" # define UVof "lo" # define UVxf "lx" # define UVXf "lX" # elif IVSIZE == INTSIZE # define IVdf "d" # define UVuf "u" # define UVof "o" # define UVxf "x" # define UVXf "X" # else # error "cannot define IV/UV formats" # endif #endif #ifndef NVef # if defined(USE_LONG_DOUBLE) && defined(HAS_LONG_DOUBLE) && \ defined(PERL_PRIfldbl) && (PERL_BCDVERSION != 0x5006000) /* Not very likely, but let's try anyway. */ # define NVef PERL_PRIeldbl # define NVff PERL_PRIfldbl # define NVgf PERL_PRIgldbl # else # define NVef "e" # define NVff "f" # define NVgf "g" # endif #endif #ifndef SvREFCNT_inc # ifdef PERL_USE_GCC_BRACE_GROUPS # define SvREFCNT_inc(sv) \ ({ \ SV * const _sv = (SV*)(sv); \ if (_sv) \ (SvREFCNT(_sv))++; \ _sv; \ }) # else # define SvREFCNT_inc(sv) \ ((PL_Sv=(SV*)(sv)) ? (++(SvREFCNT(PL_Sv)),PL_Sv) : NULL) # endif #endif #ifndef SvREFCNT_inc_simple # ifdef PERL_USE_GCC_BRACE_GROUPS # define SvREFCNT_inc_simple(sv) \ ({ \ if (sv) \ (SvREFCNT(sv))++; \ (SV *)(sv); \ }) # else # define SvREFCNT_inc_simple(sv) \ ((sv) ? (SvREFCNT(sv)++,(SV*)(sv)) : NULL) # endif #endif #ifndef SvREFCNT_inc_NN # ifdef PERL_USE_GCC_BRACE_GROUPS # define SvREFCNT_inc_NN(sv) \ ({ \ SV * const _sv = (SV*)(sv); \ SvREFCNT(_sv)++; \ _sv; \ }) # else # define SvREFCNT_inc_NN(sv) \ (PL_Sv=(SV*)(sv),++(SvREFCNT(PL_Sv)),PL_Sv) # endif #endif #ifndef SvREFCNT_inc_void # ifdef PERL_USE_GCC_BRACE_GROUPS # define SvREFCNT_inc_void(sv) \ ({ \ SV * const _sv = (SV*)(sv); \ if (_sv) \ (void)(SvREFCNT(_sv)++); \ }) # else # define SvREFCNT_inc_void(sv) \ (void)((PL_Sv=(SV*)(sv)) ? ++(SvREFCNT(PL_Sv)) : 0) # endif #endif #ifndef SvREFCNT_inc_simple_void # define SvREFCNT_inc_simple_void(sv) STMT_START { if (sv) SvREFCNT(sv)++; } STMT_END #endif #ifndef SvREFCNT_inc_simple_NN # define SvREFCNT_inc_simple_NN(sv) (++SvREFCNT(sv), (SV*)(sv)) #endif #ifndef SvREFCNT_inc_void_NN # define SvREFCNT_inc_void_NN(sv) (void)(++SvREFCNT((SV*)(sv))) #endif #ifndef SvREFCNT_inc_simple_void_NN # define SvREFCNT_inc_simple_void_NN(sv) (void)(++SvREFCNT((SV*)(sv))) #endif #ifndef newSV_type #if defined(NEED_newSV_type) static SV* DPPP_(my_newSV_type)(pTHX_ svtype const t); static #else extern SV* DPPP_(my_newSV_type)(pTHX_ svtype const t); #endif #ifdef newSV_type # undef newSV_type #endif #define newSV_type(a) DPPP_(my_newSV_type)(aTHX_ a) #define Perl_newSV_type DPPP_(my_newSV_type) #if defined(NEED_newSV_type) || defined(NEED_newSV_type_GLOBAL) SV* DPPP_(my_newSV_type)(pTHX_ svtype const t) { SV* const sv = newSV(0); sv_upgrade(sv, t); return sv; } #endif #endif #if (PERL_BCDVERSION < 0x5006000) # define D_PPP_CONSTPV_ARG(x) ((char *) (x)) #else # define D_PPP_CONSTPV_ARG(x) (x) #endif #ifndef newSVpvn # define newSVpvn(data,len) ((data) \ ? ((len) ? newSVpv((data), (len)) : newSVpv("", 0)) \ : newSV(0)) #endif #ifndef newSVpvn_utf8 # define newSVpvn_utf8(s, len, u) newSVpvn_flags((s), (len), (u) ? SVf_UTF8 : 0) #endif #ifndef SVf_UTF8 # define SVf_UTF8 0 #endif #ifndef newSVpvn_flags #if defined(NEED_newSVpvn_flags) static SV * DPPP_(my_newSVpvn_flags)(pTHX_ const char *s, STRLEN len, U32 flags); static #else extern SV * DPPP_(my_newSVpvn_flags)(pTHX_ const char *s, STRLEN len, U32 flags); #endif #ifdef newSVpvn_flags # undef newSVpvn_flags #endif #define newSVpvn_flags(a,b,c) DPPP_(my_newSVpvn_flags)(aTHX_ a,b,c) #define Perl_newSVpvn_flags DPPP_(my_newSVpvn_flags) #if defined(NEED_newSVpvn_flags) || defined(NEED_newSVpvn_flags_GLOBAL) SV * DPPP_(my_newSVpvn_flags)(pTHX_ const char *s, STRLEN len, U32 flags) { SV *sv = newSVpvn(D_PPP_CONSTPV_ARG(s), len); SvFLAGS(sv) |= (flags & SVf_UTF8); return (flags & SVs_TEMP) ? sv_2mortal(sv) : sv; } #endif #endif /* Backwards compatibility stuff... :-( */ #if !defined(NEED_sv_2pv_flags) && defined(NEED_sv_2pv_nolen) # define NEED_sv_2pv_flags #endif #if !defined(NEED_sv_2pv_flags_GLOBAL) && defined(NEED_sv_2pv_nolen_GLOBAL) # define NEED_sv_2pv_flags_GLOBAL #endif /* Hint: sv_2pv_nolen * Use the SvPV_nolen() or SvPV_nolen_const() macros instead of sv_2pv_nolen(). */ #ifndef sv_2pv_nolen # define sv_2pv_nolen(sv) SvPV_nolen(sv) #endif #ifdef SvPVbyte /* Hint: SvPVbyte * Does not work in perl-5.6.1, ppport.h implements a version * borrowed from perl-5.7.3. */ #if (PERL_BCDVERSION < 0x5007000) #if defined(NEED_sv_2pvbyte) static char * DPPP_(my_sv_2pvbyte)(pTHX_ SV *sv, STRLEN *lp); static #else extern char * DPPP_(my_sv_2pvbyte)(pTHX_ SV *sv, STRLEN *lp); #endif #ifdef sv_2pvbyte # undef sv_2pvbyte #endif #define sv_2pvbyte(a,b) DPPP_(my_sv_2pvbyte)(aTHX_ a,b) #define Perl_sv_2pvbyte DPPP_(my_sv_2pvbyte) #if defined(NEED_sv_2pvbyte) || defined(NEED_sv_2pvbyte_GLOBAL) char * DPPP_(my_sv_2pvbyte)(pTHX_ SV *sv, STRLEN *lp) { sv_utf8_downgrade(sv,0); return SvPV(sv,*lp); } #endif /* Hint: sv_2pvbyte * Use the SvPVbyte() macro instead of sv_2pvbyte(). */ #undef SvPVbyte #define SvPVbyte(sv, lp) \ ((SvFLAGS(sv) & (SVf_POK|SVf_UTF8)) == (SVf_POK) \ ? ((lp = SvCUR(sv)), SvPVX(sv)) : sv_2pvbyte(sv, &lp)) #endif #else # define SvPVbyte SvPV # define sv_2pvbyte sv_2pv #endif #ifndef sv_2pvbyte_nolen # define sv_2pvbyte_nolen(sv) sv_2pv_nolen(sv) #endif /* Hint: sv_pvn * Always use the SvPV() macro instead of sv_pvn(). */ /* Hint: sv_pvn_force * Always use the SvPV_force() macro instead of sv_pvn_force(). */ /* If these are undefined, they're not handled by the core anyway */ #ifndef SV_IMMEDIATE_UNREF # define SV_IMMEDIATE_UNREF 0 #endif #ifndef SV_GMAGIC # define SV_GMAGIC 0 #endif #ifndef SV_COW_DROP_PV # define SV_COW_DROP_PV 0 #endif #ifndef SV_UTF8_NO_ENCODING # define SV_UTF8_NO_ENCODING 0 #endif #ifndef SV_NOSTEAL # define SV_NOSTEAL 0 #endif #ifndef SV_CONST_RETURN # define SV_CONST_RETURN 0 #endif #ifndef SV_MUTABLE_RETURN # define SV_MUTABLE_RETURN 0 #endif #ifndef SV_SMAGIC # define SV_SMAGIC 0 #endif #ifndef SV_HAS_TRAILING_NUL # define SV_HAS_TRAILING_NUL 0 #endif #ifndef SV_COW_SHARED_HASH_KEYS # define SV_COW_SHARED_HASH_KEYS 0 #endif #if (PERL_BCDVERSION < 0x5007002) #if defined(NEED_sv_2pv_flags) static char * DPPP_(my_sv_2pv_flags)(pTHX_ SV *sv, STRLEN *lp, I32 flags); static #else extern char * DPPP_(my_sv_2pv_flags)(pTHX_ SV *sv, STRLEN *lp, I32 flags); #endif #ifdef sv_2pv_flags # undef sv_2pv_flags #endif #define sv_2pv_flags(a,b,c) DPPP_(my_sv_2pv_flags)(aTHX_ a,b,c) #define Perl_sv_2pv_flags DPPP_(my_sv_2pv_flags) #if defined(NEED_sv_2pv_flags) || defined(NEED_sv_2pv_flags_GLOBAL) char * DPPP_(my_sv_2pv_flags)(pTHX_ SV *sv, STRLEN *lp, I32 flags) { STRLEN n_a = (STRLEN) flags; return sv_2pv(sv, lp ? lp : &n_a); } #endif #if defined(NEED_sv_pvn_force_flags) static char * DPPP_(my_sv_pvn_force_flags)(pTHX_ SV *sv, STRLEN *lp, I32 flags); static #else extern char * DPPP_(my_sv_pvn_force_flags)(pTHX_ SV *sv, STRLEN *lp, I32 flags); #endif #ifdef sv_pvn_force_flags # undef sv_pvn_force_flags #endif #define sv_pvn_force_flags(a,b,c) DPPP_(my_sv_pvn_force_flags)(aTHX_ a,b,c) #define Perl_sv_pvn_force_flags DPPP_(my_sv_pvn_force_flags) #if defined(NEED_sv_pvn_force_flags) || defined(NEED_sv_pvn_force_flags_GLOBAL) char * DPPP_(my_sv_pvn_force_flags)(pTHX_ SV *sv, STRLEN *lp, I32 flags) { STRLEN n_a = (STRLEN) flags; return sv_pvn_force(sv, lp ? lp : &n_a); } #endif #endif #if (PERL_BCDVERSION < 0x5008008) || ( (PERL_BCDVERSION >= 0x5009000) && (PERL_BCDVERSION < 0x5009003) ) # define DPPP_SVPV_NOLEN_LP_ARG &PL_na #else # define DPPP_SVPV_NOLEN_LP_ARG 0 #endif #ifndef SvPV_const # define SvPV_const(sv, lp) SvPV_flags_const(sv, lp, SV_GMAGIC) #endif #ifndef SvPV_mutable # define SvPV_mutable(sv, lp) SvPV_flags_mutable(sv, lp, SV_GMAGIC) #endif #ifndef SvPV_flags # define SvPV_flags(sv, lp, flags) \ ((SvFLAGS(sv) & (SVf_POK)) == SVf_POK \ ? ((lp = SvCUR(sv)), SvPVX(sv)) : sv_2pv_flags(sv, &lp, flags)) #endif #ifndef SvPV_flags_const # define SvPV_flags_const(sv, lp, flags) \ ((SvFLAGS(sv) & (SVf_POK)) == SVf_POK \ ? ((lp = SvCUR(sv)), SvPVX_const(sv)) : \ (const char*) sv_2pv_flags(sv, &lp, flags|SV_CONST_RETURN)) #endif #ifndef SvPV_flags_const_nolen # define SvPV_flags_const_nolen(sv, flags) \ ((SvFLAGS(sv) & (SVf_POK)) == SVf_POK \ ? SvPVX_const(sv) : \ (const char*) sv_2pv_flags(sv, DPPP_SVPV_NOLEN_LP_ARG, flags|SV_CONST_RETURN)) #endif #ifndef SvPV_flags_mutable # define SvPV_flags_mutable(sv, lp, flags) \ ((SvFLAGS(sv) & (SVf_POK)) == SVf_POK \ ? ((lp = SvCUR(sv)), SvPVX_mutable(sv)) : \ sv_2pv_flags(sv, &lp, flags|SV_MUTABLE_RETURN)) #endif #ifndef SvPV_force # define SvPV_force(sv, lp) SvPV_force_flags(sv, lp, SV_GMAGIC) #endif #ifndef SvPV_force_nolen # define SvPV_force_nolen(sv) SvPV_force_flags_nolen(sv, SV_GMAGIC) #endif #ifndef SvPV_force_mutable # define SvPV_force_mutable(sv, lp) SvPV_force_flags_mutable(sv, lp, SV_GMAGIC) #endif #ifndef SvPV_force_nomg # define SvPV_force_nomg(sv, lp) SvPV_force_flags(sv, lp, 0) #endif #ifndef SvPV_force_nomg_nolen # define SvPV_force_nomg_nolen(sv) SvPV_force_flags_nolen(sv, 0) #endif #ifndef SvPV_force_flags # define SvPV_force_flags(sv, lp, flags) \ ((SvFLAGS(sv) & (SVf_POK|SVf_THINKFIRST)) == SVf_POK \ ? ((lp = SvCUR(sv)), SvPVX(sv)) : sv_pvn_force_flags(sv, &lp, flags)) #endif #ifndef SvPV_force_flags_nolen # define SvPV_force_flags_nolen(sv, flags) \ ((SvFLAGS(sv) & (SVf_POK|SVf_THINKFIRST)) == SVf_POK \ ? SvPVX(sv) : sv_pvn_force_flags(sv, DPPP_SVPV_NOLEN_LP_ARG, flags)) #endif #ifndef SvPV_force_flags_mutable # define SvPV_force_flags_mutable(sv, lp, flags) \ ((SvFLAGS(sv) & (SVf_POK|SVf_THINKFIRST)) == SVf_POK \ ? ((lp = SvCUR(sv)), SvPVX_mutable(sv)) \ : sv_pvn_force_flags(sv, &lp, flags|SV_MUTABLE_RETURN)) #endif #ifndef SvPV_nolen # define SvPV_nolen(sv) \ ((SvFLAGS(sv) & (SVf_POK)) == SVf_POK \ ? SvPVX(sv) : sv_2pv_flags(sv, DPPP_SVPV_NOLEN_LP_ARG, SV_GMAGIC)) #endif #ifndef SvPV_nolen_const # define SvPV_nolen_const(sv) \ ((SvFLAGS(sv) & (SVf_POK)) == SVf_POK \ ? SvPVX_const(sv) : sv_2pv_flags(sv, DPPP_SVPV_NOLEN_LP_ARG, SV_GMAGIC|SV_CONST_RETURN)) #endif #ifndef SvPV_nomg # define SvPV_nomg(sv, lp) SvPV_flags(sv, lp, 0) #endif #ifndef SvPV_nomg_const # define SvPV_nomg_const(sv, lp) SvPV_flags_const(sv, lp, 0) #endif #ifndef SvPV_nomg_const_nolen # define SvPV_nomg_const_nolen(sv) SvPV_flags_const_nolen(sv, 0) #endif #ifndef SvPV_nomg_nolen # define SvPV_nomg_nolen(sv) ((SvFLAGS(sv) & (SVf_POK)) == SVf_POK \ ? SvPVX(sv) : sv_2pv_flags(sv, DPPP_SVPV_NOLEN_LP_ARG, 0)) #endif #ifndef SvPV_renew # define SvPV_renew(sv,n) STMT_START { SvLEN_set(sv, n); \ SvPV_set((sv), (char *) saferealloc( \ (Malloc_t)SvPVX(sv), (MEM_SIZE)((n)))); \ } STMT_END #endif #ifndef SvMAGIC_set # define SvMAGIC_set(sv, val) \ STMT_START { assert(SvTYPE(sv) >= SVt_PVMG); \ (((XPVMG*) SvANY(sv))->xmg_magic = (val)); } STMT_END #endif #if (PERL_BCDVERSION < 0x5009003) #ifndef SvPVX_const # define SvPVX_const(sv) ((const char*) (0 + SvPVX(sv))) #endif #ifndef SvPVX_mutable # define SvPVX_mutable(sv) (0 + SvPVX(sv)) #endif #ifndef SvRV_set # define SvRV_set(sv, val) \ STMT_START { assert(SvTYPE(sv) >= SVt_RV); \ (((XRV*) SvANY(sv))->xrv_rv = (val)); } STMT_END #endif #else #ifndef SvPVX_const # define SvPVX_const(sv) ((const char*)((sv)->sv_u.svu_pv)) #endif #ifndef SvPVX_mutable # define SvPVX_mutable(sv) ((sv)->sv_u.svu_pv) #endif #ifndef SvRV_set # define SvRV_set(sv, val) \ STMT_START { assert(SvTYPE(sv) >= SVt_RV); \ ((sv)->sv_u.svu_rv = (val)); } STMT_END #endif #endif #ifndef SvSTASH_set # define SvSTASH_set(sv, val) \ STMT_START { assert(SvTYPE(sv) >= SVt_PVMG); \ (((XPVMG*) SvANY(sv))->xmg_stash = (val)); } STMT_END #endif #if (PERL_BCDVERSION < 0x5004000) #ifndef SvUV_set # define SvUV_set(sv, val) \ STMT_START { assert(SvTYPE(sv) == SVt_IV || SvTYPE(sv) >= SVt_PVIV); \ (((XPVIV*) SvANY(sv))->xiv_iv = (IV) (val)); } STMT_END #endif #else #ifndef SvUV_set # define SvUV_set(sv, val) \ STMT_START { assert(SvTYPE(sv) == SVt_IV || SvTYPE(sv) >= SVt_PVIV); \ (((XPVUV*) SvANY(sv))->xuv_uv = (val)); } STMT_END #endif #endif #if (PERL_BCDVERSION >= 0x5004000) && !defined(vnewSVpvf) #if defined(NEED_vnewSVpvf) static SV * DPPP_(my_vnewSVpvf)(pTHX_ const char *pat, va_list *args); static #else extern SV * DPPP_(my_vnewSVpvf)(pTHX_ const char *pat, va_list *args); #endif #ifdef vnewSVpvf # undef vnewSVpvf #endif #define vnewSVpvf(a,b) DPPP_(my_vnewSVpvf)(aTHX_ a,b) #define Perl_vnewSVpvf DPPP_(my_vnewSVpvf) #if defined(NEED_vnewSVpvf) || defined(NEED_vnewSVpvf_GLOBAL) SV * DPPP_(my_vnewSVpvf)(pTHX_ const char *pat, va_list *args) { register SV *sv = newSV(0); sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*)); return sv; } #endif #endif #if (PERL_BCDVERSION >= 0x5004000) && !defined(sv_vcatpvf) # define sv_vcatpvf(sv, pat, args) sv_vcatpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*)) #endif #if (PERL_BCDVERSION >= 0x5004000) && !defined(sv_vsetpvf) # define sv_vsetpvf(sv, pat, args) sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*)) #endif #if (PERL_BCDVERSION >= 0x5004000) && !defined(sv_catpvf_mg) #if defined(NEED_sv_catpvf_mg) static void DPPP_(my_sv_catpvf_mg)(pTHX_ SV *sv, const char *pat, ...); static #else extern void DPPP_(my_sv_catpvf_mg)(pTHX_ SV *sv, const char *pat, ...); #endif #define Perl_sv_catpvf_mg DPPP_(my_sv_catpvf_mg) #if defined(NEED_sv_catpvf_mg) || defined(NEED_sv_catpvf_mg_GLOBAL) void DPPP_(my_sv_catpvf_mg)(pTHX_ SV *sv, const char *pat, ...) { va_list args; va_start(args, pat); sv_vcatpvfn(sv, pat, strlen(pat), &args, Null(SV**), 0, Null(bool*)); SvSETMAGIC(sv); va_end(args); } #endif #endif #ifdef PERL_IMPLICIT_CONTEXT #if (PERL_BCDVERSION >= 0x5004000) && !defined(sv_catpvf_mg_nocontext) #if defined(NEED_sv_catpvf_mg_nocontext) static void DPPP_(my_sv_catpvf_mg_nocontext)(SV *sv, const char *pat, ...); static #else extern void DPPP_(my_sv_catpvf_mg_nocontext)(SV *sv, const char *pat, ...); #endif #define sv_catpvf_mg_nocontext DPPP_(my_sv_catpvf_mg_nocontext) #define Perl_sv_catpvf_mg_nocontext DPPP_(my_sv_catpvf_mg_nocontext) #if defined(NEED_sv_catpvf_mg_nocontext) || defined(NEED_sv_catpvf_mg_nocontext_GLOBAL) void DPPP_(my_sv_catpvf_mg_nocontext)(SV *sv, const char *pat, ...) { dTHX; va_list args; va_start(args, pat); sv_vcatpvfn(sv, pat, strlen(pat), &args, Null(SV**), 0, Null(bool*)); SvSETMAGIC(sv); va_end(args); } #endif #endif #endif /* sv_catpvf_mg depends on sv_catpvf_mg_nocontext */ #ifndef sv_catpvf_mg # ifdef PERL_IMPLICIT_CONTEXT # define sv_catpvf_mg Perl_sv_catpvf_mg_nocontext # else # define sv_catpvf_mg Perl_sv_catpvf_mg # endif #endif #if (PERL_BCDVERSION >= 0x5004000) && !defined(sv_vcatpvf_mg) # define sv_vcatpvf_mg(sv, pat, args) \ STMT_START { \ sv_vcatpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*)); \ SvSETMAGIC(sv); \ } STMT_END #endif #if (PERL_BCDVERSION >= 0x5004000) && !defined(sv_setpvf_mg) #if defined(NEED_sv_setpvf_mg) static void DPPP_(my_sv_setpvf_mg)(pTHX_ SV *sv, const char *pat, ...); static #else extern void DPPP_(my_sv_setpvf_mg)(pTHX_ SV *sv, const char *pat, ...); #endif #define Perl_sv_setpvf_mg DPPP_(my_sv_setpvf_mg) #if defined(NEED_sv_setpvf_mg) || defined(NEED_sv_setpvf_mg_GLOBAL) void DPPP_(my_sv_setpvf_mg)(pTHX_ SV *sv, const char *pat, ...) { va_list args; va_start(args, pat); sv_vsetpvfn(sv, pat, strlen(pat), &args, Null(SV**), 0, Null(bool*)); SvSETMAGIC(sv); va_end(args); } #endif #endif #ifdef PERL_IMPLICIT_CONTEXT #if (PERL_BCDVERSION >= 0x5004000) && !defined(sv_setpvf_mg_nocontext) #if defined(NEED_sv_setpvf_mg_nocontext) static void DPPP_(my_sv_setpvf_mg_nocontext)(SV *sv, const char *pat, ...); static #else extern void DPPP_(my_sv_setpvf_mg_nocontext)(SV *sv, const char *pat, ...); #endif #define sv_setpvf_mg_nocontext DPPP_(my_sv_setpvf_mg_nocontext) #define Perl_sv_setpvf_mg_nocontext DPPP_(my_sv_setpvf_mg_nocontext) #if defined(NEED_sv_setpvf_mg_nocontext) || defined(NEED_sv_setpvf_mg_nocontext_GLOBAL) void DPPP_(my_sv_setpvf_mg_nocontext)(SV *sv, const char *pat, ...) { dTHX; va_list args; va_start(args, pat); sv_vsetpvfn(sv, pat, strlen(pat), &args, Null(SV**), 0, Null(bool*)); SvSETMAGIC(sv); va_end(args); } #endif #endif #endif /* sv_setpvf_mg depends on sv_setpvf_mg_nocontext */ #ifndef sv_setpvf_mg # ifdef PERL_IMPLICIT_CONTEXT # define sv_setpvf_mg Perl_sv_setpvf_mg_nocontext # else # define sv_setpvf_mg Perl_sv_setpvf_mg # endif #endif #if (PERL_BCDVERSION >= 0x5004000) && !defined(sv_vsetpvf_mg) # define sv_vsetpvf_mg(sv, pat, args) \ STMT_START { \ sv_vsetpvfn(sv, pat, strlen(pat), args, Null(SV**), 0, Null(bool*)); \ SvSETMAGIC(sv); \ } STMT_END #endif /* Hint: newSVpvn_share * The SVs created by this function only mimic the behaviour of * shared PVs without really being shared. Only use if you know * what you're doing. */ #ifndef newSVpvn_share #if defined(NEED_newSVpvn_share) static SV * DPPP_(my_newSVpvn_share)(pTHX_ const char *src, I32 len, U32 hash); static #else extern SV * DPPP_(my_newSVpvn_share)(pTHX_ const char *src, I32 len, U32 hash); #endif #ifdef newSVpvn_share # undef newSVpvn_share #endif #define newSVpvn_share(a,b,c) DPPP_(my_newSVpvn_share)(aTHX_ a,b,c) #define Perl_newSVpvn_share DPPP_(my_newSVpvn_share) #if defined(NEED_newSVpvn_share) || defined(NEED_newSVpvn_share_GLOBAL) SV * DPPP_(my_newSVpvn_share)(pTHX_ const char *src, I32 len, U32 hash) { SV *sv; if (len < 0) len = -len; if (!hash) PERL_HASH(hash, (char*) src, len); sv = newSVpvn((char *) src, len); sv_upgrade(sv, SVt_PVIV); SvIVX(sv) = hash; SvREADONLY_on(sv); SvPOK_on(sv); return sv; } #endif #endif #ifndef SvSHARED_HASH # define SvSHARED_HASH(sv) (0 + SvUVX(sv)) #endif #ifndef HvNAME_get # define HvNAME_get(hv) HvNAME(hv) #endif #ifndef HvNAMELEN_get # define HvNAMELEN_get(hv) (HvNAME_get(hv) ? (I32)strlen(HvNAME_get(hv)) : 0) #endif #ifndef GvSVn # define GvSVn(gv) GvSV(gv) #endif #ifndef isGV_with_GP # define isGV_with_GP(gv) isGV(gv) #endif #ifndef gv_fetchpvn_flags # define gv_fetchpvn_flags(name, len, flags, svt) gv_fetchpv(name, flags, svt) #endif #ifndef gv_fetchsv # define gv_fetchsv(name, flags, svt) gv_fetchpv(SvPV_nolen_const(name), flags, svt) #endif #ifndef get_cvn_flags # define get_cvn_flags(name, namelen, flags) get_cv(name, flags) #endif #ifndef WARN_ALL # define WARN_ALL 0 #endif #ifndef WARN_CLOSURE # define WARN_CLOSURE 1 #endif #ifndef WARN_DEPRECATED # define WARN_DEPRECATED 2 #endif #ifndef WARN_EXITING # define WARN_EXITING 3 #endif #ifndef WARN_GLOB # define WARN_GLOB 4 #endif #ifndef WARN_IO # define WARN_IO 5 #endif #ifndef WARN_CLOSED # define WARN_CLOSED 6 #endif #ifndef WARN_EXEC # define WARN_EXEC 7 #endif #ifndef WARN_LAYER # define WARN_LAYER 8 #endif #ifndef WARN_NEWLINE # define WARN_NEWLINE 9 #endif #ifndef WARN_PIPE # define WARN_PIPE 10 #endif #ifndef WARN_UNOPENED # define WARN_UNOPENED 11 #endif #ifndef WARN_MISC # define WARN_MISC 12 #endif #ifndef WARN_NUMERIC # define WARN_NUMERIC 13 #endif #ifndef WARN_ONCE # define WARN_ONCE 14 #endif #ifndef WARN_OVERFLOW # define WARN_OVERFLOW 15 #endif #ifndef WARN_PACK # define WARN_PACK 16 #endif #ifndef WARN_PORTABLE # define WARN_PORTABLE 17 #endif #ifndef WARN_RECURSION # define WARN_RECURSION 18 #endif #ifndef WARN_REDEFINE # define WARN_REDEFINE 19 #endif #ifndef WARN_REGEXP # define WARN_REGEXP 20 #endif #ifndef WARN_SEVERE # define WARN_SEVERE 21 #endif #ifndef WARN_DEBUGGING # define WARN_DEBUGGING 22 #endif #ifndef WARN_INPLACE # define WARN_INPLACE 23 #endif #ifndef WARN_INTERNAL # define WARN_INTERNAL 24 #endif #ifndef WARN_MALLOC # define WARN_MALLOC 25 #endif #ifndef WARN_SIGNAL # define WARN_SIGNAL 26 #endif #ifndef WARN_SUBSTR # define WARN_SUBSTR 27 #endif #ifndef WARN_SYNTAX # define WARN_SYNTAX 28 #endif #ifndef WARN_AMBIGUOUS # define WARN_AMBIGUOUS 29 #endif #ifndef WARN_BAREWORD # define WARN_BAREWORD 30 #endif #ifndef WARN_DIGIT # define WARN_DIGIT 31 #endif #ifndef WARN_PARENTHESIS # define WARN_PARENTHESIS 32 #endif #ifndef WARN_PRECEDENCE # define WARN_PRECEDENCE 33 #endif #ifndef WARN_PRINTF # define WARN_PRINTF 34 #endif #ifndef WARN_PROTOTYPE # define WARN_PROTOTYPE 35 #endif #ifndef WARN_QW # define WARN_QW 36 #endif #ifndef WARN_RESERVED # define WARN_RESERVED 37 #endif #ifndef WARN_SEMICOLON # define WARN_SEMICOLON 38 #endif #ifndef WARN_TAINT # define WARN_TAINT 39 #endif #ifndef WARN_THREADS # define WARN_THREADS 40 #endif #ifndef WARN_UNINITIALIZED # define WARN_UNINITIALIZED 41 #endif #ifndef WARN_UNPACK # define WARN_UNPACK 42 #endif #ifndef WARN_UNTIE # define WARN_UNTIE 43 #endif #ifndef WARN_UTF8 # define WARN_UTF8 44 #endif #ifndef WARN_VOID # define WARN_VOID 45 #endif #ifndef WARN_ASSERTIONS # define WARN_ASSERTIONS 46 #endif #ifndef packWARN # define packWARN(a) (a) #endif #ifndef ckWARN # ifdef G_WARN_ON # define ckWARN(a) (PL_dowarn & G_WARN_ON) # else # define ckWARN(a) PL_dowarn # endif #endif #if (PERL_BCDVERSION >= 0x5004000) && !defined(warner) #if defined(NEED_warner) static void DPPP_(my_warner)(U32 err, const char *pat, ...); static #else extern void DPPP_(my_warner)(U32 err, const char *pat, ...); #endif #define Perl_warner DPPP_(my_warner) #if defined(NEED_warner) || defined(NEED_warner_GLOBAL) void DPPP_(my_warner)(U32 err, const char *pat, ...) { SV *sv; va_list args; PERL_UNUSED_ARG(err); va_start(args, pat); sv = vnewSVpvf(pat, &args); va_end(args); sv_2mortal(sv); warn("%s", SvPV_nolen(sv)); } #define warner Perl_warner #define Perl_warner_nocontext Perl_warner #endif #endif /* concatenating with "" ensures that only literal strings are accepted as argument * note that STR_WITH_LEN() can't be used as argument to macros or functions that * under some configurations might be macros */ #ifndef STR_WITH_LEN # define STR_WITH_LEN(s) (s ""), (sizeof(s)-1) #endif #ifndef newSVpvs # define newSVpvs(str) newSVpvn(str "", sizeof(str) - 1) #endif #ifndef newSVpvs_flags # define newSVpvs_flags(str, flags) newSVpvn_flags(str "", sizeof(str) - 1, flags) #endif #ifndef newSVpvs_share # define newSVpvs_share(str) newSVpvn_share(str "", sizeof(str) - 1, 0) #endif #ifndef sv_catpvs # define sv_catpvs(sv, str) sv_catpvn(sv, str "", sizeof(str) - 1) #endif #ifndef sv_setpvs # define sv_setpvs(sv, str) sv_setpvn(sv, str "", sizeof(str) - 1) #endif #ifndef hv_fetchs # define hv_fetchs(hv, key, lval) hv_fetch(hv, key "", sizeof(key) - 1, lval) #endif #ifndef hv_stores # define hv_stores(hv, key, val) hv_store(hv, key "", sizeof(key) - 1, val, 0) #endif #ifndef gv_fetchpvs # define gv_fetchpvs(name, flags, svt) gv_fetchpvn_flags(name "", sizeof(name) - 1, flags, svt) #endif #ifndef gv_stashpvs # define gv_stashpvs(name, flags) gv_stashpvn(name "", sizeof(name) - 1, flags) #endif #ifndef get_cvs # define get_cvs(name, flags) get_cvn_flags(name "", sizeof(name)-1, flags) #endif #ifndef SvGETMAGIC # define SvGETMAGIC(x) STMT_START { if (SvGMAGICAL(x)) mg_get(x); } STMT_END #endif /* Some random bits for sv_unmagicext. These should probably be pulled in for real and organized at some point */ #ifndef HEf_SVKEY # define HEf_SVKEY -2 #endif #if defined(__GNUC__) && !defined(PERL_GCC_BRACE_GROUPS_FORBIDDEN) # define MUTABLE_PTR(p) ({ void *_p = (p); _p; }) #else # define MUTABLE_PTR(p) ((void *) (p)) #endif #define MUTABLE_SV(p) ((SV *)MUTABLE_PTR(p)) /* end of random bits */ #ifndef PERL_MAGIC_sv # define PERL_MAGIC_sv '\0' #endif #ifndef PERL_MAGIC_overload # define PERL_MAGIC_overload 'A' #endif #ifndef PERL_MAGIC_overload_elem # define PERL_MAGIC_overload_elem 'a' #endif #ifndef PERL_MAGIC_overload_table # define PERL_MAGIC_overload_table 'c' #endif #ifndef PERL_MAGIC_bm # define PERL_MAGIC_bm 'B' #endif #ifndef PERL_MAGIC_regdata # define PERL_MAGIC_regdata 'D' #endif #ifndef PERL_MAGIC_regdatum # define PERL_MAGIC_regdatum 'd' #endif #ifndef PERL_MAGIC_env # define PERL_MAGIC_env 'E' #endif #ifndef PERL_MAGIC_envelem # define PERL_MAGIC_envelem 'e' #endif #ifndef PERL_MAGIC_fm # define PERL_MAGIC_fm 'f' #endif #ifndef PERL_MAGIC_regex_global # define PERL_MAGIC_regex_global 'g' #endif #ifndef PERL_MAGIC_isa # define PERL_MAGIC_isa 'I' #endif #ifndef PERL_MAGIC_isaelem # define PERL_MAGIC_isaelem 'i' #endif #ifndef PERL_MAGIC_nkeys # define PERL_MAGIC_nkeys 'k' #endif #ifndef PERL_MAGIC_dbfile # define PERL_MAGIC_dbfile 'L' #endif #ifndef PERL_MAGIC_dbline # define PERL_MAGIC_dbline 'l' #endif #ifndef PERL_MAGIC_mutex # define PERL_MAGIC_mutex 'm' #endif #ifndef PERL_MAGIC_shared # define PERL_MAGIC_shared 'N' #endif #ifndef PERL_MAGIC_shared_scalar # define PERL_MAGIC_shared_scalar 'n' #endif #ifndef PERL_MAGIC_collxfrm # define PERL_MAGIC_collxfrm 'o' #endif #ifndef PERL_MAGIC_tied # define PERL_MAGIC_tied 'P' #endif #ifndef PERL_MAGIC_tiedelem # define PERL_MAGIC_tiedelem 'p' #endif #ifndef PERL_MAGIC_tiedscalar # define PERL_MAGIC_tiedscalar 'q' #endif #ifndef PERL_MAGIC_qr # define PERL_MAGIC_qr 'r' #endif #ifndef PERL_MAGIC_sig # define PERL_MAGIC_sig 'S' #endif #ifndef PERL_MAGIC_sigelem # define PERL_MAGIC_sigelem 's' #endif #ifndef PERL_MAGIC_taint # define PERL_MAGIC_taint 't' #endif #ifndef PERL_MAGIC_uvar # define PERL_MAGIC_uvar 'U' #endif #ifndef PERL_MAGIC_uvar_elem # define PERL_MAGIC_uvar_elem 'u' #endif #ifndef PERL_MAGIC_vstring # define PERL_MAGIC_vstring 'V' #endif #ifndef PERL_MAGIC_vec # define PERL_MAGIC_vec 'v' #endif #ifndef PERL_MAGIC_utf8 # define PERL_MAGIC_utf8 'w' #endif #ifndef PERL_MAGIC_substr # define PERL_MAGIC_substr 'x' #endif #ifndef PERL_MAGIC_defelem # define PERL_MAGIC_defelem 'y' #endif #ifndef PERL_MAGIC_glob # define PERL_MAGIC_glob '*' #endif #ifndef PERL_MAGIC_arylen # define PERL_MAGIC_arylen '#' #endif #ifndef PERL_MAGIC_pos # define PERL_MAGIC_pos '.' #endif #ifndef PERL_MAGIC_backref # define PERL_MAGIC_backref '<' #endif #ifndef PERL_MAGIC_ext # define PERL_MAGIC_ext '~' #endif /* That's the best we can do... */ #ifndef sv_catpvn_nomg # define sv_catpvn_nomg sv_catpvn #endif #ifndef sv_catsv_nomg # define sv_catsv_nomg sv_catsv #endif #ifndef sv_setsv_nomg # define sv_setsv_nomg sv_setsv #endif #ifndef sv_pvn_nomg # define sv_pvn_nomg sv_pvn #endif #ifndef SvIV_nomg # define SvIV_nomg SvIV #endif #ifndef SvUV_nomg # define SvUV_nomg SvUV #endif #ifndef sv_catpv_mg # define sv_catpv_mg(sv, ptr) \ STMT_START { \ SV *TeMpSv = sv; \ sv_catpv(TeMpSv,ptr); \ SvSETMAGIC(TeMpSv); \ } STMT_END #endif #ifndef sv_catpvn_mg # define sv_catpvn_mg(sv, ptr, len) \ STMT_START { \ SV *TeMpSv = sv; \ sv_catpvn(TeMpSv,ptr,len); \ SvSETMAGIC(TeMpSv); \ } STMT_END #endif #ifndef sv_catsv_mg # define sv_catsv_mg(dsv, ssv) \ STMT_START { \ SV *TeMpSv = dsv; \ sv_catsv(TeMpSv,ssv); \ SvSETMAGIC(TeMpSv); \ } STMT_END #endif #ifndef sv_setiv_mg # define sv_setiv_mg(sv, i) \ STMT_START { \ SV *TeMpSv = sv; \ sv_setiv(TeMpSv,i); \ SvSETMAGIC(TeMpSv); \ } STMT_END #endif #ifndef sv_setnv_mg # define sv_setnv_mg(sv, num) \ STMT_START { \ SV *TeMpSv = sv; \ sv_setnv(TeMpSv,num); \ SvSETMAGIC(TeMpSv); \ } STMT_END #endif #ifndef sv_setpv_mg # define sv_setpv_mg(sv, ptr) \ STMT_START { \ SV *TeMpSv = sv; \ sv_setpv(TeMpSv,ptr); \ SvSETMAGIC(TeMpSv); \ } STMT_END #endif #ifndef sv_setpvn_mg # define sv_setpvn_mg(sv, ptr, len) \ STMT_START { \ SV *TeMpSv = sv; \ sv_setpvn(TeMpSv,ptr,len); \ SvSETMAGIC(TeMpSv); \ } STMT_END #endif #ifndef sv_setsv_mg # define sv_setsv_mg(dsv, ssv) \ STMT_START { \ SV *TeMpSv = dsv; \ sv_setsv(TeMpSv,ssv); \ SvSETMAGIC(TeMpSv); \ } STMT_END #endif #ifndef sv_setuv_mg # define sv_setuv_mg(sv, i) \ STMT_START { \ SV *TeMpSv = sv; \ sv_setuv(TeMpSv,i); \ SvSETMAGIC(TeMpSv); \ } STMT_END #endif #ifndef sv_usepvn_mg # define sv_usepvn_mg(sv, ptr, len) \ STMT_START { \ SV *TeMpSv = sv; \ sv_usepvn(TeMpSv,ptr,len); \ SvSETMAGIC(TeMpSv); \ } STMT_END #endif #ifndef SvVSTRING_mg # define SvVSTRING_mg(sv) (SvMAGICAL(sv) ? mg_find(sv, PERL_MAGIC_vstring) : NULL) #endif /* Hint: sv_magic_portable * This is a compatibility function that is only available with * Devel::PPPort. It is NOT in the perl core. * Its purpose is to mimic the 5.8.0 behaviour of sv_magic() when * it is being passed a name pointer with namlen == 0. In that * case, perl 5.8.0 and later store the pointer, not a copy of it. * The compatibility can be provided back to perl 5.004. With * earlier versions, the code will not compile. */ #if (PERL_BCDVERSION < 0x5004000) /* code that uses sv_magic_portable will not compile */ #elif (PERL_BCDVERSION < 0x5008000) # define sv_magic_portable(sv, obj, how, name, namlen) \ STMT_START { \ SV *SvMp_sv = (sv); \ char *SvMp_name = (char *) (name); \ I32 SvMp_namlen = (namlen); \ if (SvMp_name && SvMp_namlen == 0) \ { \ MAGIC *mg; \ sv_magic(SvMp_sv, obj, how, 0, 0); \ mg = SvMAGIC(SvMp_sv); \ mg->mg_len = -42; /* XXX: this is the tricky part */ \ mg->mg_ptr = SvMp_name; \ } \ else \ { \ sv_magic(SvMp_sv, obj, how, SvMp_name, SvMp_namlen); \ } \ } STMT_END #else # define sv_magic_portable(a, b, c, d, e) sv_magic(a, b, c, d, e) #endif #if !defined(mg_findext) #if defined(NEED_mg_findext) static MAGIC * DPPP_(my_mg_findext)(SV * sv, int type, const MGVTBL *vtbl); static #else extern MAGIC * DPPP_(my_mg_findext)(SV * sv, int type, const MGVTBL *vtbl); #endif #define mg_findext DPPP_(my_mg_findext) #define Perl_mg_findext DPPP_(my_mg_findext) #if defined(NEED_mg_findext) || defined(NEED_mg_findext_GLOBAL) MAGIC * DPPP_(my_mg_findext)(SV * sv, int type, const MGVTBL *vtbl) { if (sv) { MAGIC *mg; #ifdef AvPAD_NAMELIST assert(!(SvTYPE(sv) == SVt_PVAV && AvPAD_NAMELIST(sv))); #endif for (mg = SvMAGIC (sv); mg; mg = mg->mg_moremagic) { if (mg->mg_type == type && mg->mg_virtual == vtbl) return mg; } } return NULL; } #endif #endif #if !defined(sv_unmagicext) #if defined(NEED_sv_unmagicext) static int DPPP_(my_sv_unmagicext)(pTHX_ SV * const sv, const int type, MGVTBL * vtbl); static #else extern int DPPP_(my_sv_unmagicext)(pTHX_ SV * const sv, const int type, MGVTBL * vtbl); #endif #ifdef sv_unmagicext # undef sv_unmagicext #endif #define sv_unmagicext(a,b,c) DPPP_(my_sv_unmagicext)(aTHX_ a,b,c) #define Perl_sv_unmagicext DPPP_(my_sv_unmagicext) #if defined(NEED_sv_unmagicext) || defined(NEED_sv_unmagicext_GLOBAL) int DPPP_(my_sv_unmagicext)(pTHX_ SV *const sv, const int type, MGVTBL *vtbl) { MAGIC* mg; MAGIC** mgp; if (SvTYPE(sv) < SVt_PVMG || !SvMAGIC(sv)) return 0; mgp = &(SvMAGIC(sv)); for (mg = *mgp; mg; mg = *mgp) { const MGVTBL* const virt = mg->mg_virtual; if (mg->mg_type == type && virt == vtbl) { *mgp = mg->mg_moremagic; if (virt && virt->svt_free) virt->svt_free(aTHX_ sv, mg); if (mg->mg_ptr && mg->mg_type != PERL_MAGIC_regex_global) { if (mg->mg_len > 0) Safefree(mg->mg_ptr); else if (mg->mg_len == HEf_SVKEY) /* Questionable on older perls... */ SvREFCNT_dec(MUTABLE_SV(mg->mg_ptr)); else if (mg->mg_type == PERL_MAGIC_utf8) Safefree(mg->mg_ptr); } if (mg->mg_flags & MGf_REFCOUNTED) SvREFCNT_dec(mg->mg_obj); Safefree(mg); } else mgp = &mg->mg_moremagic; } if (SvMAGIC(sv)) { if (SvMAGICAL(sv)) /* if we're under save_magic, wait for restore_magic; */ mg_magical(sv); /* else fix the flags now */ } else { SvMAGICAL_off(sv); SvFLAGS(sv) |= (SvFLAGS(sv) & (SVp_IOK|SVp_NOK|SVp_POK)) >> PRIVSHIFT; } return 0; } #endif #endif #ifdef USE_ITHREADS #ifndef CopFILE # define CopFILE(c) ((c)->cop_file) #endif #ifndef CopFILEGV # define CopFILEGV(c) (CopFILE(c) ? gv_fetchfile(CopFILE(c)) : Nullgv) #endif #ifndef CopFILE_set # define CopFILE_set(c,pv) ((c)->cop_file = savepv(pv)) #endif #ifndef CopFILESV # define CopFILESV(c) (CopFILE(c) ? GvSV(gv_fetchfile(CopFILE(c))) : Nullsv) #endif #ifndef CopFILEAV # define CopFILEAV(c) (CopFILE(c) ? GvAV(gv_fetchfile(CopFILE(c))) : Nullav) #endif #ifndef CopSTASHPV # define CopSTASHPV(c) ((c)->cop_stashpv) #endif #ifndef CopSTASHPV_set # define CopSTASHPV_set(c,pv) ((c)->cop_stashpv = ((pv) ? savepv(pv) : Nullch)) #endif #ifndef CopSTASH # define CopSTASH(c) (CopSTASHPV(c) ? gv_stashpv(CopSTASHPV(c),GV_ADD) : Nullhv) #endif #ifndef CopSTASH_set # define CopSTASH_set(c,hv) CopSTASHPV_set(c, (hv) ? HvNAME(hv) : Nullch) #endif #ifndef CopSTASH_eq # define CopSTASH_eq(c,hv) ((hv) && (CopSTASHPV(c) == HvNAME(hv) \ || (CopSTASHPV(c) && HvNAME(hv) \ && strEQ(CopSTASHPV(c), HvNAME(hv))))) #endif #else #ifndef CopFILEGV # define CopFILEGV(c) ((c)->cop_filegv) #endif #ifndef CopFILEGV_set # define CopFILEGV_set(c,gv) ((c)->cop_filegv = (GV*)SvREFCNT_inc(gv)) #endif #ifndef CopFILE_set # define CopFILE_set(c,pv) CopFILEGV_set((c), gv_fetchfile(pv)) #endif #ifndef CopFILESV # define CopFILESV(c) (CopFILEGV(c) ? GvSV(CopFILEGV(c)) : Nullsv) #endif #ifndef CopFILEAV # define CopFILEAV(c) (CopFILEGV(c) ? GvAV(CopFILEGV(c)) : Nullav) #endif #ifndef CopFILE # define CopFILE(c) (CopFILESV(c) ? SvPVX(CopFILESV(c)) : Nullch) #endif #ifndef CopSTASH # define CopSTASH(c) ((c)->cop_stash) #endif #ifndef CopSTASH_set # define CopSTASH_set(c,hv) ((c)->cop_stash = (hv)) #endif #ifndef CopSTASHPV # define CopSTASHPV(c) (CopSTASH(c) ? HvNAME(CopSTASH(c)) : Nullch) #endif #ifndef CopSTASHPV_set # define CopSTASHPV_set(c,pv) CopSTASH_set((c), gv_stashpv(pv,GV_ADD)) #endif #ifndef CopSTASH_eq # define CopSTASH_eq(c,hv) (CopSTASH(c) == (hv)) #endif #endif /* USE_ITHREADS */ #if (PERL_BCDVERSION >= 0x5006000) #ifndef caller_cx # if defined(NEED_caller_cx) || defined(NEED_caller_cx_GLOBAL) static I32 DPPP_dopoptosub_at(const PERL_CONTEXT *cxstk, I32 startingblock) { I32 i; for (i = startingblock; i >= 0; i--) { register const PERL_CONTEXT * const cx = &cxstk[i]; switch (CxTYPE(cx)) { default: continue; case CXt_EVAL: case CXt_SUB: case CXt_FORMAT: return i; } } return i; } # endif # if defined(NEED_caller_cx) static const PERL_CONTEXT * DPPP_(my_caller_cx)(pTHX_ I32 count, const PERL_CONTEXT **dbcxp); static #else extern const PERL_CONTEXT * DPPP_(my_caller_cx)(pTHX_ I32 count, const PERL_CONTEXT **dbcxp); #endif #ifdef caller_cx # undef caller_cx #endif #define caller_cx(a,b) DPPP_(my_caller_cx)(aTHX_ a,b) #define Perl_caller_cx DPPP_(my_caller_cx) #if defined(NEED_caller_cx) || defined(NEED_caller_cx_GLOBAL) const PERL_CONTEXT * DPPP_(my_caller_cx)(pTHX_ I32 count, const PERL_CONTEXT **dbcxp) { register I32 cxix = DPPP_dopoptosub_at(cxstack, cxstack_ix); register const PERL_CONTEXT *cx; register const PERL_CONTEXT *ccstack = cxstack; const PERL_SI *top_si = PL_curstackinfo; for (;;) { /* we may be in a higher stacklevel, so dig down deeper */ while (cxix < 0 && top_si->si_type != PERLSI_MAIN) { top_si = top_si->si_prev; ccstack = top_si->si_cxstack; cxix = DPPP_dopoptosub_at(ccstack, top_si->si_cxix); } if (cxix < 0) return NULL; /* caller() should not report the automatic calls to &DB::sub */ if (PL_DBsub && GvCV(PL_DBsub) && cxix >= 0 && ccstack[cxix].blk_sub.cv == GvCV(PL_DBsub)) count++; if (!count--) break; cxix = DPPP_dopoptosub_at(ccstack, cxix - 1); } cx = &ccstack[cxix]; if (dbcxp) *dbcxp = cx; if (CxTYPE(cx) == CXt_SUB || CxTYPE(cx) == CXt_FORMAT) { const I32 dbcxix = DPPP_dopoptosub_at(ccstack, cxix - 1); /* We expect that ccstack[dbcxix] is CXt_SUB, anyway, the field below is defined for any cx. */ /* caller() should not report the automatic calls to &DB::sub */ if (PL_DBsub && GvCV(PL_DBsub) && dbcxix >= 0 && ccstack[dbcxix].blk_sub.cv == GvCV(PL_DBsub)) cx = &ccstack[dbcxix]; } return cx; } # endif #endif /* caller_cx */ #endif /* 5.6.0 */ #ifndef IN_PERL_COMPILETIME # define IN_PERL_COMPILETIME (PL_curcop == &PL_compiling) #endif #ifndef IN_LOCALE_RUNTIME # define IN_LOCALE_RUNTIME (PL_curcop->op_private & HINT_LOCALE) #endif #ifndef IN_LOCALE_COMPILETIME # define IN_LOCALE_COMPILETIME (PL_hints & HINT_LOCALE) #endif #ifndef IN_LOCALE # define IN_LOCALE (IN_PERL_COMPILETIME ? IN_LOCALE_COMPILETIME : IN_LOCALE_RUNTIME) #endif #ifndef IS_NUMBER_IN_UV # define IS_NUMBER_IN_UV 0x01 #endif #ifndef IS_NUMBER_GREATER_THAN_UV_MAX # define IS_NUMBER_GREATER_THAN_UV_MAX 0x02 #endif #ifndef IS_NUMBER_NOT_INT # define IS_NUMBER_NOT_INT 0x04 #endif #ifndef IS_NUMBER_NEG # define IS_NUMBER_NEG 0x08 #endif #ifndef IS_NUMBER_INFINITY # define IS_NUMBER_INFINITY 0x10 #endif #ifndef IS_NUMBER_NAN # define IS_NUMBER_NAN 0x20 #endif #ifndef GROK_NUMERIC_RADIX # define GROK_NUMERIC_RADIX(sp, send) grok_numeric_radix(sp, send) #endif #ifndef PERL_SCAN_GREATER_THAN_UV_MAX # define PERL_SCAN_GREATER_THAN_UV_MAX 0x02 #endif #ifndef PERL_SCAN_SILENT_ILLDIGIT # define PERL_SCAN_SILENT_ILLDIGIT 0x04 #endif #ifndef PERL_SCAN_ALLOW_UNDERSCORES # define PERL_SCAN_ALLOW_UNDERSCORES 0x01 #endif #ifndef PERL_SCAN_DISALLOW_PREFIX # define PERL_SCAN_DISALLOW_PREFIX 0x02 #endif #ifndef grok_numeric_radix #if defined(NEED_grok_numeric_radix) static bool DPPP_(my_grok_numeric_radix)(pTHX_ const char ** sp, const char * send); static #else extern bool DPPP_(my_grok_numeric_radix)(pTHX_ const char ** sp, const char * send); #endif #ifdef grok_numeric_radix # undef grok_numeric_radix #endif #define grok_numeric_radix(a,b) DPPP_(my_grok_numeric_radix)(aTHX_ a,b) #define Perl_grok_numeric_radix DPPP_(my_grok_numeric_radix) #if defined(NEED_grok_numeric_radix) || defined(NEED_grok_numeric_radix_GLOBAL) bool DPPP_(my_grok_numeric_radix)(pTHX_ const char **sp, const char *send) { #ifdef USE_LOCALE_NUMERIC #ifdef PL_numeric_radix_sv if (PL_numeric_radix_sv && IN_LOCALE) { STRLEN len; char* radix = SvPV(PL_numeric_radix_sv, len); if (*sp + len <= send && memEQ(*sp, radix, len)) { *sp += len; return TRUE; } } #else /* older perls don't have PL_numeric_radix_sv so the radix * must manually be requested from locale.h */ #include dTHR; /* needed for older threaded perls */ struct lconv *lc = localeconv(); char *radix = lc->decimal_point; if (radix && IN_LOCALE) { STRLEN len = strlen(radix); if (*sp + len <= send && memEQ(*sp, radix, len)) { *sp += len; return TRUE; } } #endif #endif /* USE_LOCALE_NUMERIC */ /* always try "." if numeric radix didn't match because * we may have data from different locales mixed */ if (*sp < send && **sp == '.') { ++*sp; return TRUE; } return FALSE; } #endif #endif #ifndef grok_number #if defined(NEED_grok_number) static int DPPP_(my_grok_number)(pTHX_ const char * pv, STRLEN len, UV * valuep); static #else extern int DPPP_(my_grok_number)(pTHX_ const char * pv, STRLEN len, UV * valuep); #endif #ifdef grok_number # undef grok_number #endif #define grok_number(a,b,c) DPPP_(my_grok_number)(aTHX_ a,b,c) #define Perl_grok_number DPPP_(my_grok_number) #if defined(NEED_grok_number) || defined(NEED_grok_number_GLOBAL) int DPPP_(my_grok_number)(pTHX_ const char *pv, STRLEN len, UV *valuep) { const char *s = pv; const char *send = pv + len; const UV max_div_10 = UV_MAX / 10; const char max_mod_10 = UV_MAX % 10; int numtype = 0; int sawinf = 0; int sawnan = 0; while (s < send && isSPACE(*s)) s++; if (s == send) { return 0; } else if (*s == '-') { s++; numtype = IS_NUMBER_NEG; } else if (*s == '+') s++; if (s == send) return 0; /* next must be digit or the radix separator or beginning of infinity */ if (isDIGIT(*s)) { /* UVs are at least 32 bits, so the first 9 decimal digits cannot overflow. */ UV value = *s - '0'; /* This construction seems to be more optimiser friendly. (without it gcc does the isDIGIT test and the *s - '0' separately) With it gcc on arm is managing 6 instructions (6 cycles) per digit. In theory the optimiser could deduce how far to unroll the loop before checking for overflow. */ if (++s < send) { int digit = *s - '0'; if (digit >= 0 && digit <= 9) { value = value * 10 + digit; if (++s < send) { digit = *s - '0'; if (digit >= 0 && digit <= 9) { value = value * 10 + digit; if (++s < send) { digit = *s - '0'; if (digit >= 0 && digit <= 9) { value = value * 10 + digit; if (++s < send) { digit = *s - '0'; if (digit >= 0 && digit <= 9) { value = value * 10 + digit; if (++s < send) { digit = *s - '0'; if (digit >= 0 && digit <= 9) { value = value * 10 + digit; if (++s < send) { digit = *s - '0'; if (digit >= 0 && digit <= 9) { value = value * 10 + digit; if (++s < send) { digit = *s - '0'; if (digit >= 0 && digit <= 9) { value = value * 10 + digit; if (++s < send) { digit = *s - '0'; if (digit >= 0 && digit <= 9) { value = value * 10 + digit; if (++s < send) { /* Now got 9 digits, so need to check each time for overflow. */ digit = *s - '0'; while (digit >= 0 && digit <= 9 && (value < max_div_10 || (value == max_div_10 && digit <= max_mod_10))) { value = value * 10 + digit; if (++s < send) digit = *s - '0'; else break; } if (digit >= 0 && digit <= 9 && (s < send)) { /* value overflowed. skip the remaining digits, don't worry about setting *valuep. */ do { s++; } while (s < send && isDIGIT(*s)); numtype |= IS_NUMBER_GREATER_THAN_UV_MAX; goto skip_value; } } } } } } } } } } } } } } } } } } numtype |= IS_NUMBER_IN_UV; if (valuep) *valuep = value; skip_value: if (GROK_NUMERIC_RADIX(&s, send)) { numtype |= IS_NUMBER_NOT_INT; while (s < send && isDIGIT(*s)) /* optional digits after the radix */ s++; } } else if (GROK_NUMERIC_RADIX(&s, send)) { numtype |= IS_NUMBER_NOT_INT | IS_NUMBER_IN_UV; /* valuep assigned below */ /* no digits before the radix means we need digits after it */ if (s < send && isDIGIT(*s)) { do { s++; } while (s < send && isDIGIT(*s)); if (valuep) { /* integer approximation is valid - it's 0. */ *valuep = 0; } } else return 0; } else if (*s == 'I' || *s == 'i') { s++; if (s == send || (*s != 'N' && *s != 'n')) return 0; s++; if (s == send || (*s != 'F' && *s != 'f')) return 0; s++; if (s < send && (*s == 'I' || *s == 'i')) { s++; if (s == send || (*s != 'N' && *s != 'n')) return 0; s++; if (s == send || (*s != 'I' && *s != 'i')) return 0; s++; if (s == send || (*s != 'T' && *s != 't')) return 0; s++; if (s == send || (*s != 'Y' && *s != 'y')) return 0; s++; } sawinf = 1; } else if (*s == 'N' || *s == 'n') { /* XXX TODO: There are signaling NaNs and quiet NaNs. */ s++; if (s == send || (*s != 'A' && *s != 'a')) return 0; s++; if (s == send || (*s != 'N' && *s != 'n')) return 0; s++; sawnan = 1; } else return 0; if (sawinf) { numtype &= IS_NUMBER_NEG; /* Keep track of sign */ numtype |= IS_NUMBER_INFINITY | IS_NUMBER_NOT_INT; } else if (sawnan) { numtype &= IS_NUMBER_NEG; /* Keep track of sign */ numtype |= IS_NUMBER_NAN | IS_NUMBER_NOT_INT; } else if (s < send) { /* we can have an optional exponent part */ if (*s == 'e' || *s == 'E') { /* The only flag we keep is sign. Blow away any "it's UV" */ numtype &= IS_NUMBER_NEG; numtype |= IS_NUMBER_NOT_INT; s++; if (s < send && (*s == '-' || *s == '+')) s++; if (s < send && isDIGIT(*s)) { do { s++; } while (s < send && isDIGIT(*s)); } else return 0; } } while (s < send && isSPACE(*s)) s++; if (s >= send) return numtype; if (len == 10 && memEQ(pv, "0 but true", 10)) { if (valuep) *valuep = 0; return IS_NUMBER_IN_UV; } return 0; } #endif #endif /* * The grok_* routines have been modified to use warn() instead of * Perl_warner(). Also, 'hexdigit' was the former name of PL_hexdigit, * which is why the stack variable has been renamed to 'xdigit'. */ #ifndef grok_bin #if defined(NEED_grok_bin) static UV DPPP_(my_grok_bin)(pTHX_ const char * start, STRLEN * len_p, I32 * flags, NV * result); static #else extern UV DPPP_(my_grok_bin)(pTHX_ const char * start, STRLEN * len_p, I32 * flags, NV * result); #endif #ifdef grok_bin # undef grok_bin #endif #define grok_bin(a,b,c,d) DPPP_(my_grok_bin)(aTHX_ a,b,c,d) #define Perl_grok_bin DPPP_(my_grok_bin) #if defined(NEED_grok_bin) || defined(NEED_grok_bin_GLOBAL) UV DPPP_(my_grok_bin)(pTHX_ const char *start, STRLEN *len_p, I32 *flags, NV *result) { const char *s = start; STRLEN len = *len_p; UV value = 0; NV value_nv = 0; const UV max_div_2 = UV_MAX / 2; bool allow_underscores = *flags & PERL_SCAN_ALLOW_UNDERSCORES; bool overflowed = FALSE; if (!(*flags & PERL_SCAN_DISALLOW_PREFIX)) { /* strip off leading b or 0b. for compatibility silently suffer "b" and "0b" as valid binary numbers. */ if (len >= 1) { if (s[0] == 'b') { s++; len--; } else if (len >= 2 && s[0] == '0' && s[1] == 'b') { s+=2; len-=2; } } } for (; len-- && *s; s++) { char bit = *s; if (bit == '0' || bit == '1') { /* Write it in this wonky order with a goto to attempt to get the compiler to make the common case integer-only loop pretty tight. With gcc seems to be much straighter code than old scan_bin. */ redo: if (!overflowed) { if (value <= max_div_2) { value = (value << 1) | (bit - '0'); continue; } /* Bah. We're just overflowed. */ warn("Integer overflow in binary number"); overflowed = TRUE; value_nv = (NV) value; } value_nv *= 2.0; /* If an NV has not enough bits in its mantissa to * represent a UV this summing of small low-order numbers * is a waste of time (because the NV cannot preserve * the low-order bits anyway): we could just remember when * did we overflow and in the end just multiply value_nv by the * right amount. */ value_nv += (NV)(bit - '0'); continue; } if (bit == '_' && len && allow_underscores && (bit = s[1]) && (bit == '0' || bit == '1')) { --len; ++s; goto redo; } if (!(*flags & PERL_SCAN_SILENT_ILLDIGIT)) warn("Illegal binary digit '%c' ignored", *s); break; } if ( ( overflowed && value_nv > 4294967295.0) #if UVSIZE > 4 || (!overflowed && value > 0xffffffff ) #endif ) { warn("Binary number > 0b11111111111111111111111111111111 non-portable"); } *len_p = s - start; if (!overflowed) { *flags = 0; return value; } *flags = PERL_SCAN_GREATER_THAN_UV_MAX; if (result) *result = value_nv; return UV_MAX; } #endif #endif #ifndef grok_hex #if defined(NEED_grok_hex) static UV DPPP_(my_grok_hex)(pTHX_ const char * start, STRLEN * len_p, I32 * flags, NV * result); static #else extern UV DPPP_(my_grok_hex)(pTHX_ const char * start, STRLEN * len_p, I32 * flags, NV * result); #endif #ifdef grok_hex # undef grok_hex #endif #define grok_hex(a,b,c,d) DPPP_(my_grok_hex)(aTHX_ a,b,c,d) #define Perl_grok_hex DPPP_(my_grok_hex) #if defined(NEED_grok_hex) || defined(NEED_grok_hex_GLOBAL) UV DPPP_(my_grok_hex)(pTHX_ const char *start, STRLEN *len_p, I32 *flags, NV *result) { const char *s = start; STRLEN len = *len_p; UV value = 0; NV value_nv = 0; const UV max_div_16 = UV_MAX / 16; bool allow_underscores = *flags & PERL_SCAN_ALLOW_UNDERSCORES; bool overflowed = FALSE; const char *xdigit; if (!(*flags & PERL_SCAN_DISALLOW_PREFIX)) { /* strip off leading x or 0x. for compatibility silently suffer "x" and "0x" as valid hex numbers. */ if (len >= 1) { if (s[0] == 'x') { s++; len--; } else if (len >= 2 && s[0] == '0' && s[1] == 'x') { s+=2; len-=2; } } } for (; len-- && *s; s++) { xdigit = strchr((char *) PL_hexdigit, *s); if (xdigit) { /* Write it in this wonky order with a goto to attempt to get the compiler to make the common case integer-only loop pretty tight. With gcc seems to be much straighter code than old scan_hex. */ redo: if (!overflowed) { if (value <= max_div_16) { value = (value << 4) | ((xdigit - PL_hexdigit) & 15); continue; } warn("Integer overflow in hexadecimal number"); overflowed = TRUE; value_nv = (NV) value; } value_nv *= 16.0; /* If an NV has not enough bits in its mantissa to * represent a UV this summing of small low-order numbers * is a waste of time (because the NV cannot preserve * the low-order bits anyway): we could just remember when * did we overflow and in the end just multiply value_nv by the * right amount of 16-tuples. */ value_nv += (NV)((xdigit - PL_hexdigit) & 15); continue; } if (*s == '_' && len && allow_underscores && s[1] && (xdigit = strchr((char *) PL_hexdigit, s[1]))) { --len; ++s; goto redo; } if (!(*flags & PERL_SCAN_SILENT_ILLDIGIT)) warn("Illegal hexadecimal digit '%c' ignored", *s); break; } if ( ( overflowed && value_nv > 4294967295.0) #if UVSIZE > 4 || (!overflowed && value > 0xffffffff ) #endif ) { warn("Hexadecimal number > 0xffffffff non-portable"); } *len_p = s - start; if (!overflowed) { *flags = 0; return value; } *flags = PERL_SCAN_GREATER_THAN_UV_MAX; if (result) *result = value_nv; return UV_MAX; } #endif #endif #ifndef grok_oct #if defined(NEED_grok_oct) static UV DPPP_(my_grok_oct)(pTHX_ const char * start, STRLEN * len_p, I32 * flags, NV * result); static #else extern UV DPPP_(my_grok_oct)(pTHX_ const char * start, STRLEN * len_p, I32 * flags, NV * result); #endif #ifdef grok_oct # undef grok_oct #endif #define grok_oct(a,b,c,d) DPPP_(my_grok_oct)(aTHX_ a,b,c,d) #define Perl_grok_oct DPPP_(my_grok_oct) #if defined(NEED_grok_oct) || defined(NEED_grok_oct_GLOBAL) UV DPPP_(my_grok_oct)(pTHX_ const char *start, STRLEN *len_p, I32 *flags, NV *result) { const char *s = start; STRLEN len = *len_p; UV value = 0; NV value_nv = 0; const UV max_div_8 = UV_MAX / 8; bool allow_underscores = *flags & PERL_SCAN_ALLOW_UNDERSCORES; bool overflowed = FALSE; for (; len-- && *s; s++) { /* gcc 2.95 optimiser not smart enough to figure that this subtraction out front allows slicker code. */ int digit = *s - '0'; if (digit >= 0 && digit <= 7) { /* Write it in this wonky order with a goto to attempt to get the compiler to make the common case integer-only loop pretty tight. */ redo: if (!overflowed) { if (value <= max_div_8) { value = (value << 3) | digit; continue; } /* Bah. We're just overflowed. */ warn("Integer overflow in octal number"); overflowed = TRUE; value_nv = (NV) value; } value_nv *= 8.0; /* If an NV has not enough bits in its mantissa to * represent a UV this summing of small low-order numbers * is a waste of time (because the NV cannot preserve * the low-order bits anyway): we could just remember when * did we overflow and in the end just multiply value_nv by the * right amount of 8-tuples. */ value_nv += (NV)digit; continue; } if (digit == ('_' - '0') && len && allow_underscores && (digit = s[1] - '0') && (digit >= 0 && digit <= 7)) { --len; ++s; goto redo; } /* Allow \octal to work the DWIM way (that is, stop scanning * as soon as non-octal characters are seen, complain only iff * someone seems to want to use the digits eight and nine). */ if (digit == 8 || digit == 9) { if (!(*flags & PERL_SCAN_SILENT_ILLDIGIT)) warn("Illegal octal digit '%c' ignored", *s); } break; } if ( ( overflowed && value_nv > 4294967295.0) #if UVSIZE > 4 || (!overflowed && value > 0xffffffff ) #endif ) { warn("Octal number > 037777777777 non-portable"); } *len_p = s - start; if (!overflowed) { *flags = 0; return value; } *flags = PERL_SCAN_GREATER_THAN_UV_MAX; if (result) *result = value_nv; return UV_MAX; } #endif #endif #if !defined(my_snprintf) #if defined(NEED_my_snprintf) static int DPPP_(my_my_snprintf)(char * buffer, const Size_t len, const char * format, ...); static #else extern int DPPP_(my_my_snprintf)(char * buffer, const Size_t len, const char * format, ...); #endif #define my_snprintf DPPP_(my_my_snprintf) #define Perl_my_snprintf DPPP_(my_my_snprintf) #if defined(NEED_my_snprintf) || defined(NEED_my_snprintf_GLOBAL) int DPPP_(my_my_snprintf)(char *buffer, const Size_t len, const char *format, ...) { dTHX; int retval; va_list ap; va_start(ap, format); #ifdef HAS_VSNPRINTF retval = vsnprintf(buffer, len, format, ap); #else retval = vsprintf(buffer, format, ap); #endif va_end(ap); if (retval < 0 || (len > 0 && (Size_t)retval >= len)) Perl_croak(aTHX_ "panic: my_snprintf buffer overflow"); return retval; } #endif #endif #if !defined(my_sprintf) #if defined(NEED_my_sprintf) static int DPPP_(my_my_sprintf)(char * buffer, const char * pat, ...); static #else extern int DPPP_(my_my_sprintf)(char * buffer, const char * pat, ...); #endif #define my_sprintf DPPP_(my_my_sprintf) #define Perl_my_sprintf DPPP_(my_my_sprintf) #if defined(NEED_my_sprintf) || defined(NEED_my_sprintf_GLOBAL) int DPPP_(my_my_sprintf)(char *buffer, const char* pat, ...) { va_list args; va_start(args, pat); vsprintf(buffer, pat, args); va_end(args); return strlen(buffer); } #endif #endif #ifdef NO_XSLOCKS # ifdef dJMPENV # define dXCPT dJMPENV; int rEtV = 0 # define XCPT_TRY_START JMPENV_PUSH(rEtV); if (rEtV == 0) # define XCPT_TRY_END JMPENV_POP; # define XCPT_CATCH if (rEtV != 0) # define XCPT_RETHROW JMPENV_JUMP(rEtV) # else # define dXCPT Sigjmp_buf oldTOP; int rEtV = 0 # define XCPT_TRY_START Copy(top_env, oldTOP, 1, Sigjmp_buf); rEtV = Sigsetjmp(top_env, 1); if (rEtV == 0) # define XCPT_TRY_END Copy(oldTOP, top_env, 1, Sigjmp_buf); # define XCPT_CATCH if (rEtV != 0) # define XCPT_RETHROW Siglongjmp(top_env, rEtV) # endif #endif #if !defined(my_strlcat) #if defined(NEED_my_strlcat) static Size_t DPPP_(my_my_strlcat)(char * dst, const char * src, Size_t size); static #else extern Size_t DPPP_(my_my_strlcat)(char * dst, const char * src, Size_t size); #endif #define my_strlcat DPPP_(my_my_strlcat) #define Perl_my_strlcat DPPP_(my_my_strlcat) #if defined(NEED_my_strlcat) || defined(NEED_my_strlcat_GLOBAL) Size_t DPPP_(my_my_strlcat)(char *dst, const char *src, Size_t size) { Size_t used, length, copy; used = strlen(dst); length = strlen(src); if (size > 0 && used < size - 1) { copy = (length >= size - used) ? size - used - 1 : length; memcpy(dst + used, src, copy); dst[used + copy] = '\0'; } return used + length; } #endif #endif #if !defined(my_strlcpy) #if defined(NEED_my_strlcpy) static Size_t DPPP_(my_my_strlcpy)(char * dst, const char * src, Size_t size); static #else extern Size_t DPPP_(my_my_strlcpy)(char * dst, const char * src, Size_t size); #endif #define my_strlcpy DPPP_(my_my_strlcpy) #define Perl_my_strlcpy DPPP_(my_my_strlcpy) #if defined(NEED_my_strlcpy) || defined(NEED_my_strlcpy_GLOBAL) Size_t DPPP_(my_my_strlcpy)(char *dst, const char *src, Size_t size) { Size_t length, copy; length = strlen(src); if (size > 0) { copy = (length >= size) ? size - 1 : length; memcpy(dst, src, copy); dst[copy] = '\0'; } return length; } #endif #endif #ifndef PERL_PV_ESCAPE_QUOTE # define PERL_PV_ESCAPE_QUOTE 0x0001 #endif #ifndef PERL_PV_PRETTY_QUOTE # define PERL_PV_PRETTY_QUOTE PERL_PV_ESCAPE_QUOTE #endif #ifndef PERL_PV_PRETTY_ELLIPSES # define PERL_PV_PRETTY_ELLIPSES 0x0002 #endif #ifndef PERL_PV_PRETTY_LTGT # define PERL_PV_PRETTY_LTGT 0x0004 #endif #ifndef PERL_PV_ESCAPE_FIRSTCHAR # define PERL_PV_ESCAPE_FIRSTCHAR 0x0008 #endif #ifndef PERL_PV_ESCAPE_UNI # define PERL_PV_ESCAPE_UNI 0x0100 #endif #ifndef PERL_PV_ESCAPE_UNI_DETECT # define PERL_PV_ESCAPE_UNI_DETECT 0x0200 #endif #ifndef PERL_PV_ESCAPE_ALL # define PERL_PV_ESCAPE_ALL 0x1000 #endif #ifndef PERL_PV_ESCAPE_NOBACKSLASH # define PERL_PV_ESCAPE_NOBACKSLASH 0x2000 #endif #ifndef PERL_PV_ESCAPE_NOCLEAR # define PERL_PV_ESCAPE_NOCLEAR 0x4000 #endif #ifndef PERL_PV_ESCAPE_RE # define PERL_PV_ESCAPE_RE 0x8000 #endif #ifndef PERL_PV_PRETTY_NOCLEAR # define PERL_PV_PRETTY_NOCLEAR PERL_PV_ESCAPE_NOCLEAR #endif #ifndef PERL_PV_PRETTY_DUMP # define PERL_PV_PRETTY_DUMP PERL_PV_PRETTY_ELLIPSES|PERL_PV_PRETTY_QUOTE #endif #ifndef PERL_PV_PRETTY_REGPROP # define PERL_PV_PRETTY_REGPROP PERL_PV_PRETTY_ELLIPSES|PERL_PV_PRETTY_LTGT|PERL_PV_ESCAPE_RE #endif /* Hint: pv_escape * Note that unicode functionality is only backported to * those perl versions that support it. For older perl * versions, the implementation will fall back to bytes. */ #ifndef pv_escape #if defined(NEED_pv_escape) static char * DPPP_(my_pv_escape)(pTHX_ SV * dsv, char const * const str, const STRLEN count, const STRLEN max, STRLEN * const escaped, const U32 flags); static #else extern char * DPPP_(my_pv_escape)(pTHX_ SV * dsv, char const * const str, const STRLEN count, const STRLEN max, STRLEN * const escaped, const U32 flags); #endif #ifdef pv_escape # undef pv_escape #endif #define pv_escape(a,b,c,d,e,f) DPPP_(my_pv_escape)(aTHX_ a,b,c,d,e,f) #define Perl_pv_escape DPPP_(my_pv_escape) #if defined(NEED_pv_escape) || defined(NEED_pv_escape_GLOBAL) char * DPPP_(my_pv_escape)(pTHX_ SV *dsv, char const * const str, const STRLEN count, const STRLEN max, STRLEN * const escaped, const U32 flags) { const char esc = flags & PERL_PV_ESCAPE_RE ? '%' : '\\'; const char dq = flags & PERL_PV_ESCAPE_QUOTE ? '"' : esc; char octbuf[32] = "%123456789ABCDF"; STRLEN wrote = 0; STRLEN chsize = 0; STRLEN readsize = 1; #if defined(is_utf8_string) && defined(utf8_to_uvchr) bool isuni = flags & PERL_PV_ESCAPE_UNI ? 1 : 0; #endif const char *pv = str; const char * const end = pv + count; octbuf[0] = esc; if (!(flags & PERL_PV_ESCAPE_NOCLEAR)) sv_setpvs(dsv, ""); #if defined(is_utf8_string) && defined(utf8_to_uvchr) if ((flags & PERL_PV_ESCAPE_UNI_DETECT) && is_utf8_string((U8*)pv, count)) isuni = 1; #endif for (; pv < end && (!max || wrote < max) ; pv += readsize) { const UV u = #if defined(is_utf8_string) && defined(utf8_to_uvchr) isuni ? utf8_to_uvchr((U8*)pv, &readsize) : #endif (U8)*pv; const U8 c = (U8)u & 0xFF; if (u > 255 || (flags & PERL_PV_ESCAPE_ALL)) { if (flags & PERL_PV_ESCAPE_FIRSTCHAR) chsize = my_snprintf(octbuf, sizeof octbuf, "%" UVxf, u); else chsize = my_snprintf(octbuf, sizeof octbuf, "%cx{%" UVxf "}", esc, u); } else if (flags & PERL_PV_ESCAPE_NOBACKSLASH) { chsize = 1; } else { if (c == dq || c == esc || !isPRINT(c)) { chsize = 2; switch (c) { case '\\' : /* fallthrough */ case '%' : if (c == esc) octbuf[1] = esc; else chsize = 1; break; case '\v' : octbuf[1] = 'v'; break; case '\t' : octbuf[1] = 't'; break; case '\r' : octbuf[1] = 'r'; break; case '\n' : octbuf[1] = 'n'; break; case '\f' : octbuf[1] = 'f'; break; case '"' : if (dq == '"') octbuf[1] = '"'; else chsize = 1; break; default: chsize = my_snprintf(octbuf, sizeof octbuf, pv < end && isDIGIT((U8)*(pv+readsize)) ? "%c%03o" : "%c%o", esc, c); } } else { chsize = 1; } } if (max && wrote + chsize > max) { break; } else if (chsize > 1) { sv_catpvn(dsv, octbuf, chsize); wrote += chsize; } else { char tmp[2]; my_snprintf(tmp, sizeof tmp, "%c", c); sv_catpvn(dsv, tmp, 1); wrote++; } if (flags & PERL_PV_ESCAPE_FIRSTCHAR) break; } if (escaped != NULL) *escaped= pv - str; return SvPVX(dsv); } #endif #endif #ifndef pv_pretty #if defined(NEED_pv_pretty) static char * DPPP_(my_pv_pretty)(pTHX_ SV * dsv, char const * const str, const STRLEN count, const STRLEN max, char const * const start_color, char const * const end_color, const U32 flags); static #else extern char * DPPP_(my_pv_pretty)(pTHX_ SV * dsv, char const * const str, const STRLEN count, const STRLEN max, char const * const start_color, char const * const end_color, const U32 flags); #endif #ifdef pv_pretty # undef pv_pretty #endif #define pv_pretty(a,b,c,d,e,f,g) DPPP_(my_pv_pretty)(aTHX_ a,b,c,d,e,f,g) #define Perl_pv_pretty DPPP_(my_pv_pretty) #if defined(NEED_pv_pretty) || defined(NEED_pv_pretty_GLOBAL) char * DPPP_(my_pv_pretty)(pTHX_ SV *dsv, char const * const str, const STRLEN count, const STRLEN max, char const * const start_color, char const * const end_color, const U32 flags) { const U8 dq = (flags & PERL_PV_PRETTY_QUOTE) ? '"' : '%'; STRLEN escaped; if (!(flags & PERL_PV_PRETTY_NOCLEAR)) sv_setpvs(dsv, ""); if (dq == '"') sv_catpvs(dsv, "\""); else if (flags & PERL_PV_PRETTY_LTGT) sv_catpvs(dsv, "<"); if (start_color != NULL) sv_catpv(dsv, D_PPP_CONSTPV_ARG(start_color)); pv_escape(dsv, str, count, max, &escaped, flags | PERL_PV_ESCAPE_NOCLEAR); if (end_color != NULL) sv_catpv(dsv, D_PPP_CONSTPV_ARG(end_color)); if (dq == '"') sv_catpvs(dsv, "\""); else if (flags & PERL_PV_PRETTY_LTGT) sv_catpvs(dsv, ">"); if ((flags & PERL_PV_PRETTY_ELLIPSES) && escaped < count) sv_catpvs(dsv, "..."); return SvPVX(dsv); } #endif #endif #ifndef pv_display #if defined(NEED_pv_display) static char * DPPP_(my_pv_display)(pTHX_ SV * dsv, const char * pv, STRLEN cur, STRLEN len, STRLEN pvlim); static #else extern char * DPPP_(my_pv_display)(pTHX_ SV * dsv, const char * pv, STRLEN cur, STRLEN len, STRLEN pvlim); #endif #ifdef pv_display # undef pv_display #endif #define pv_display(a,b,c,d,e) DPPP_(my_pv_display)(aTHX_ a,b,c,d,e) #define Perl_pv_display DPPP_(my_pv_display) #if defined(NEED_pv_display) || defined(NEED_pv_display_GLOBAL) char * DPPP_(my_pv_display)(pTHX_ SV *dsv, const char *pv, STRLEN cur, STRLEN len, STRLEN pvlim) { pv_pretty(dsv, pv, cur, pvlim, NULL, NULL, PERL_PV_PRETTY_DUMP); if (len > cur && pv[cur] == '\0') sv_catpvs(dsv, "\\0"); return SvPVX(dsv); } #endif #endif #endif /* _P_P_PORTABILITY_H_ */ /* End of File ppport.h */ nsca-ng-1.6/perl/t/000077500000000000000000000000001344421036200141125ustar00rootroot00000000000000nsca-ng-1.6/perl/t/001_load.t000077500000000000000000000003241344421036200156000ustar00rootroot00000000000000#!/usr/bin/perl use strict; use warnings; use Test::More tests => 2; BEGIN { use_ok('Net::NSCAng::Client'); } isa_ok(Net::NSCAng::Client->new('bogushost.invalid', 'none', 'none'), 'Net::NSCAng::Client'); nsca-ng-1.6/perl/t/Net-NSCAng-Client.t000066400000000000000000000036311344421036200173130ustar00rootroot00000000000000use strict; use warnings; use POSIX qw(setlocale LC_ALL); use Test::More tests => 14; use Test::Exception; use Config; use Net::NSCAng::Client; BEGIN { setlocale(LC_ALL, "C"); $Config{useithreads} and warn "WARNING: Net::NSCAng::Client is not thread safe but your perl has threads enabled!\n"; }; my @cparams = qw/ localhost myid s3cr3t /; my @nn = (node_name => 'here'); my @sd = (svc_description => 'bogus'); my $n; lives_ok(sub { $n = Net::NSCAng::Client->new(@cparams) }, 'Simple constructor'); dies_ok(sub { $n->host_result(0, "OK") }, 'host_result() dies w/o node_name'); dies_ok(sub { $n->svc_result(0, "OK") }, 'svc_result() dies w/o node_name'); lives_ok(sub { crf(sub { $n->host_result(0, "OK", @nn) })}, 'host_result() with local node_name'); dies_ok(sub { $n->svc_result(0, "OK", @nn) }, 'svc_result() still dies with local node_name'); lives_ok(sub { $n = Net::NSCAng::Client->new(@cparams, @nn) }, 'Constructor with node_name'); lives_ok(sub {crf(sub { $n->host_result(0, "OK") })}, 'host_result() with node_name from constructor'); dies_ok(sub { $n->svc_result(0, "OK") }, 'svc_result() dies w/o svc_description'); lives_ok(sub {crf(sub { $n->svc_result(0, "OK", @sd) })}, 'svc_result() with local svc_description'); lives_ok(sub { $n = Net::NSCAng::Client->new(@cparams, @nn, @sd) }, 'Constructor with node_name'); lives_ok(sub { crf(sub { $n->host_result(0, "OK") })}, 'host_result() OK w/o local params'); lives_ok(sub { crf(sub { $n->svc_result(0, "OK") })}, 'svc_result() OK w/o local params'); dies_ok(sub { $n->command("BOGUS_COMMAND;1;2;3") }, 'command() dies w/o argument'); lives_ok(sub {crf(sub { $n->command("BOGUS_COMMAND;1;2;3") })}, 'command() works'); # Connection-refused-filter # Supresses exceptions with a "connection refused" error as this is expected sub crf { my $sub = shift; eval { $sub->() }; if($@) { die $@ unless $@ =~ /SSL error:Connection refused/; } } nsca-ng-1.6/perl/t/manifest.t000066400000000000000000000007641344421036200161140ustar00rootroot00000000000000#!perl -T use 5.10.1; use strict; use warnings FATAL => 'all'; use Test::More; unless ( $ENV{RELEASE_TESTING} ) { plan( skip_all => "Author tests not required for installation" ); } my $min_tcm = 0.9; eval "use Test::CheckManifest $min_tcm"; plan skip_all => "Test::CheckManifest $min_tcm required" if $@; ok_manifest({ exclude => [ qw# /.git /.gitignore /Client.bs /Client.o /Client.c /client.o # ], filter => [ qr/\.sw[pqr]$/, qr/\.old$/, qr/\.tar.(?:bz2|gz|)$/ ], } ); nsca-ng-1.6/perl/t/pod.t000066400000000000000000000004021344421036200150550ustar00rootroot00000000000000#!perl -T use 5.10.1; use strict; use warnings FATAL => 'all'; use Test::More; # Ensure a recent version of Test::Pod my $min_tp = 1.22; eval "use Test::Pod $min_tp"; plan skip_all => "Test::Pod $min_tp required for testing POD" if $@; all_pod_files_ok(); nsca-ng-1.6/perl/typemap000066400000000000000000000001421344421036200152460ustar00rootroot00000000000000const char * T_PTROBJ Net::NSCAng::Client T_PTROBJ nscang_object_t T_PTROBJ nsca-ng-1.6/perl/uthash.h000066400000000000000000002075541344421036200153310ustar00rootroot00000000000000/* Copyright (c) 2003-2016, Troy D. Hanson http://troydhanson.github.com/uthash/ All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef UTHASH_H #define UTHASH_H #define UTHASH_VERSION 2.0.1 #include /* memcmp,strlen */ #include /* ptrdiff_t */ #include /* exit() */ /* These macros use decltype or the earlier __typeof GNU extension. As decltype is only available in newer compilers (VS2010 or gcc 4.3+ when compiling c++ source) this code uses whatever method is needed or, for VS2008 where neither is available, uses casting workarounds. */ #if defined(_MSC_VER) /* MS compiler */ #if _MSC_VER >= 1600 && defined(__cplusplus) /* VS2010 or newer in C++ mode */ #define DECLTYPE(x) (decltype(x)) #else /* VS2008 or older (or VS2010 in C mode) */ #define NO_DECLTYPE #define DECLTYPE(x) #endif #elif defined(__BORLANDC__) || defined(__LCC__) || defined(__WATCOMC__) #define NO_DECLTYPE #define DECLTYPE(x) #else /* GNU, Sun and other compilers */ #define DECLTYPE(x) (__typeof(x)) #endif #ifdef NO_DECLTYPE #define DECLTYPE_ASSIGN(dst,src) \ do { \ char **_da_dst = (char**)(&(dst)); \ *_da_dst = (char*)(src); \ } while (0) #else #define DECLTYPE_ASSIGN(dst,src) \ do { \ (dst) = DECLTYPE(dst)(src); \ } while (0) #endif /* a number of the hash function use uint32_t which isn't defined on Pre VS2010 */ #if defined(_WIN32) #if defined(_MSC_VER) && _MSC_VER >= 1600 #include #elif defined(__WATCOMC__) || defined(__MINGW32__) || defined(__CYGWIN__) #include #else typedef unsigned int uint32_t; typedef unsigned char uint8_t; #endif #elif defined(__GNUC__) && !defined(__VXWORKS__) #include #else typedef unsigned int uint32_t; typedef unsigned char uint8_t; #endif #ifndef uthash_fatal #define uthash_fatal(msg) exit(-1) /* fatal error (out of memory,etc) */ #endif #ifndef uthash_malloc #define uthash_malloc(sz) malloc(sz) /* malloc fcn */ #endif #ifndef uthash_free #define uthash_free(ptr,sz) free(ptr) /* free fcn */ #endif #ifndef uthash_strlen #define uthash_strlen(s) strlen(s) #endif #ifndef uthash_memcmp #define uthash_memcmp(a,b,n) memcmp(a,b,n) #endif #ifndef uthash_noexpand_fyi #define uthash_noexpand_fyi(tbl) /* can be defined to log noexpand */ #endif #ifndef uthash_expand_fyi #define uthash_expand_fyi(tbl) /* can be defined to log expands */ #endif /* initial number of buckets */ #define HASH_INITIAL_NUM_BUCKETS 32U /* initial number of buckets */ #define HASH_INITIAL_NUM_BUCKETS_LOG2 5U /* lg2 of initial number of buckets */ #define HASH_BKT_CAPACITY_THRESH 10U /* expand when bucket count reaches */ /* calculate the element whose hash handle address is hhp */ #define ELMT_FROM_HH(tbl,hhp) ((void*)(((char*)(hhp)) - ((tbl)->hho))) /* calculate the hash handle from element address elp */ #define HH_FROM_ELMT(tbl,elp) ((UT_hash_handle *)(((char*)(elp)) + ((tbl)->hho))) #define HASH_VALUE(keyptr,keylen,hashv) \ do { \ HASH_FCN(keyptr, keylen, hashv); \ } while (0) #define HASH_FIND_BYHASHVALUE(hh,head,keyptr,keylen,hashval,out) \ do { \ (out) = NULL; \ if (head) { \ unsigned _hf_bkt; \ HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _hf_bkt); \ if (HASH_BLOOM_TEST((head)->hh.tbl, hashval) != 0) { \ HASH_FIND_IN_BKT((head)->hh.tbl, hh, (head)->hh.tbl->buckets[ _hf_bkt ], keyptr, keylen, hashval, out); \ } \ } \ } while (0) #define HASH_FIND(hh,head,keyptr,keylen,out) \ do { \ unsigned _hf_hashv; \ HASH_VALUE(keyptr, keylen, _hf_hashv); \ HASH_FIND_BYHASHVALUE(hh, head, keyptr, keylen, _hf_hashv, out); \ } while (0) #ifdef HASH_BLOOM #define HASH_BLOOM_BITLEN (1UL << HASH_BLOOM) #define HASH_BLOOM_BYTELEN (HASH_BLOOM_BITLEN/8UL) + (((HASH_BLOOM_BITLEN%8UL)!=0UL) ? 1UL : 0UL) #define HASH_BLOOM_MAKE(tbl) \ do { \ (tbl)->bloom_nbits = HASH_BLOOM; \ (tbl)->bloom_bv = (uint8_t*)uthash_malloc(HASH_BLOOM_BYTELEN); \ if (!((tbl)->bloom_bv)) { uthash_fatal( "out of memory"); } \ memset((tbl)->bloom_bv, 0, HASH_BLOOM_BYTELEN); \ (tbl)->bloom_sig = HASH_BLOOM_SIGNATURE; \ } while (0) #define HASH_BLOOM_FREE(tbl) \ do { \ uthash_free((tbl)->bloom_bv, HASH_BLOOM_BYTELEN); \ } while (0) #define HASH_BLOOM_BITSET(bv,idx) (bv[(idx)/8U] |= (1U << ((idx)%8U))) #define HASH_BLOOM_BITTEST(bv,idx) (bv[(idx)/8U] & (1U << ((idx)%8U))) #define HASH_BLOOM_ADD(tbl,hashv) \ HASH_BLOOM_BITSET((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1U))) #define HASH_BLOOM_TEST(tbl,hashv) \ HASH_BLOOM_BITTEST((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1U))) #else #define HASH_BLOOM_MAKE(tbl) #define HASH_BLOOM_FREE(tbl) #define HASH_BLOOM_ADD(tbl,hashv) #define HASH_BLOOM_TEST(tbl,hashv) (1) #define HASH_BLOOM_BYTELEN 0U #endif #define HASH_MAKE_TABLE(hh,head) \ do { \ (head)->hh.tbl = (UT_hash_table*)uthash_malloc( \ sizeof(UT_hash_table)); \ if (!((head)->hh.tbl)) { uthash_fatal( "out of memory"); } \ memset((head)->hh.tbl, 0, sizeof(UT_hash_table)); \ (head)->hh.tbl->tail = &((head)->hh); \ (head)->hh.tbl->num_buckets = HASH_INITIAL_NUM_BUCKETS; \ (head)->hh.tbl->log2_num_buckets = HASH_INITIAL_NUM_BUCKETS_LOG2; \ (head)->hh.tbl->hho = (char*)(&(head)->hh) - (char*)(head); \ (head)->hh.tbl->buckets = (UT_hash_bucket*)uthash_malloc( \ HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket)); \ if (! (head)->hh.tbl->buckets) { uthash_fatal( "out of memory"); } \ memset((head)->hh.tbl->buckets, 0, \ HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket)); \ HASH_BLOOM_MAKE((head)->hh.tbl); \ (head)->hh.tbl->signature = HASH_SIGNATURE; \ } while (0) #define HASH_REPLACE_BYHASHVALUE_INORDER(hh,head,fieldname,keylen_in,hashval,add,replaced,cmpfcn) \ do { \ (replaced) = NULL; \ HASH_FIND_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, replaced); \ if (replaced) { \ HASH_DELETE(hh, head, replaced); \ } \ HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, &((add)->fieldname), keylen_in, hashval, add, cmpfcn); \ } while (0) #define HASH_REPLACE_BYHASHVALUE(hh,head,fieldname,keylen_in,hashval,add,replaced) \ do { \ (replaced) = NULL; \ HASH_FIND_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, replaced); \ if (replaced) { \ HASH_DELETE(hh, head, replaced); \ } \ HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, add); \ } while (0) #define HASH_REPLACE(hh,head,fieldname,keylen_in,add,replaced) \ do { \ unsigned _hr_hashv; \ HASH_VALUE(&((add)->fieldname), keylen_in, _hr_hashv); \ HASH_REPLACE_BYHASHVALUE(hh, head, fieldname, keylen_in, _hr_hashv, add, replaced); \ } while (0) #define HASH_REPLACE_INORDER(hh,head,fieldname,keylen_in,add,replaced,cmpfcn) \ do { \ unsigned _hr_hashv; \ HASH_VALUE(&((add)->fieldname), keylen_in, _hr_hashv); \ HASH_REPLACE_BYHASHVALUE_INORDER(hh, head, fieldname, keylen_in, _hr_hashv, add, replaced, cmpfcn); \ } while (0) #define HASH_APPEND_LIST(hh, head, add) \ do { \ (add)->hh.next = NULL; \ (add)->hh.prev = ELMT_FROM_HH((head)->hh.tbl, (head)->hh.tbl->tail); \ (head)->hh.tbl->tail->next = (add); \ (head)->hh.tbl->tail = &((add)->hh); \ } while (0) #define HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh,head,keyptr,keylen_in,hashval,add,cmpfcn) \ do { \ unsigned _ha_bkt; \ (add)->hh.hashv = (hashval); \ (add)->hh.key = (char*) (keyptr); \ (add)->hh.keylen = (unsigned) (keylen_in); \ if (!(head)) { \ (add)->hh.next = NULL; \ (add)->hh.prev = NULL; \ (head) = (add); \ HASH_MAKE_TABLE(hh, head); \ } else { \ struct UT_hash_handle *_hs_iter = &(head)->hh; \ (add)->hh.tbl = (head)->hh.tbl; \ do { \ if (cmpfcn(DECLTYPE(head) ELMT_FROM_HH((head)->hh.tbl, _hs_iter), add) > 0) \ break; \ } while ((_hs_iter = _hs_iter->next)); \ if (_hs_iter) { \ (add)->hh.next = _hs_iter; \ if (((add)->hh.prev = _hs_iter->prev)) { \ HH_FROM_ELMT((head)->hh.tbl, _hs_iter->prev)->next = (add); \ } else { \ (head) = (add); \ } \ _hs_iter->prev = (add); \ } else { \ HASH_APPEND_LIST(hh, head, add); \ } \ } \ (head)->hh.tbl->num_items++; \ HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _ha_bkt); \ HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt], &(add)->hh); \ HASH_BLOOM_ADD((head)->hh.tbl, hashval); \ HASH_EMIT_KEY(hh, head, keyptr, keylen_in); \ HASH_FSCK(hh, head); \ } while (0) #define HASH_ADD_KEYPTR_INORDER(hh,head,keyptr,keylen_in,add,cmpfcn) \ do { \ unsigned _hs_hashv; \ HASH_VALUE(keyptr, keylen_in, _hs_hashv); \ HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, keyptr, keylen_in, _hs_hashv, add, cmpfcn); \ } while (0) #define HASH_ADD_BYHASHVALUE_INORDER(hh,head,fieldname,keylen_in,hashval,add,cmpfcn) \ HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, &((add)->fieldname), keylen_in, hashval, add, cmpfcn) #define HASH_ADD_INORDER(hh,head,fieldname,keylen_in,add,cmpfcn) \ HASH_ADD_KEYPTR_INORDER(hh, head, &((add)->fieldname), keylen_in, add, cmpfcn) #define HASH_ADD_KEYPTR_BYHASHVALUE(hh,head,keyptr,keylen_in,hashval,add) \ do { \ unsigned _ha_bkt; \ (add)->hh.hashv = (hashval); \ (add)->hh.key = (char*) (keyptr); \ (add)->hh.keylen = (unsigned) (keylen_in); \ if (!(head)) { \ (add)->hh.next = NULL; \ (add)->hh.prev = NULL; \ (head) = (add); \ HASH_MAKE_TABLE(hh, head); \ } else { \ (add)->hh.tbl = (head)->hh.tbl; \ HASH_APPEND_LIST(hh, head, add); \ } \ (head)->hh.tbl->num_items++; \ HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _ha_bkt); \ HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt], &(add)->hh); \ HASH_BLOOM_ADD((head)->hh.tbl, hashval); \ HASH_EMIT_KEY(hh, head, keyptr, keylen_in); \ HASH_FSCK(hh, head); \ } while (0) #define HASH_ADD_KEYPTR(hh,head,keyptr,keylen_in,add) \ do { \ unsigned _ha_hashv; \ HASH_VALUE(keyptr, keylen_in, _ha_hashv); \ HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, keyptr, keylen_in, _ha_hashv, add); \ } while (0) #define HASH_ADD_BYHASHVALUE(hh,head,fieldname,keylen_in,hashval,add) \ HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, add) #define HASH_ADD(hh,head,fieldname,keylen_in,add) \ HASH_ADD_KEYPTR(hh, head, &((add)->fieldname), keylen_in, add) #define HASH_TO_BKT(hashv,num_bkts,bkt) \ do { \ bkt = ((hashv) & ((num_bkts) - 1U)); \ } while (0) /* delete "delptr" from the hash table. * "the usual" patch-up process for the app-order doubly-linked-list. * The use of _hd_hh_del below deserves special explanation. * These used to be expressed using (delptr) but that led to a bug * if someone used the same symbol for the head and deletee, like * HASH_DELETE(hh,users,users); * We want that to work, but by changing the head (users) below * we were forfeiting our ability to further refer to the deletee (users) * in the patch-up process. Solution: use scratch space to * copy the deletee pointer, then the latter references are via that * scratch pointer rather than through the repointed (users) symbol. */ #define HASH_DELETE(hh,head,delptr) \ do { \ struct UT_hash_handle *_hd_hh_del; \ if ( ((delptr)->hh.prev == NULL) && ((delptr)->hh.next == NULL) ) { \ uthash_free((head)->hh.tbl->buckets, \ (head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket) ); \ HASH_BLOOM_FREE((head)->hh.tbl); \ uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ head = NULL; \ } else { \ unsigned _hd_bkt; \ _hd_hh_del = &((delptr)->hh); \ if ((delptr) == ELMT_FROM_HH((head)->hh.tbl,(head)->hh.tbl->tail)) { \ (head)->hh.tbl->tail = \ (UT_hash_handle*)((ptrdiff_t)((delptr)->hh.prev) + \ (head)->hh.tbl->hho); \ } \ if ((delptr)->hh.prev != NULL) { \ ((UT_hash_handle*)((ptrdiff_t)((delptr)->hh.prev) + \ (head)->hh.tbl->hho))->next = (delptr)->hh.next; \ } else { \ DECLTYPE_ASSIGN(head,(delptr)->hh.next); \ } \ if (_hd_hh_del->next != NULL) { \ ((UT_hash_handle*)((ptrdiff_t)_hd_hh_del->next + \ (head)->hh.tbl->hho))->prev = \ _hd_hh_del->prev; \ } \ HASH_TO_BKT( _hd_hh_del->hashv, (head)->hh.tbl->num_buckets, _hd_bkt); \ HASH_DEL_IN_BKT(hh,(head)->hh.tbl->buckets[_hd_bkt], _hd_hh_del); \ (head)->hh.tbl->num_items--; \ } \ HASH_FSCK(hh,head); \ } while (0) /* convenience forms of HASH_FIND/HASH_ADD/HASH_DEL */ #define HASH_FIND_STR(head,findstr,out) \ HASH_FIND(hh,head,findstr,(unsigned)uthash_strlen(findstr),out) #define HASH_ADD_STR(head,strfield,add) \ HASH_ADD(hh,head,strfield[0],(unsigned)uthash_strlen(add->strfield),add) #define HASH_REPLACE_STR(head,strfield,add,replaced) \ HASH_REPLACE(hh,head,strfield[0],(unsigned)uthash_strlen(add->strfield),add,replaced) #define HASH_FIND_INT(head,findint,out) \ HASH_FIND(hh,head,findint,sizeof(int),out) #define HASH_ADD_INT(head,intfield,add) \ HASH_ADD(hh,head,intfield,sizeof(int),add) #define HASH_REPLACE_INT(head,intfield,add,replaced) \ HASH_REPLACE(hh,head,intfield,sizeof(int),add,replaced) #define HASH_FIND_PTR(head,findptr,out) \ HASH_FIND(hh,head,findptr,sizeof(void *),out) #define HASH_ADD_PTR(head,ptrfield,add) \ HASH_ADD(hh,head,ptrfield,sizeof(void *),add) #define HASH_REPLACE_PTR(head,ptrfield,add,replaced) \ HASH_REPLACE(hh,head,ptrfield,sizeof(void *),add,replaced) #define HASH_DEL(head,delptr) \ HASH_DELETE(hh,head,delptr) /* HASH_FSCK checks hash integrity on every add/delete when HASH_DEBUG is defined. * This is for uthash developer only; it compiles away if HASH_DEBUG isn't defined. */ #ifdef HASH_DEBUG #define HASH_OOPS(...) do { fprintf(stderr,__VA_ARGS__); exit(-1); } while (0) #define HASH_FSCK(hh,head) \ do { \ struct UT_hash_handle *_thh; \ if (head) { \ unsigned _bkt_i; \ unsigned _count; \ char *_prev; \ _count = 0; \ for( _bkt_i = 0; _bkt_i < (head)->hh.tbl->num_buckets; _bkt_i++) { \ unsigned _bkt_count = 0; \ _thh = (head)->hh.tbl->buckets[_bkt_i].hh_head; \ _prev = NULL; \ while (_thh) { \ if (_prev != (char*)(_thh->hh_prev)) { \ HASH_OOPS("invalid hh_prev %p, actual %p\n", \ _thh->hh_prev, _prev ); \ } \ _bkt_count++; \ _prev = (char*)(_thh); \ _thh = _thh->hh_next; \ } \ _count += _bkt_count; \ if ((head)->hh.tbl->buckets[_bkt_i].count != _bkt_count) { \ HASH_OOPS("invalid bucket count %u, actual %u\n", \ (head)->hh.tbl->buckets[_bkt_i].count, _bkt_count); \ } \ } \ if (_count != (head)->hh.tbl->num_items) { \ HASH_OOPS("invalid hh item count %u, actual %u\n", \ (head)->hh.tbl->num_items, _count ); \ } \ /* traverse hh in app order; check next/prev integrity, count */ \ _count = 0; \ _prev = NULL; \ _thh = &(head)->hh; \ while (_thh) { \ _count++; \ if (_prev !=(char*)(_thh->prev)) { \ HASH_OOPS("invalid prev %p, actual %p\n", \ _thh->prev, _prev ); \ } \ _prev = (char*)ELMT_FROM_HH((head)->hh.tbl, _thh); \ _thh = ( _thh->next ? (UT_hash_handle*)((char*)(_thh->next) + \ (head)->hh.tbl->hho) : NULL ); \ } \ if (_count != (head)->hh.tbl->num_items) { \ HASH_OOPS("invalid app item count %u, actual %u\n", \ (head)->hh.tbl->num_items, _count ); \ } \ } \ } while (0) #else #define HASH_FSCK(hh,head) #endif /* When compiled with -DHASH_EMIT_KEYS, length-prefixed keys are emitted to * the descriptor to which this macro is defined for tuning the hash function. * The app can #include to get the prototype for write(2). */ #ifdef HASH_EMIT_KEYS #define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) \ do { \ unsigned _klen = fieldlen; \ write(HASH_EMIT_KEYS, &_klen, sizeof(_klen)); \ write(HASH_EMIT_KEYS, keyptr, (unsigned long)fieldlen); \ } while (0) #else #define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) #endif /* default to Jenkin's hash unless overridden e.g. DHASH_FUNCTION=HASH_SAX */ #ifdef HASH_FUNCTION #define HASH_FCN HASH_FUNCTION #else #define HASH_FCN HASH_JEN #endif /* The Bernstein hash function, used in Perl prior to v5.6. Note (x<<5+x)=x*33. */ #define HASH_BER(key,keylen,hashv) \ do { \ unsigned _hb_keylen=(unsigned)keylen; \ const unsigned char *_hb_key=(const unsigned char*)(key); \ (hashv) = 0; \ while (_hb_keylen-- != 0U) { \ (hashv) = (((hashv) << 5) + (hashv)) + *_hb_key++; \ } \ } while (0) /* SAX/FNV/OAT/JEN hash functions are macro variants of those listed at * http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx */ #define HASH_SAX(key,keylen,hashv) \ do { \ unsigned _sx_i; \ const unsigned char *_hs_key=(const unsigned char*)(key); \ hashv = 0; \ for(_sx_i=0; _sx_i < keylen; _sx_i++) { \ hashv ^= (hashv << 5) + (hashv >> 2) + _hs_key[_sx_i]; \ } \ } while (0) /* FNV-1a variation */ #define HASH_FNV(key,keylen,hashv) \ do { \ unsigned _fn_i; \ const unsigned char *_hf_key=(const unsigned char*)(key); \ hashv = 2166136261U; \ for(_fn_i=0; _fn_i < keylen; _fn_i++) { \ hashv = hashv ^ _hf_key[_fn_i]; \ hashv = hashv * 16777619U; \ } \ } while (0) #define HASH_OAT(key,keylen,hashv) \ do { \ unsigned _ho_i; \ const unsigned char *_ho_key=(const unsigned char*)(key); \ hashv = 0; \ for(_ho_i=0; _ho_i < keylen; _ho_i++) { \ hashv += _ho_key[_ho_i]; \ hashv += (hashv << 10); \ hashv ^= (hashv >> 6); \ } \ hashv += (hashv << 3); \ hashv ^= (hashv >> 11); \ hashv += (hashv << 15); \ } while (0) #define HASH_JEN_MIX(a,b,c) \ do { \ a -= b; a -= c; a ^= ( c >> 13 ); \ b -= c; b -= a; b ^= ( a << 8 ); \ c -= a; c -= b; c ^= ( b >> 13 ); \ a -= b; a -= c; a ^= ( c >> 12 ); \ b -= c; b -= a; b ^= ( a << 16 ); \ c -= a; c -= b; c ^= ( b >> 5 ); \ a -= b; a -= c; a ^= ( c >> 3 ); \ b -= c; b -= a; b ^= ( a << 10 ); \ c -= a; c -= b; c ^= ( b >> 15 ); \ } while (0) #define HASH_JEN(key,keylen,hashv) \ do { \ unsigned _hj_i,_hj_j,_hj_k; \ unsigned const char *_hj_key=(unsigned const char*)(key); \ hashv = 0xfeedbeefu; \ _hj_i = _hj_j = 0x9e3779b9u; \ _hj_k = (unsigned)(keylen); \ while (_hj_k >= 12U) { \ _hj_i += (_hj_key[0] + ( (unsigned)_hj_key[1] << 8 ) \ + ( (unsigned)_hj_key[2] << 16 ) \ + ( (unsigned)_hj_key[3] << 24 ) ); \ _hj_j += (_hj_key[4] + ( (unsigned)_hj_key[5] << 8 ) \ + ( (unsigned)_hj_key[6] << 16 ) \ + ( (unsigned)_hj_key[7] << 24 ) ); \ hashv += (_hj_key[8] + ( (unsigned)_hj_key[9] << 8 ) \ + ( (unsigned)_hj_key[10] << 16 ) \ + ( (unsigned)_hj_key[11] << 24 ) ); \ \ HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ \ _hj_key += 12; \ _hj_k -= 12U; \ } \ hashv += (unsigned)(keylen); \ switch ( _hj_k ) { \ case 11: hashv += ( (unsigned)_hj_key[10] << 24 ); /* FALLTHROUGH */ \ case 10: hashv += ( (unsigned)_hj_key[9] << 16 ); /* FALLTHROUGH */ \ case 9: hashv += ( (unsigned)_hj_key[8] << 8 ); /* FALLTHROUGH */ \ case 8: _hj_j += ( (unsigned)_hj_key[7] << 24 ); /* FALLTHROUGH */ \ case 7: _hj_j += ( (unsigned)_hj_key[6] << 16 ); /* FALLTHROUGH */ \ case 6: _hj_j += ( (unsigned)_hj_key[5] << 8 ); /* FALLTHROUGH */ \ case 5: _hj_j += _hj_key[4]; /* FALLTHROUGH */ \ case 4: _hj_i += ( (unsigned)_hj_key[3] << 24 ); /* FALLTHROUGH */ \ case 3: _hj_i += ( (unsigned)_hj_key[2] << 16 ); /* FALLTHROUGH */ \ case 2: _hj_i += ( (unsigned)_hj_key[1] << 8 ); /* FALLTHROUGH */ \ case 1: _hj_i += _hj_key[0]; \ } \ HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ } while (0) /* The Paul Hsieh hash function */ #undef get16bits #if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) \ || defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__) #define get16bits(d) (*((const uint16_t *) (d))) #endif #if !defined (get16bits) #define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8) \ +(uint32_t)(((const uint8_t *)(d))[0]) ) #endif #define HASH_SFH(key,keylen,hashv) \ do { \ unsigned const char *_sfh_key=(unsigned const char*)(key); \ uint32_t _sfh_tmp, _sfh_len = (uint32_t)keylen; \ \ unsigned _sfh_rem = _sfh_len & 3U; \ _sfh_len >>= 2; \ hashv = 0xcafebabeu; \ \ /* Main loop */ \ for (;_sfh_len > 0U; _sfh_len--) { \ hashv += get16bits (_sfh_key); \ _sfh_tmp = ((uint32_t)(get16bits (_sfh_key+2)) << 11) ^ hashv; \ hashv = (hashv << 16) ^ _sfh_tmp; \ _sfh_key += 2U*sizeof (uint16_t); \ hashv += hashv >> 11; \ } \ \ /* Handle end cases */ \ switch (_sfh_rem) { \ case 3: hashv += get16bits (_sfh_key); \ hashv ^= hashv << 16; \ hashv ^= (uint32_t)(_sfh_key[sizeof (uint16_t)]) << 18; \ hashv += hashv >> 11; \ break; \ case 2: hashv += get16bits (_sfh_key); \ hashv ^= hashv << 11; \ hashv += hashv >> 17; \ break; \ case 1: hashv += *_sfh_key; \ hashv ^= hashv << 10; \ hashv += hashv >> 1; \ } \ \ /* Force "avalanching" of final 127 bits */ \ hashv ^= hashv << 3; \ hashv += hashv >> 5; \ hashv ^= hashv << 4; \ hashv += hashv >> 17; \ hashv ^= hashv << 25; \ hashv += hashv >> 6; \ } while (0) #ifdef HASH_USING_NO_STRICT_ALIASING /* The MurmurHash exploits some CPU's (x86,x86_64) tolerance for unaligned reads. * For other types of CPU's (e.g. Sparc) an unaligned read causes a bus error. * MurmurHash uses the faster approach only on CPU's where we know it's safe. * * Note the preprocessor built-in defines can be emitted using: * * gcc -m64 -dM -E - < /dev/null (on gcc) * cc -## a.c (where a.c is a simple test file) (Sun Studio) */ #if (defined(__i386__) || defined(__x86_64__) || defined(_M_IX86)) #define MUR_GETBLOCK(p,i) p[i] #else /* non intel */ #define MUR_PLUS0_ALIGNED(p) (((unsigned long)p & 3UL) == 0UL) #define MUR_PLUS1_ALIGNED(p) (((unsigned long)p & 3UL) == 1UL) #define MUR_PLUS2_ALIGNED(p) (((unsigned long)p & 3UL) == 2UL) #define MUR_PLUS3_ALIGNED(p) (((unsigned long)p & 3UL) == 3UL) #define WP(p) ((uint32_t*)((unsigned long)(p) & ~3UL)) #if (defined(__BIG_ENDIAN__) || defined(SPARC) || defined(__ppc__) || defined(__ppc64__)) #define MUR_THREE_ONE(p) ((((*WP(p))&0x00ffffff) << 8) | (((*(WP(p)+1))&0xff000000) >> 24)) #define MUR_TWO_TWO(p) ((((*WP(p))&0x0000ffff) <<16) | (((*(WP(p)+1))&0xffff0000) >> 16)) #define MUR_ONE_THREE(p) ((((*WP(p))&0x000000ff) <<24) | (((*(WP(p)+1))&0xffffff00) >> 8)) #else /* assume little endian non-intel */ #define MUR_THREE_ONE(p) ((((*WP(p))&0xffffff00) >> 8) | (((*(WP(p)+1))&0x000000ff) << 24)) #define MUR_TWO_TWO(p) ((((*WP(p))&0xffff0000) >>16) | (((*(WP(p)+1))&0x0000ffff) << 16)) #define MUR_ONE_THREE(p) ((((*WP(p))&0xff000000) >>24) | (((*(WP(p)+1))&0x00ffffff) << 8)) #endif #define MUR_GETBLOCK(p,i) (MUR_PLUS0_ALIGNED(p) ? ((p)[i]) : \ (MUR_PLUS1_ALIGNED(p) ? MUR_THREE_ONE(p) : \ (MUR_PLUS2_ALIGNED(p) ? MUR_TWO_TWO(p) : \ MUR_ONE_THREE(p)))) #endif #define MUR_ROTL32(x,r) (((x) << (r)) | ((x) >> (32 - (r)))) #define MUR_FMIX(_h) \ do { \ _h ^= _h >> 16; \ _h *= 0x85ebca6bu; \ _h ^= _h >> 13; \ _h *= 0xc2b2ae35u; \ _h ^= _h >> 16; \ } while (0) #define HASH_MUR(key,keylen,hashv) \ do { \ const uint8_t *_mur_data = (const uint8_t*)(key); \ const int _mur_nblocks = (int)(keylen) / 4; \ uint32_t _mur_h1 = 0xf88D5353u; \ uint32_t _mur_c1 = 0xcc9e2d51u; \ uint32_t _mur_c2 = 0x1b873593u; \ uint32_t _mur_k1 = 0; \ const uint8_t *_mur_tail; \ const uint32_t *_mur_blocks = (const uint32_t*)(_mur_data+(_mur_nblocks*4)); \ int _mur_i; \ for(_mur_i = -_mur_nblocks; _mur_i!=0; _mur_i++) { \ _mur_k1 = MUR_GETBLOCK(_mur_blocks,_mur_i); \ _mur_k1 *= _mur_c1; \ _mur_k1 = MUR_ROTL32(_mur_k1,15); \ _mur_k1 *= _mur_c2; \ \ _mur_h1 ^= _mur_k1; \ _mur_h1 = MUR_ROTL32(_mur_h1,13); \ _mur_h1 = (_mur_h1*5U) + 0xe6546b64u; \ } \ _mur_tail = (const uint8_t*)(_mur_data + (_mur_nblocks*4)); \ _mur_k1=0; \ switch((keylen) & 3U) { \ case 3: _mur_k1 ^= (uint32_t)_mur_tail[2] << 16; /* FALLTHROUGH */ \ case 2: _mur_k1 ^= (uint32_t)_mur_tail[1] << 8; /* FALLTHROUGH */ \ case 1: _mur_k1 ^= (uint32_t)_mur_tail[0]; \ _mur_k1 *= _mur_c1; \ _mur_k1 = MUR_ROTL32(_mur_k1,15); \ _mur_k1 *= _mur_c2; \ _mur_h1 ^= _mur_k1; \ } \ _mur_h1 ^= (uint32_t)(keylen); \ MUR_FMIX(_mur_h1); \ hashv = _mur_h1; \ } while (0) #endif /* HASH_USING_NO_STRICT_ALIASING */ /* iterate over items in a known bucket to find desired item */ #define HASH_FIND_IN_BKT(tbl,hh,head,keyptr,keylen_in,hashval,out) \ do { \ if ((head).hh_head != NULL) { \ DECLTYPE_ASSIGN(out, ELMT_FROM_HH(tbl, (head).hh_head)); \ } else { \ (out) = NULL; \ } \ while ((out) != NULL) { \ if ((out)->hh.hashv == (hashval) && (out)->hh.keylen == (keylen_in)) { \ if (uthash_memcmp((out)->hh.key, keyptr, keylen_in) == 0) { \ break; \ } \ } \ if ((out)->hh.hh_next != NULL) { \ DECLTYPE_ASSIGN(out, ELMT_FROM_HH(tbl, (out)->hh.hh_next)); \ } else { \ (out) = NULL; \ } \ } \ } while (0) /* add an item to a bucket */ #define HASH_ADD_TO_BKT(head,addhh) \ do { \ head.count++; \ (addhh)->hh_next = head.hh_head; \ (addhh)->hh_prev = NULL; \ if (head.hh_head != NULL) { (head).hh_head->hh_prev = (addhh); } \ (head).hh_head=addhh; \ if ((head.count >= ((head.expand_mult+1U) * HASH_BKT_CAPACITY_THRESH)) \ && ((addhh)->tbl->noexpand != 1U)) { \ HASH_EXPAND_BUCKETS((addhh)->tbl); \ } \ } while (0) /* remove an item from a given bucket */ #define HASH_DEL_IN_BKT(hh,head,hh_del) \ (head).count--; \ if ((head).hh_head == hh_del) { \ (head).hh_head = hh_del->hh_next; \ } \ if (hh_del->hh_prev) { \ hh_del->hh_prev->hh_next = hh_del->hh_next; \ } \ if (hh_del->hh_next) { \ hh_del->hh_next->hh_prev = hh_del->hh_prev; \ } /* Bucket expansion has the effect of doubling the number of buckets * and redistributing the items into the new buckets. Ideally the * items will distribute more or less evenly into the new buckets * (the extent to which this is true is a measure of the quality of * the hash function as it applies to the key domain). * * With the items distributed into more buckets, the chain length * (item count) in each bucket is reduced. Thus by expanding buckets * the hash keeps a bound on the chain length. This bounded chain * length is the essence of how a hash provides constant time lookup. * * The calculation of tbl->ideal_chain_maxlen below deserves some * explanation. First, keep in mind that we're calculating the ideal * maximum chain length based on the *new* (doubled) bucket count. * In fractions this is just n/b (n=number of items,b=new num buckets). * Since the ideal chain length is an integer, we want to calculate * ceil(n/b). We don't depend on floating point arithmetic in this * hash, so to calculate ceil(n/b) with integers we could write * * ceil(n/b) = (n/b) + ((n%b)?1:0) * * and in fact a previous version of this hash did just that. * But now we have improved things a bit by recognizing that b is * always a power of two. We keep its base 2 log handy (call it lb), * so now we can write this with a bit shift and logical AND: * * ceil(n/b) = (n>>lb) + ( (n & (b-1)) ? 1:0) * */ #define HASH_EXPAND_BUCKETS(tbl) \ do { \ unsigned _he_bkt; \ unsigned _he_bkt_i; \ struct UT_hash_handle *_he_thh, *_he_hh_nxt; \ UT_hash_bucket *_he_new_buckets, *_he_newbkt; \ _he_new_buckets = (UT_hash_bucket*)uthash_malloc( \ 2UL * tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ if (!_he_new_buckets) { uthash_fatal( "out of memory"); } \ memset(_he_new_buckets, 0, \ 2UL * tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ tbl->ideal_chain_maxlen = \ (tbl->num_items >> (tbl->log2_num_buckets+1U)) + \ (((tbl->num_items & ((tbl->num_buckets*2U)-1U)) != 0U) ? 1U : 0U); \ tbl->nonideal_items = 0; \ for(_he_bkt_i = 0; _he_bkt_i < tbl->num_buckets; _he_bkt_i++) \ { \ _he_thh = tbl->buckets[ _he_bkt_i ].hh_head; \ while (_he_thh != NULL) { \ _he_hh_nxt = _he_thh->hh_next; \ HASH_TO_BKT( _he_thh->hashv, tbl->num_buckets*2U, _he_bkt); \ _he_newbkt = &(_he_new_buckets[ _he_bkt ]); \ if (++(_he_newbkt->count) > tbl->ideal_chain_maxlen) { \ tbl->nonideal_items++; \ _he_newbkt->expand_mult = _he_newbkt->count / \ tbl->ideal_chain_maxlen; \ } \ _he_thh->hh_prev = NULL; \ _he_thh->hh_next = _he_newbkt->hh_head; \ if (_he_newbkt->hh_head != NULL) { _he_newbkt->hh_head->hh_prev = \ _he_thh; } \ _he_newbkt->hh_head = _he_thh; \ _he_thh = _he_hh_nxt; \ } \ } \ uthash_free( tbl->buckets, tbl->num_buckets*sizeof(struct UT_hash_bucket) ); \ tbl->num_buckets *= 2U; \ tbl->log2_num_buckets++; \ tbl->buckets = _he_new_buckets; \ tbl->ineff_expands = (tbl->nonideal_items > (tbl->num_items >> 1)) ? \ (tbl->ineff_expands+1U) : 0U; \ if (tbl->ineff_expands > 1U) { \ tbl->noexpand=1; \ uthash_noexpand_fyi(tbl); \ } \ uthash_expand_fyi(tbl); \ } while (0) /* This is an adaptation of Simon Tatham's O(n log(n)) mergesort */ /* Note that HASH_SORT assumes the hash handle name to be hh. * HASH_SRT was added to allow the hash handle name to be passed in. */ #define HASH_SORT(head,cmpfcn) HASH_SRT(hh,head,cmpfcn) #define HASH_SRT(hh,head,cmpfcn) \ do { \ unsigned _hs_i; \ unsigned _hs_looping,_hs_nmerges,_hs_insize,_hs_psize,_hs_qsize; \ struct UT_hash_handle *_hs_p, *_hs_q, *_hs_e, *_hs_list, *_hs_tail; \ if (head != NULL) { \ _hs_insize = 1; \ _hs_looping = 1; \ _hs_list = &((head)->hh); \ while (_hs_looping != 0U) { \ _hs_p = _hs_list; \ _hs_list = NULL; \ _hs_tail = NULL; \ _hs_nmerges = 0; \ while (_hs_p != NULL) { \ _hs_nmerges++; \ _hs_q = _hs_p; \ _hs_psize = 0; \ for ( _hs_i = 0; _hs_i < _hs_insize; _hs_i++ ) { \ _hs_psize++; \ _hs_q = (UT_hash_handle*)((_hs_q->next != NULL) ? \ ((void*)((char*)(_hs_q->next) + \ (head)->hh.tbl->hho)) : NULL); \ if (! (_hs_q) ) { break; } \ } \ _hs_qsize = _hs_insize; \ while ((_hs_psize > 0U) || ((_hs_qsize > 0U) && (_hs_q != NULL))) {\ if (_hs_psize == 0U) { \ _hs_e = _hs_q; \ _hs_q = (UT_hash_handle*)((_hs_q->next != NULL) ? \ ((void*)((char*)(_hs_q->next) + \ (head)->hh.tbl->hho)) : NULL); \ _hs_qsize--; \ } else if ( (_hs_qsize == 0U) || (_hs_q == NULL) ) { \ _hs_e = _hs_p; \ if (_hs_p != NULL){ \ _hs_p = (UT_hash_handle*)((_hs_p->next != NULL) ? \ ((void*)((char*)(_hs_p->next) + \ (head)->hh.tbl->hho)) : NULL); \ } \ _hs_psize--; \ } else if (( \ cmpfcn(DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl,_hs_p)), \ DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl,_hs_q))) \ ) <= 0) { \ _hs_e = _hs_p; \ if (_hs_p != NULL){ \ _hs_p = (UT_hash_handle*)((_hs_p->next != NULL) ? \ ((void*)((char*)(_hs_p->next) + \ (head)->hh.tbl->hho)) : NULL); \ } \ _hs_psize--; \ } else { \ _hs_e = _hs_q; \ _hs_q = (UT_hash_handle*)((_hs_q->next != NULL) ? \ ((void*)((char*)(_hs_q->next) + \ (head)->hh.tbl->hho)) : NULL); \ _hs_qsize--; \ } \ if ( _hs_tail != NULL ) { \ _hs_tail->next = ((_hs_e != NULL) ? \ ELMT_FROM_HH((head)->hh.tbl,_hs_e) : NULL); \ } else { \ _hs_list = _hs_e; \ } \ if (_hs_e != NULL) { \ _hs_e->prev = ((_hs_tail != NULL) ? \ ELMT_FROM_HH((head)->hh.tbl,_hs_tail) : NULL); \ } \ _hs_tail = _hs_e; \ } \ _hs_p = _hs_q; \ } \ if (_hs_tail != NULL){ \ _hs_tail->next = NULL; \ } \ if ( _hs_nmerges <= 1U ) { \ _hs_looping=0; \ (head)->hh.tbl->tail = _hs_tail; \ DECLTYPE_ASSIGN(head,ELMT_FROM_HH((head)->hh.tbl, _hs_list)); \ } \ _hs_insize *= 2U; \ } \ HASH_FSCK(hh,head); \ } \ } while (0) /* This function selects items from one hash into another hash. * The end result is that the selected items have dual presence * in both hashes. There is no copy of the items made; rather * they are added into the new hash through a secondary hash * hash handle that must be present in the structure. */ #define HASH_SELECT(hh_dst, dst, hh_src, src, cond) \ do { \ unsigned _src_bkt, _dst_bkt; \ void *_last_elt=NULL, *_elt; \ UT_hash_handle *_src_hh, *_dst_hh, *_last_elt_hh=NULL; \ ptrdiff_t _dst_hho = ((char*)(&(dst)->hh_dst) - (char*)(dst)); \ if (src != NULL) { \ for(_src_bkt=0; _src_bkt < (src)->hh_src.tbl->num_buckets; _src_bkt++) { \ for(_src_hh = (src)->hh_src.tbl->buckets[_src_bkt].hh_head; \ _src_hh != NULL; \ _src_hh = _src_hh->hh_next) { \ _elt = ELMT_FROM_HH((src)->hh_src.tbl, _src_hh); \ if (cond(_elt)) { \ _dst_hh = (UT_hash_handle*)(((char*)_elt) + _dst_hho); \ _dst_hh->key = _src_hh->key; \ _dst_hh->keylen = _src_hh->keylen; \ _dst_hh->hashv = _src_hh->hashv; \ _dst_hh->prev = _last_elt; \ _dst_hh->next = NULL; \ if (_last_elt_hh != NULL) { _last_elt_hh->next = _elt; } \ if (dst == NULL) { \ DECLTYPE_ASSIGN(dst,_elt); \ HASH_MAKE_TABLE(hh_dst,dst); \ } else { \ _dst_hh->tbl = (dst)->hh_dst.tbl; \ } \ HASH_TO_BKT(_dst_hh->hashv, _dst_hh->tbl->num_buckets, _dst_bkt); \ HASH_ADD_TO_BKT(_dst_hh->tbl->buckets[_dst_bkt],_dst_hh); \ (dst)->hh_dst.tbl->num_items++; \ _last_elt = _elt; \ _last_elt_hh = _dst_hh; \ } \ } \ } \ } \ HASH_FSCK(hh_dst,dst); \ } while (0) #define HASH_CLEAR(hh,head) \ do { \ if (head != NULL) { \ uthash_free((head)->hh.tbl->buckets, \ (head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket)); \ HASH_BLOOM_FREE((head)->hh.tbl); \ uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ (head)=NULL; \ } \ } while (0) #define HASH_OVERHEAD(hh,head) \ ((head != NULL) ? ( \ (size_t)(((head)->hh.tbl->num_items * sizeof(UT_hash_handle)) + \ ((head)->hh.tbl->num_buckets * sizeof(UT_hash_bucket)) + \ sizeof(UT_hash_table) + \ (HASH_BLOOM_BYTELEN))) : 0U) #ifdef NO_DECLTYPE #define HASH_ITER(hh,head,el,tmp) \ for(((el)=(head)), ((*(char**)(&(tmp)))=(char*)((head!=NULL)?(head)->hh.next:NULL)); \ (el) != NULL; ((el)=(tmp)), ((*(char**)(&(tmp)))=(char*)((tmp!=NULL)?(tmp)->hh.next:NULL))) #else #define HASH_ITER(hh,head,el,tmp) \ for(((el)=(head)), ((tmp)=DECLTYPE(el)((head!=NULL)?(head)->hh.next:NULL)); \ (el) != NULL; ((el)=(tmp)), ((tmp)=DECLTYPE(el)((tmp!=NULL)?(tmp)->hh.next:NULL))) #endif /* obtain a count of items in the hash */ #define HASH_COUNT(head) HASH_CNT(hh,head) #define HASH_CNT(hh,head) ((head != NULL)?((head)->hh.tbl->num_items):0U) typedef struct UT_hash_bucket { struct UT_hash_handle *hh_head; unsigned count; /* expand_mult is normally set to 0. In this situation, the max chain length * threshold is enforced at its default value, HASH_BKT_CAPACITY_THRESH. (If * the bucket's chain exceeds this length, bucket expansion is triggered). * However, setting expand_mult to a non-zero value delays bucket expansion * (that would be triggered by additions to this particular bucket) * until its chain length reaches a *multiple* of HASH_BKT_CAPACITY_THRESH. * (The multiplier is simply expand_mult+1). The whole idea of this * multiplier is to reduce bucket expansions, since they are expensive, in * situations where we know that a particular bucket tends to be overused. * It is better to let its chain length grow to a longer yet-still-bounded * value, than to do an O(n) bucket expansion too often. */ unsigned expand_mult; } UT_hash_bucket; /* random signature used only to find hash tables in external analysis */ #define HASH_SIGNATURE 0xa0111fe1u #define HASH_BLOOM_SIGNATURE 0xb12220f2u typedef struct UT_hash_table { UT_hash_bucket *buckets; unsigned num_buckets, log2_num_buckets; unsigned num_items; struct UT_hash_handle *tail; /* tail hh in app order, for fast append */ ptrdiff_t hho; /* hash handle offset (byte pos of hash handle in element */ /* in an ideal situation (all buckets used equally), no bucket would have * more than ceil(#items/#buckets) items. that's the ideal chain length. */ unsigned ideal_chain_maxlen; /* nonideal_items is the number of items in the hash whose chain position * exceeds the ideal chain maxlen. these items pay the penalty for an uneven * hash distribution; reaching them in a chain traversal takes >ideal steps */ unsigned nonideal_items; /* ineffective expands occur when a bucket doubling was performed, but * afterward, more than half the items in the hash had nonideal chain * positions. If this happens on two consecutive expansions we inhibit any * further expansion, as it's not helping; this happens when the hash * function isn't a good fit for the key domain. When expansion is inhibited * the hash will still work, albeit no longer in constant time. */ unsigned ineff_expands, noexpand; uint32_t signature; /* used only to find hash tables in external analysis */ #ifdef HASH_BLOOM uint32_t bloom_sig; /* used only to test bloom exists in external analysis */ uint8_t *bloom_bv; uint8_t bloom_nbits; #endif } UT_hash_table; typedef struct UT_hash_handle { struct UT_hash_table *tbl; void *prev; /* prev element in app order */ void *next; /* next element in app order */ struct UT_hash_handle *hh_prev; /* previous hh in bucket order */ struct UT_hash_handle *hh_next; /* next hh in bucket order */ void *key; /* ptr to enclosing struct's key */ unsigned keylen; /* enclosing struct's key len */ unsigned hashv; /* result of hash-fcn(key) */ } UT_hash_handle; #endif /* UTHASH_H */ nsca-ng-1.6/python/000077500000000000000000000000001344421036200142265ustar00rootroot00000000000000nsca-ng-1.6/python/Makefile.am000066400000000000000000000030241344421036200162610ustar00rootroot00000000000000## Process this file with automake(1) to produce Makefile.in. ## Copyright (c) 2014 Holger Weiss ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1. Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## ## 2. Redistributions in binary form must reproduce the above copyright notice, ## this list of conditions and the following disclaimer in the documentation ## and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE ## LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ## CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF ## SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ## INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ## CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ## ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ## POSSIBILITY OF SUCH DAMAGE. EXTRA_DIST = PKG-INFO client.c client.h nscang.c setup.py uthash.h clean-local: -rm -rf build nsca-ng-1.6/python/PKG-INFO000066400000000000000000000003341344421036200153230ustar00rootroot00000000000000Metadata-Version: 1.0 Name: python-nscang Version: 1.0 Platform: POSIX, Windows Summary: Python NSCA-ng client. Home-page: https://www.nsca-ng.org/ Author: Alexander Golovko Author-email: alexandro@onsec.ru License: BSD nsca-ng-1.6/python/README000066400000000000000000000011561344421036200151110ustar00rootroot00000000000000This is the `README` file of *python-nscang*. Description ----------- The Python NSCA-ng client allows for sending host or service check results to NSCA-ng servers. Examples -------- from nscang import NSCAngNotifyer n = NSCAngNotifyer(host="monitoring.example.com", port=5668, identity="foo.example.com", psk="secret") n.svc_result(host_name="foo.example.com", svc_description="RAID status", return_code=0, plugin_output="OK: md126[raid1], md127[raid1]", timeout=5) nsca-ng-1.6/python/README.md000077700000000000000000000000001344421036200163602READMEustar00rootroot00000000000000nsca-ng-1.6/python/client.c000066400000000000000000000263761344421036200156660ustar00rootroot00000000000000/* * Copyright (c) 2014 Alexander Golovko * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include #include #include #include #include #include "client.h" #include "uthash.h" static nscang_client_t *nscang_client_instances; static pthread_rwlock_t nscang_client_instances_lock = PTHREAD_RWLOCK_INITIALIZER; unsigned int set_psk(SSL *ssl, const char *hint, char *identity, unsigned int max_identity_length, unsigned char *psk, unsigned int max_psk_length) { int rc; nscang_client_t *c = NULL; while (1) { rc = pthread_rwlock_rdlock(&nscang_client_instances_lock); if ((rc != EBUSY) && (rc != EAGAIN)) break; } if (rc == 0) { HASH_FIND_PTR(nscang_client_instances, &ssl, c); pthread_rwlock_unlock(&nscang_client_instances_lock); } if (c != NULL) { strncpy(identity, c->identity, max_identity_length); identity[max_identity_length - 1] = 0x00; strncpy((char *)psk, c->psk, max_psk_length); psk[max_psk_length - 1] = 0x00; return strlen((char *)psk); } identity[0] = 0x00; psk[0] = 0x00; return 0; } int nscang_client_init(nscang_client_t *c, char *host, int port, char *ciphers, char *identity, char *psk) { int rc; memset(c, 0x00, sizeof(nscang_client_t)); c->ssl_ctx = SSL_CTX_new(SSLv23_client_method()); if (c->ssl_ctx == NULL) { c->_errno = NSCANG_ERROR_SSL_CTX_CREATE; return 0; } if (ciphers != NULL) { if (SSL_CTX_set_cipher_list(c->ssl_ctx, ciphers) != 1) { c->_errno = NSCANG_ERROR_SSL_CIPHERS; return 0; } } SSL_CTX_set_options(c->ssl_ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3); c->bio = BIO_new(BIO_s_connect()); if (c->bio == NULL) { c->_errno = NSCANG_ERROR_SSL_BIO_CREATE; return 0; } BIO_set_conn_hostname(c->bio, host); BIO_set_conn_int_port(c->bio, &port); BIO_set_nbio(c->bio, 1); c->ssl = SSL_new(c->ssl_ctx); if (c->ssl == NULL) { nscang_client_free(c); c->_errno = NSCANG_ERROR_SSL_CREATE; return 0; } SSL_set_bio(c->ssl, c->bio, c->bio); SSL_set_connect_state(c->ssl); SSL_set_psk_client_callback(c->ssl, set_psk); c->identity = malloc(strlen(identity) + 1); c->psk = malloc(strlen(psk) + 1); if ((c->identity == NULL) || (c->psk == NULL)) { c->_errno = NSCANG_ERROR_MALLOC; return 0; } strcpy(c->identity, identity); strcpy(c->psk, psk); /* Busyloop until we get an rw lock. */ while (1) { rc = pthread_rwlock_wrlock(&nscang_client_instances_lock); if (rc != EBUSY) break; } if (rc != 0) { c->_errno = NSCANG_ERROR_LOCKING; return 0; } HASH_ADD_PTR(nscang_client_instances, ssl, c); pthread_rwlock_unlock(&nscang_client_instances_lock); c->state = NSCANG_STATE_NEW; return 1; } void nscang_client_free(nscang_client_t *c) { if (c->state != NSCANG_STATE_NONE) nscang_client_disconnect(c); if (c->ssl != NULL) { int rc; /* Busyloop until we get an rw lock. */ while (1) { rc = pthread_rwlock_wrlock (&nscang_client_instances_lock); if (rc != EBUSY) break; } if (rc == 0) { HASH_DEL(nscang_client_instances, c); pthread_rwlock_unlock(&nscang_client_instances_lock); } } if (c->ssl != NULL) { SSL_free(c->ssl); c->ssl = NULL; c->bio = NULL; } if (c->ssl_ctx != NULL) { SSL_CTX_free(c->ssl_ctx); c->ssl_ctx = NULL; } if (c->identity != NULL) { free(c->identity); c->identity = NULL; } if (c->psk != NULL) { free(c->psk); c->psk = NULL; } c->state = NSCANG_STATE_NONE; } int nscang_client_write(nscang_client_t *c, void *buf, int len, int timeout) { int rc; time_t endtime; fd_set fdset; struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 100000; endtime = time(NULL) + timeout; while (1) { if ((rc = SSL_write(c->ssl, buf, len)) > 0) return 1; if (!BIO_should_retry(c->bio)) { c->_errno = NSCANG_ERROR_SSL; return 0; } if (time(NULL) > endtime) { c->_errno = NSCANG_ERROR_TIMEOUT; return 0; } FD_ZERO(&fdset); FD_SET(BIO_get_fd(c->bio, NULL), &fdset); select(1, NULL, &fdset, NULL, &tv); } } int nscang_client_response(nscang_client_t *c, int timeout) { int rc; time_t endtime; fd_set fdset; char buf[1024]; int was_read = 0; char *ptr = buf; struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 100000; endtime = time(NULL) + timeout; while (1) { rc = SSL_read(c->ssl, ptr, 1024 - was_read); if (rc > 0) { was_read = was_read + rc; ptr = buf + was_read; if (buf[was_read - 1] == '\n') { if (buf[was_read - 2] == '\r') buf[was_read - 2] = 0x00; else buf[was_read - 1] = 0x00; break; } if (was_read == 1024) { c->_errno = NSCANG_ERROR_TOO_LONG_RESPONSE; return 0; } } else if (!BIO_should_retry(c->bio)) { c->_errno = NSCANG_ERROR_SSL; return 0; } if (time(NULL) > endtime) { c->_errno = NSCANG_ERROR_TIMEOUT; return 0; } FD_ZERO(&fdset); FD_SET(BIO_get_fd(c->bio, NULL), &fdset); select(1, &fdset, NULL, NULL, &tv); } if (strncmp(buf, "MOIN", 4) == 0) { if (strcmp(buf, "MOIN 1") == 0) { return NSCANG_RESP_MOIN; } else { c->_errno = NSCANG_ERROR_BAD_PROTO_VERSION; strncpy(c->errstr, buf + 5, sizeof(c->errstr) - 1); c->errstr[sizeof(c->errstr) - 1] = 0x00; return 0; } } else if (strncmp(buf, "OKAY", 4) == 0) { return NSCANG_RESP_OKAY; } else if (strncmp(buf, "FAIL", 4) == 0) { c->_errno = NSCANG_ERROR_FAIL; strncpy(c->errstr, buf + 5, sizeof(c->errstr) - 1); c->errstr[sizeof(c->errstr) - 1] = 0x00; return 0; } else if (strncmp(buf, "BAIL", 4) == 0) { nscang_client_disconnect(c); c->_errno = NSCANG_ERROR_BAIL; strncpy(c->errstr, buf + 5, sizeof(c->errstr) - 1); c->errstr[sizeof(c->errstr) - 1] = 0x00; return 0; } else { char *msg = "BAIL Unknown response!"; nscang_client_write(c, msg, sizeof(msg), 0); nscang_client_disconnect(c); c->_errno = NSCANG_ERROR_UNKNOWN_RESPONSE; strncpy(c->errstr, buf, sizeof(c->errstr) - 1); c->errstr[sizeof(c->errstr) - 1] = 0x00; return 0; } } void nscang_client_disconnect(nscang_client_t *c) { fd_set fdset; struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 100000; if (c->state == NSCANG_STATE_MOIN) nscang_client_send_quit(c); if ((SSL_shutdown(c->ssl) == -1) && BIO_should_retry(c->bio)) { FD_ZERO(&fdset); FD_SET(BIO_get_fd(c->bio, NULL), &fdset); select(1, NULL, &fdset, NULL, &tv); SSL_shutdown(c->ssl); } SSL_clear(c->ssl); BIO_reset(c->bio); c->state = NSCANG_STATE_NEW; } int nscang_client_send_moin(nscang_client_t *c, int timeout) { char cmd[64]; int len, rc; if (c->state == NSCANG_STATE_MOIN) return 1; if (c->state != NSCANG_STATE_NEW) { c->_errno = NSCANG_ERROR_BAD_STATE; return 0; } srandom(time(NULL)); len = snprintf(cmd, sizeof(cmd), "MOIN 1 %08ld%08ld\r\n", random(), random()); if (!nscang_client_write(c, cmd, len, timeout)) return 0; rc = nscang_client_response(c, timeout); if (!rc) return 0; if (rc != NSCANG_RESP_MOIN) { c->_errno = NSCANG_ERROR_PROTOCOL_MISMATCH; return 0; } c->state = NSCANG_STATE_MOIN; return 1; } int nscang_client_send_push(nscang_client_t *c, char *host, char *service, int status, char *message, int timeout) { char cmd[64], command[1024]; int len, rc; if (!nscang_client_send_moin(c, timeout)) return 0; if (service == NULL) len = snprintf(command, sizeof(command) - 1, "[%u] PROCESS_HOST_CHECK_RESULT;%s;%d;%s", (unsigned int)time(NULL), host, status, message); else len = snprintf(command, sizeof(command) - 1, "[%u] PROCESS_SERVICE_CHECK_RESULT;%s;%s;%d;%s", (unsigned int)time(NULL), host, service, status, message); command[len++] = '\n'; snprintf(cmd, sizeof(cmd), "PUSH %d\n", len); if (!nscang_client_write(c, cmd, strlen(cmd), timeout)) return 0; rc = nscang_client_response(c, timeout); if (!rc) return 0; if (rc != NSCANG_RESP_OKAY) { c->_errno = NSCANG_ERROR_PROTOCOL_MISMATCH; return 0; } if (!nscang_client_write(c, command, len, timeout)) return 0; rc = nscang_client_response(c, timeout); if (!rc) return 0; if (rc != NSCANG_RESP_OKAY) { c->_errno = NSCANG_ERROR_PROTOCOL_MISMATCH; return 0; } return 1; } int nscang_client_send_quit(nscang_client_t *c) { if (c->state != NSCANG_STATE_MOIN) { c->_errno = NSCANG_ERROR_BAD_STATE; return 0; } if (!nscang_client_write(c, "QUIT\n", 5, 0)) return 0; return 1; } char * nscang_client_errstr(nscang_client_t *c, char *buf, int buf_size) { switch (c->_errno) { case NSCANG_ERROR_SSL_CTX_CREATE: strncpy(buf, "Can't create SSL context", buf_size); break; case NSCANG_ERROR_SSL_CIPHERS: strncpy(buf, "Bad ciphers list", buf_size); break; case NSCANG_ERROR_SSL_BIO_CREATE: strncpy(buf, "Can't create BIO socket", buf_size); break; case NSCANG_ERROR_SSL_CREATE: strncpy(buf, "Can't create SSL", buf_size); break; case NSCANG_ERROR_SSL: snprintf(buf, buf_size, "SSL error - %s - %s", ERR_reason_error_string(ERR_peek_last_error()), ERR_reason_error_string(ERR_peek_error())); break; case NSCANG_ERROR_MALLOC: strncpy(buf, "Can't allocate memory", buf_size); break; case NSCANG_ERROR_TIMEOUT: strncpy(buf, "Timeout was reached", buf_size); break; case NSCANG_ERROR_TOO_LONG_RESPONSE: strncpy(buf, "Protocol mismatch - too long response", buf_size); break; case NSCANG_ERROR_BAD_PROTO_VERSION: snprintf(buf, buf_size, "Protocol mismatch - bad version '%s'", c->errstr); break; case NSCANG_ERROR_PROTOCOL_MISMATCH: strncpy(buf, "Protocol mismatch - unexpected server response", buf_size); break; case NSCANG_ERROR_UNKNOWN_RESPONSE: strncpy(buf, "Protocol mismatch - unknown server response", buf_size); break; case NSCANG_ERROR_BAIL: snprintf(buf, buf_size, "BAIL: %s", c->errstr); break; case NSCANG_ERROR_FAIL: snprintf(buf, buf_size, "FAIL: %s", c->errstr); break; case NSCANG_ERROR_BAD_STATE: snprintf(buf, buf_size, "Operation not permitted in state %d", c->state); break; case NSCANG_ERROR_LOCKING: strncpy(buf, "Can't obtain lock for instances list", buf_size); break; default: buf[0] = 0x00; } buf[buf_size - 1] = 0x00; return buf; } nsca-ng-1.6/python/client.h000066400000000000000000000060001344421036200156510ustar00rootroot00000000000000/* * Copyright (c) 2014 Alexander Golovko * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef __NSCANG_CLIENT_H #define __NSCANG_CLIENT_H #include #include #include "uthash.h" typedef struct { SSL_CTX *ssl_ctx; BIO *bio; SSL *ssl; int state; char *identity; char *psk; int _errno; char errstr[1024]; UT_hash_handle hh; } nscang_client_t; #define NSCANG_STATE_NONE 0 #define NSCANG_STATE_NEW 1 #define NSCANG_STATE_MOIN 2 #define NSCANG_RESP_MOIN 1 #define NSCANG_RESP_OKAY 2 #define NSCANG_ERROR_MALLOC 1 #define NSCANG_ERROR_TIMEOUT 2 #define NSCANG_ERROR_TOO_LONG_RESPONSE 3 #define NSCANG_ERROR_BAD_PROTO_VERSION 4 #define NSCANG_ERROR_PROTOCOL_MISMATCH 5 #define NSCANG_ERROR_UNKNOWN_RESPONSE 6 #define NSCANG_ERROR_BAIL 7 #define NSCANG_ERROR_FAIL 8 #define NSCANG_ERROR_BAD_STATE 9 #define NSCANG_ERROR_LOCKING 10 #define NSCANG_ERROR_SSL_CTX_CREATE 101 #define NSCANG_ERROR_SSL_CIPHERS 102 #define NSCANG_ERROR_SSL_BIO_CREATE 103 #define NSCANG_ERROR_SSL_CREATE 104 #define NSCANG_ERROR_SSL 105 int nscang_client_init(nscang_client_t *c, char *host, int port, char *ciphers, char *identity, char *psk); void nscang_client_free(nscang_client_t *c); void nscang_client_disconnect(nscang_client_t *c); int nscang_client_send_moin(nscang_client_t *c, int timeout); int nscang_client_send_push(nscang_client_t *c, char *host, char *service, int status, char *message, int timeout); int nscang_client_send_quit(nscang_client_t *c); char *nscang_client_errstr(nscang_client_t *c, char *buf, int buf_size); #endif /* __NSCANG_CLIENT_H */ nsca-ng-1.6/python/nscang.c000066400000000000000000000171021344421036200156440ustar00rootroot00000000000000/* * Copyright (c) 2014 Alexander Golovko * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include #include "structmember.h" #include #include "client.h" typedef struct { PyObject_HEAD char *host; unsigned int port; char *identity; char *psk; char *ciphers; nscang_client_t *client; /* Type-specific fields go here. */ } NSCAngNotifyer; static PyObject * nscang_host_result(PyObject *self, PyObject *args, PyObject *kwds) { char errstr[1024]; static char *kwlist[] = { "host_name", "return_code", "plugin_output", "timeout", NULL }; char *host = NULL; char *output = ""; int rc = 0; int timeout = 5; nscang_client_t *client = ((NSCAngNotifyer *)self)->client; if (!PyArg_ParseTupleAndKeywords(args, kwds, "sI|sI:host_result", kwlist, &host, &rc, &output, &timeout)) return NULL; if (nscang_client_send_push(client, host, NULL, rc, output, timeout)) { Py_INCREF(Py_None); return Py_None; } nscang_client_disconnect(client); if (nscang_client_send_push(client, host, NULL, rc, output, timeout)) { Py_INCREF(Py_None); return Py_None; } PyErr_Format(PyExc_RuntimeError, "host_result: %s", nscang_client_errstr(client, errstr, sizeof(errstr))); return NULL; } static PyObject * nscang_svc_result(PyObject *self, PyObject *args, PyObject *kwds) { char errstr[1024]; static char *kwlist[] = { "host_name", "svc_description", "return_code", "plugin_output", "timeout", NULL }; char *host = NULL; char *service = NULL; char *output = ""; int rc = 0; int timeout = 5; nscang_client_t *client = ((NSCAngNotifyer *)self)->client; if (!PyArg_ParseTupleAndKeywords(args, kwds, "ssI|sI:svc_result", kwlist, &host, &service, &rc, &output, &timeout)) return NULL; if (nscang_client_send_push(client, host, service, rc, output, timeout)) { Py_INCREF(Py_None); return Py_None; } nscang_client_disconnect(client); if (nscang_client_send_push(client, host, service, rc, output, timeout)) { Py_INCREF(Py_None); return Py_None; } PyErr_Format(PyExc_RuntimeError, "svc_result: %s", nscang_client_errstr(client, errstr, sizeof(errstr))); return NULL; } static int NSCAngNotifyer_init(NSCAngNotifyer *self, PyObject *args, PyObject *kwds) { char errstr[1024]; static char *kwlist[] = { "host", "port", "identity", "psk", "ciphers", NULL }; self->host = NULL; self->port = 5668; self->identity = NULL; self->psk = NULL; self->ciphers = NULL; if (!PyArg_ParseTupleAndKeywords(args, kwds, "sIss|s:__init__", kwlist, &self->host, &self->port, &self->identity, &self->psk, &self->ciphers)) return -1; self->client = malloc(sizeof(nscang_client_t)); if (self->client == NULL) { PyErr_Format(PyExc_MemoryError, "Can't allocate memory for NSCAng connection state"); return -1; } if (!nscang_client_init(self->client, self->host, self->port, self->ciphers, self->identity, self->psk)) { PyErr_Format(PyExc_RuntimeError, "nscang_client_init: %s", nscang_client_errstr(self->client, errstr, sizeof(errstr))); return -1; } return 0; } static void NSCAngNotifyer_dealloc(NSCAngNotifyer *self) { nscang_client_free(self->client); } static PyMemberDef NSCAngNotifyer_members[] = { { "host", T_STRING, offsetof(NSCAngNotifyer, host), READONLY }, { "port", T_INT, offsetof(NSCAngNotifyer, port), READONLY }, { NULL } }; static PyMethodDef NSCAngNotifyer_methods[] = { { "host_result", (PyCFunction) nscang_host_result, METH_VARARGS | METH_KEYWORDS, "Send a passive host check to the configured monitoring host" }, { "svc_result", (PyCFunction) nscang_svc_result, METH_VARARGS | METH_KEYWORDS, "Send a service result to the configured monitoring host" }, { NULL } }; static PyTypeObject NSCAngNotifyerType = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ "nscang.NSCAngNotifyer", /* tp_name */ sizeof(NSCAngNotifyer), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor) NSCAngNotifyer_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "NSCAngNotifyer objects", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ NSCAngNotifyer_methods, /* tp_methods */ NSCAngNotifyer_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc) NSCAngNotifyer_init, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ PyType_GenericNew, /* tp_new */ _PyObject_Del /* tp_free */ }; static PyMethodDef module_methods[] = { { NULL } }; DL_EXPORT(void) initnscang(void) { PyObject *m; SSL_library_init(); SSL_load_error_strings(); if (PyType_Ready(&NSCAngNotifyerType) < 0) return; m = Py_InitModule("nscang", module_methods); if (m == NULL) return; Py_INCREF(&NSCAngNotifyerType); PyModule_AddObject(m, "NSCAngNotifyer", (PyObject *)&NSCAngNotifyerType); } nsca-ng-1.6/python/setup.py000066400000000000000000000011321344421036200157350ustar00rootroot00000000000000#!/usr/bin/python from distutils.core import setup, Extension VERSION = "1.1" setup(name = "python-nscang", version = VERSION, description = "Python NSCA-ng client", author = "Alexander Golovko", author_email = "alexandro@onsec.ru", license = "BSD", long_description = \ """ Python NSCA-ng client. """, ext_modules = [Extension("nscang", ["nscang.c", "client.c"], libraries = ["pthread", "ssl", "crypto"], define_macros = [("VERSION", '"%s"' % VERSION)])], ) nsca-ng-1.6/python/uthash.h000066400000000000000000002075541344421036200157100ustar00rootroot00000000000000/* Copyright (c) 2003-2016, Troy D. Hanson http://troydhanson.github.com/uthash/ All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef UTHASH_H #define UTHASH_H #define UTHASH_VERSION 2.0.1 #include /* memcmp,strlen */ #include /* ptrdiff_t */ #include /* exit() */ /* These macros use decltype or the earlier __typeof GNU extension. As decltype is only available in newer compilers (VS2010 or gcc 4.3+ when compiling c++ source) this code uses whatever method is needed or, for VS2008 where neither is available, uses casting workarounds. */ #if defined(_MSC_VER) /* MS compiler */ #if _MSC_VER >= 1600 && defined(__cplusplus) /* VS2010 or newer in C++ mode */ #define DECLTYPE(x) (decltype(x)) #else /* VS2008 or older (or VS2010 in C mode) */ #define NO_DECLTYPE #define DECLTYPE(x) #endif #elif defined(__BORLANDC__) || defined(__LCC__) || defined(__WATCOMC__) #define NO_DECLTYPE #define DECLTYPE(x) #else /* GNU, Sun and other compilers */ #define DECLTYPE(x) (__typeof(x)) #endif #ifdef NO_DECLTYPE #define DECLTYPE_ASSIGN(dst,src) \ do { \ char **_da_dst = (char**)(&(dst)); \ *_da_dst = (char*)(src); \ } while (0) #else #define DECLTYPE_ASSIGN(dst,src) \ do { \ (dst) = DECLTYPE(dst)(src); \ } while (0) #endif /* a number of the hash function use uint32_t which isn't defined on Pre VS2010 */ #if defined(_WIN32) #if defined(_MSC_VER) && _MSC_VER >= 1600 #include #elif defined(__WATCOMC__) || defined(__MINGW32__) || defined(__CYGWIN__) #include #else typedef unsigned int uint32_t; typedef unsigned char uint8_t; #endif #elif defined(__GNUC__) && !defined(__VXWORKS__) #include #else typedef unsigned int uint32_t; typedef unsigned char uint8_t; #endif #ifndef uthash_fatal #define uthash_fatal(msg) exit(-1) /* fatal error (out of memory,etc) */ #endif #ifndef uthash_malloc #define uthash_malloc(sz) malloc(sz) /* malloc fcn */ #endif #ifndef uthash_free #define uthash_free(ptr,sz) free(ptr) /* free fcn */ #endif #ifndef uthash_strlen #define uthash_strlen(s) strlen(s) #endif #ifndef uthash_memcmp #define uthash_memcmp(a,b,n) memcmp(a,b,n) #endif #ifndef uthash_noexpand_fyi #define uthash_noexpand_fyi(tbl) /* can be defined to log noexpand */ #endif #ifndef uthash_expand_fyi #define uthash_expand_fyi(tbl) /* can be defined to log expands */ #endif /* initial number of buckets */ #define HASH_INITIAL_NUM_BUCKETS 32U /* initial number of buckets */ #define HASH_INITIAL_NUM_BUCKETS_LOG2 5U /* lg2 of initial number of buckets */ #define HASH_BKT_CAPACITY_THRESH 10U /* expand when bucket count reaches */ /* calculate the element whose hash handle address is hhp */ #define ELMT_FROM_HH(tbl,hhp) ((void*)(((char*)(hhp)) - ((tbl)->hho))) /* calculate the hash handle from element address elp */ #define HH_FROM_ELMT(tbl,elp) ((UT_hash_handle *)(((char*)(elp)) + ((tbl)->hho))) #define HASH_VALUE(keyptr,keylen,hashv) \ do { \ HASH_FCN(keyptr, keylen, hashv); \ } while (0) #define HASH_FIND_BYHASHVALUE(hh,head,keyptr,keylen,hashval,out) \ do { \ (out) = NULL; \ if (head) { \ unsigned _hf_bkt; \ HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _hf_bkt); \ if (HASH_BLOOM_TEST((head)->hh.tbl, hashval) != 0) { \ HASH_FIND_IN_BKT((head)->hh.tbl, hh, (head)->hh.tbl->buckets[ _hf_bkt ], keyptr, keylen, hashval, out); \ } \ } \ } while (0) #define HASH_FIND(hh,head,keyptr,keylen,out) \ do { \ unsigned _hf_hashv; \ HASH_VALUE(keyptr, keylen, _hf_hashv); \ HASH_FIND_BYHASHVALUE(hh, head, keyptr, keylen, _hf_hashv, out); \ } while (0) #ifdef HASH_BLOOM #define HASH_BLOOM_BITLEN (1UL << HASH_BLOOM) #define HASH_BLOOM_BYTELEN (HASH_BLOOM_BITLEN/8UL) + (((HASH_BLOOM_BITLEN%8UL)!=0UL) ? 1UL : 0UL) #define HASH_BLOOM_MAKE(tbl) \ do { \ (tbl)->bloom_nbits = HASH_BLOOM; \ (tbl)->bloom_bv = (uint8_t*)uthash_malloc(HASH_BLOOM_BYTELEN); \ if (!((tbl)->bloom_bv)) { uthash_fatal( "out of memory"); } \ memset((tbl)->bloom_bv, 0, HASH_BLOOM_BYTELEN); \ (tbl)->bloom_sig = HASH_BLOOM_SIGNATURE; \ } while (0) #define HASH_BLOOM_FREE(tbl) \ do { \ uthash_free((tbl)->bloom_bv, HASH_BLOOM_BYTELEN); \ } while (0) #define HASH_BLOOM_BITSET(bv,idx) (bv[(idx)/8U] |= (1U << ((idx)%8U))) #define HASH_BLOOM_BITTEST(bv,idx) (bv[(idx)/8U] & (1U << ((idx)%8U))) #define HASH_BLOOM_ADD(tbl,hashv) \ HASH_BLOOM_BITSET((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1U))) #define HASH_BLOOM_TEST(tbl,hashv) \ HASH_BLOOM_BITTEST((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1U))) #else #define HASH_BLOOM_MAKE(tbl) #define HASH_BLOOM_FREE(tbl) #define HASH_BLOOM_ADD(tbl,hashv) #define HASH_BLOOM_TEST(tbl,hashv) (1) #define HASH_BLOOM_BYTELEN 0U #endif #define HASH_MAKE_TABLE(hh,head) \ do { \ (head)->hh.tbl = (UT_hash_table*)uthash_malloc( \ sizeof(UT_hash_table)); \ if (!((head)->hh.tbl)) { uthash_fatal( "out of memory"); } \ memset((head)->hh.tbl, 0, sizeof(UT_hash_table)); \ (head)->hh.tbl->tail = &((head)->hh); \ (head)->hh.tbl->num_buckets = HASH_INITIAL_NUM_BUCKETS; \ (head)->hh.tbl->log2_num_buckets = HASH_INITIAL_NUM_BUCKETS_LOG2; \ (head)->hh.tbl->hho = (char*)(&(head)->hh) - (char*)(head); \ (head)->hh.tbl->buckets = (UT_hash_bucket*)uthash_malloc( \ HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket)); \ if (! (head)->hh.tbl->buckets) { uthash_fatal( "out of memory"); } \ memset((head)->hh.tbl->buckets, 0, \ HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket)); \ HASH_BLOOM_MAKE((head)->hh.tbl); \ (head)->hh.tbl->signature = HASH_SIGNATURE; \ } while (0) #define HASH_REPLACE_BYHASHVALUE_INORDER(hh,head,fieldname,keylen_in,hashval,add,replaced,cmpfcn) \ do { \ (replaced) = NULL; \ HASH_FIND_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, replaced); \ if (replaced) { \ HASH_DELETE(hh, head, replaced); \ } \ HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, &((add)->fieldname), keylen_in, hashval, add, cmpfcn); \ } while (0) #define HASH_REPLACE_BYHASHVALUE(hh,head,fieldname,keylen_in,hashval,add,replaced) \ do { \ (replaced) = NULL; \ HASH_FIND_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, replaced); \ if (replaced) { \ HASH_DELETE(hh, head, replaced); \ } \ HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, add); \ } while (0) #define HASH_REPLACE(hh,head,fieldname,keylen_in,add,replaced) \ do { \ unsigned _hr_hashv; \ HASH_VALUE(&((add)->fieldname), keylen_in, _hr_hashv); \ HASH_REPLACE_BYHASHVALUE(hh, head, fieldname, keylen_in, _hr_hashv, add, replaced); \ } while (0) #define HASH_REPLACE_INORDER(hh,head,fieldname,keylen_in,add,replaced,cmpfcn) \ do { \ unsigned _hr_hashv; \ HASH_VALUE(&((add)->fieldname), keylen_in, _hr_hashv); \ HASH_REPLACE_BYHASHVALUE_INORDER(hh, head, fieldname, keylen_in, _hr_hashv, add, replaced, cmpfcn); \ } while (0) #define HASH_APPEND_LIST(hh, head, add) \ do { \ (add)->hh.next = NULL; \ (add)->hh.prev = ELMT_FROM_HH((head)->hh.tbl, (head)->hh.tbl->tail); \ (head)->hh.tbl->tail->next = (add); \ (head)->hh.tbl->tail = &((add)->hh); \ } while (0) #define HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh,head,keyptr,keylen_in,hashval,add,cmpfcn) \ do { \ unsigned _ha_bkt; \ (add)->hh.hashv = (hashval); \ (add)->hh.key = (char*) (keyptr); \ (add)->hh.keylen = (unsigned) (keylen_in); \ if (!(head)) { \ (add)->hh.next = NULL; \ (add)->hh.prev = NULL; \ (head) = (add); \ HASH_MAKE_TABLE(hh, head); \ } else { \ struct UT_hash_handle *_hs_iter = &(head)->hh; \ (add)->hh.tbl = (head)->hh.tbl; \ do { \ if (cmpfcn(DECLTYPE(head) ELMT_FROM_HH((head)->hh.tbl, _hs_iter), add) > 0) \ break; \ } while ((_hs_iter = _hs_iter->next)); \ if (_hs_iter) { \ (add)->hh.next = _hs_iter; \ if (((add)->hh.prev = _hs_iter->prev)) { \ HH_FROM_ELMT((head)->hh.tbl, _hs_iter->prev)->next = (add); \ } else { \ (head) = (add); \ } \ _hs_iter->prev = (add); \ } else { \ HASH_APPEND_LIST(hh, head, add); \ } \ } \ (head)->hh.tbl->num_items++; \ HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _ha_bkt); \ HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt], &(add)->hh); \ HASH_BLOOM_ADD((head)->hh.tbl, hashval); \ HASH_EMIT_KEY(hh, head, keyptr, keylen_in); \ HASH_FSCK(hh, head); \ } while (0) #define HASH_ADD_KEYPTR_INORDER(hh,head,keyptr,keylen_in,add,cmpfcn) \ do { \ unsigned _hs_hashv; \ HASH_VALUE(keyptr, keylen_in, _hs_hashv); \ HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, keyptr, keylen_in, _hs_hashv, add, cmpfcn); \ } while (0) #define HASH_ADD_BYHASHVALUE_INORDER(hh,head,fieldname,keylen_in,hashval,add,cmpfcn) \ HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh, head, &((add)->fieldname), keylen_in, hashval, add, cmpfcn) #define HASH_ADD_INORDER(hh,head,fieldname,keylen_in,add,cmpfcn) \ HASH_ADD_KEYPTR_INORDER(hh, head, &((add)->fieldname), keylen_in, add, cmpfcn) #define HASH_ADD_KEYPTR_BYHASHVALUE(hh,head,keyptr,keylen_in,hashval,add) \ do { \ unsigned _ha_bkt; \ (add)->hh.hashv = (hashval); \ (add)->hh.key = (char*) (keyptr); \ (add)->hh.keylen = (unsigned) (keylen_in); \ if (!(head)) { \ (add)->hh.next = NULL; \ (add)->hh.prev = NULL; \ (head) = (add); \ HASH_MAKE_TABLE(hh, head); \ } else { \ (add)->hh.tbl = (head)->hh.tbl; \ HASH_APPEND_LIST(hh, head, add); \ } \ (head)->hh.tbl->num_items++; \ HASH_TO_BKT(hashval, (head)->hh.tbl->num_buckets, _ha_bkt); \ HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt], &(add)->hh); \ HASH_BLOOM_ADD((head)->hh.tbl, hashval); \ HASH_EMIT_KEY(hh, head, keyptr, keylen_in); \ HASH_FSCK(hh, head); \ } while (0) #define HASH_ADD_KEYPTR(hh,head,keyptr,keylen_in,add) \ do { \ unsigned _ha_hashv; \ HASH_VALUE(keyptr, keylen_in, _ha_hashv); \ HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, keyptr, keylen_in, _ha_hashv, add); \ } while (0) #define HASH_ADD_BYHASHVALUE(hh,head,fieldname,keylen_in,hashval,add) \ HASH_ADD_KEYPTR_BYHASHVALUE(hh, head, &((add)->fieldname), keylen_in, hashval, add) #define HASH_ADD(hh,head,fieldname,keylen_in,add) \ HASH_ADD_KEYPTR(hh, head, &((add)->fieldname), keylen_in, add) #define HASH_TO_BKT(hashv,num_bkts,bkt) \ do { \ bkt = ((hashv) & ((num_bkts) - 1U)); \ } while (0) /* delete "delptr" from the hash table. * "the usual" patch-up process for the app-order doubly-linked-list. * The use of _hd_hh_del below deserves special explanation. * These used to be expressed using (delptr) but that led to a bug * if someone used the same symbol for the head and deletee, like * HASH_DELETE(hh,users,users); * We want that to work, but by changing the head (users) below * we were forfeiting our ability to further refer to the deletee (users) * in the patch-up process. Solution: use scratch space to * copy the deletee pointer, then the latter references are via that * scratch pointer rather than through the repointed (users) symbol. */ #define HASH_DELETE(hh,head,delptr) \ do { \ struct UT_hash_handle *_hd_hh_del; \ if ( ((delptr)->hh.prev == NULL) && ((delptr)->hh.next == NULL) ) { \ uthash_free((head)->hh.tbl->buckets, \ (head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket) ); \ HASH_BLOOM_FREE((head)->hh.tbl); \ uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ head = NULL; \ } else { \ unsigned _hd_bkt; \ _hd_hh_del = &((delptr)->hh); \ if ((delptr) == ELMT_FROM_HH((head)->hh.tbl,(head)->hh.tbl->tail)) { \ (head)->hh.tbl->tail = \ (UT_hash_handle*)((ptrdiff_t)((delptr)->hh.prev) + \ (head)->hh.tbl->hho); \ } \ if ((delptr)->hh.prev != NULL) { \ ((UT_hash_handle*)((ptrdiff_t)((delptr)->hh.prev) + \ (head)->hh.tbl->hho))->next = (delptr)->hh.next; \ } else { \ DECLTYPE_ASSIGN(head,(delptr)->hh.next); \ } \ if (_hd_hh_del->next != NULL) { \ ((UT_hash_handle*)((ptrdiff_t)_hd_hh_del->next + \ (head)->hh.tbl->hho))->prev = \ _hd_hh_del->prev; \ } \ HASH_TO_BKT( _hd_hh_del->hashv, (head)->hh.tbl->num_buckets, _hd_bkt); \ HASH_DEL_IN_BKT(hh,(head)->hh.tbl->buckets[_hd_bkt], _hd_hh_del); \ (head)->hh.tbl->num_items--; \ } \ HASH_FSCK(hh,head); \ } while (0) /* convenience forms of HASH_FIND/HASH_ADD/HASH_DEL */ #define HASH_FIND_STR(head,findstr,out) \ HASH_FIND(hh,head,findstr,(unsigned)uthash_strlen(findstr),out) #define HASH_ADD_STR(head,strfield,add) \ HASH_ADD(hh,head,strfield[0],(unsigned)uthash_strlen(add->strfield),add) #define HASH_REPLACE_STR(head,strfield,add,replaced) \ HASH_REPLACE(hh,head,strfield[0],(unsigned)uthash_strlen(add->strfield),add,replaced) #define HASH_FIND_INT(head,findint,out) \ HASH_FIND(hh,head,findint,sizeof(int),out) #define HASH_ADD_INT(head,intfield,add) \ HASH_ADD(hh,head,intfield,sizeof(int),add) #define HASH_REPLACE_INT(head,intfield,add,replaced) \ HASH_REPLACE(hh,head,intfield,sizeof(int),add,replaced) #define HASH_FIND_PTR(head,findptr,out) \ HASH_FIND(hh,head,findptr,sizeof(void *),out) #define HASH_ADD_PTR(head,ptrfield,add) \ HASH_ADD(hh,head,ptrfield,sizeof(void *),add) #define HASH_REPLACE_PTR(head,ptrfield,add,replaced) \ HASH_REPLACE(hh,head,ptrfield,sizeof(void *),add,replaced) #define HASH_DEL(head,delptr) \ HASH_DELETE(hh,head,delptr) /* HASH_FSCK checks hash integrity on every add/delete when HASH_DEBUG is defined. * This is for uthash developer only; it compiles away if HASH_DEBUG isn't defined. */ #ifdef HASH_DEBUG #define HASH_OOPS(...) do { fprintf(stderr,__VA_ARGS__); exit(-1); } while (0) #define HASH_FSCK(hh,head) \ do { \ struct UT_hash_handle *_thh; \ if (head) { \ unsigned _bkt_i; \ unsigned _count; \ char *_prev; \ _count = 0; \ for( _bkt_i = 0; _bkt_i < (head)->hh.tbl->num_buckets; _bkt_i++) { \ unsigned _bkt_count = 0; \ _thh = (head)->hh.tbl->buckets[_bkt_i].hh_head; \ _prev = NULL; \ while (_thh) { \ if (_prev != (char*)(_thh->hh_prev)) { \ HASH_OOPS("invalid hh_prev %p, actual %p\n", \ _thh->hh_prev, _prev ); \ } \ _bkt_count++; \ _prev = (char*)(_thh); \ _thh = _thh->hh_next; \ } \ _count += _bkt_count; \ if ((head)->hh.tbl->buckets[_bkt_i].count != _bkt_count) { \ HASH_OOPS("invalid bucket count %u, actual %u\n", \ (head)->hh.tbl->buckets[_bkt_i].count, _bkt_count); \ } \ } \ if (_count != (head)->hh.tbl->num_items) { \ HASH_OOPS("invalid hh item count %u, actual %u\n", \ (head)->hh.tbl->num_items, _count ); \ } \ /* traverse hh in app order; check next/prev integrity, count */ \ _count = 0; \ _prev = NULL; \ _thh = &(head)->hh; \ while (_thh) { \ _count++; \ if (_prev !=(char*)(_thh->prev)) { \ HASH_OOPS("invalid prev %p, actual %p\n", \ _thh->prev, _prev ); \ } \ _prev = (char*)ELMT_FROM_HH((head)->hh.tbl, _thh); \ _thh = ( _thh->next ? (UT_hash_handle*)((char*)(_thh->next) + \ (head)->hh.tbl->hho) : NULL ); \ } \ if (_count != (head)->hh.tbl->num_items) { \ HASH_OOPS("invalid app item count %u, actual %u\n", \ (head)->hh.tbl->num_items, _count ); \ } \ } \ } while (0) #else #define HASH_FSCK(hh,head) #endif /* When compiled with -DHASH_EMIT_KEYS, length-prefixed keys are emitted to * the descriptor to which this macro is defined for tuning the hash function. * The app can #include to get the prototype for write(2). */ #ifdef HASH_EMIT_KEYS #define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) \ do { \ unsigned _klen = fieldlen; \ write(HASH_EMIT_KEYS, &_klen, sizeof(_klen)); \ write(HASH_EMIT_KEYS, keyptr, (unsigned long)fieldlen); \ } while (0) #else #define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) #endif /* default to Jenkin's hash unless overridden e.g. DHASH_FUNCTION=HASH_SAX */ #ifdef HASH_FUNCTION #define HASH_FCN HASH_FUNCTION #else #define HASH_FCN HASH_JEN #endif /* The Bernstein hash function, used in Perl prior to v5.6. Note (x<<5+x)=x*33. */ #define HASH_BER(key,keylen,hashv) \ do { \ unsigned _hb_keylen=(unsigned)keylen; \ const unsigned char *_hb_key=(const unsigned char*)(key); \ (hashv) = 0; \ while (_hb_keylen-- != 0U) { \ (hashv) = (((hashv) << 5) + (hashv)) + *_hb_key++; \ } \ } while (0) /* SAX/FNV/OAT/JEN hash functions are macro variants of those listed at * http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx */ #define HASH_SAX(key,keylen,hashv) \ do { \ unsigned _sx_i; \ const unsigned char *_hs_key=(const unsigned char*)(key); \ hashv = 0; \ for(_sx_i=0; _sx_i < keylen; _sx_i++) { \ hashv ^= (hashv << 5) + (hashv >> 2) + _hs_key[_sx_i]; \ } \ } while (0) /* FNV-1a variation */ #define HASH_FNV(key,keylen,hashv) \ do { \ unsigned _fn_i; \ const unsigned char *_hf_key=(const unsigned char*)(key); \ hashv = 2166136261U; \ for(_fn_i=0; _fn_i < keylen; _fn_i++) { \ hashv = hashv ^ _hf_key[_fn_i]; \ hashv = hashv * 16777619U; \ } \ } while (0) #define HASH_OAT(key,keylen,hashv) \ do { \ unsigned _ho_i; \ const unsigned char *_ho_key=(const unsigned char*)(key); \ hashv = 0; \ for(_ho_i=0; _ho_i < keylen; _ho_i++) { \ hashv += _ho_key[_ho_i]; \ hashv += (hashv << 10); \ hashv ^= (hashv >> 6); \ } \ hashv += (hashv << 3); \ hashv ^= (hashv >> 11); \ hashv += (hashv << 15); \ } while (0) #define HASH_JEN_MIX(a,b,c) \ do { \ a -= b; a -= c; a ^= ( c >> 13 ); \ b -= c; b -= a; b ^= ( a << 8 ); \ c -= a; c -= b; c ^= ( b >> 13 ); \ a -= b; a -= c; a ^= ( c >> 12 ); \ b -= c; b -= a; b ^= ( a << 16 ); \ c -= a; c -= b; c ^= ( b >> 5 ); \ a -= b; a -= c; a ^= ( c >> 3 ); \ b -= c; b -= a; b ^= ( a << 10 ); \ c -= a; c -= b; c ^= ( b >> 15 ); \ } while (0) #define HASH_JEN(key,keylen,hashv) \ do { \ unsigned _hj_i,_hj_j,_hj_k; \ unsigned const char *_hj_key=(unsigned const char*)(key); \ hashv = 0xfeedbeefu; \ _hj_i = _hj_j = 0x9e3779b9u; \ _hj_k = (unsigned)(keylen); \ while (_hj_k >= 12U) { \ _hj_i += (_hj_key[0] + ( (unsigned)_hj_key[1] << 8 ) \ + ( (unsigned)_hj_key[2] << 16 ) \ + ( (unsigned)_hj_key[3] << 24 ) ); \ _hj_j += (_hj_key[4] + ( (unsigned)_hj_key[5] << 8 ) \ + ( (unsigned)_hj_key[6] << 16 ) \ + ( (unsigned)_hj_key[7] << 24 ) ); \ hashv += (_hj_key[8] + ( (unsigned)_hj_key[9] << 8 ) \ + ( (unsigned)_hj_key[10] << 16 ) \ + ( (unsigned)_hj_key[11] << 24 ) ); \ \ HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ \ _hj_key += 12; \ _hj_k -= 12U; \ } \ hashv += (unsigned)(keylen); \ switch ( _hj_k ) { \ case 11: hashv += ( (unsigned)_hj_key[10] << 24 ); /* FALLTHROUGH */ \ case 10: hashv += ( (unsigned)_hj_key[9] << 16 ); /* FALLTHROUGH */ \ case 9: hashv += ( (unsigned)_hj_key[8] << 8 ); /* FALLTHROUGH */ \ case 8: _hj_j += ( (unsigned)_hj_key[7] << 24 ); /* FALLTHROUGH */ \ case 7: _hj_j += ( (unsigned)_hj_key[6] << 16 ); /* FALLTHROUGH */ \ case 6: _hj_j += ( (unsigned)_hj_key[5] << 8 ); /* FALLTHROUGH */ \ case 5: _hj_j += _hj_key[4]; /* FALLTHROUGH */ \ case 4: _hj_i += ( (unsigned)_hj_key[3] << 24 ); /* FALLTHROUGH */ \ case 3: _hj_i += ( (unsigned)_hj_key[2] << 16 ); /* FALLTHROUGH */ \ case 2: _hj_i += ( (unsigned)_hj_key[1] << 8 ); /* FALLTHROUGH */ \ case 1: _hj_i += _hj_key[0]; \ } \ HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ } while (0) /* The Paul Hsieh hash function */ #undef get16bits #if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) \ || defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__) #define get16bits(d) (*((const uint16_t *) (d))) #endif #if !defined (get16bits) #define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8) \ +(uint32_t)(((const uint8_t *)(d))[0]) ) #endif #define HASH_SFH(key,keylen,hashv) \ do { \ unsigned const char *_sfh_key=(unsigned const char*)(key); \ uint32_t _sfh_tmp, _sfh_len = (uint32_t)keylen; \ \ unsigned _sfh_rem = _sfh_len & 3U; \ _sfh_len >>= 2; \ hashv = 0xcafebabeu; \ \ /* Main loop */ \ for (;_sfh_len > 0U; _sfh_len--) { \ hashv += get16bits (_sfh_key); \ _sfh_tmp = ((uint32_t)(get16bits (_sfh_key+2)) << 11) ^ hashv; \ hashv = (hashv << 16) ^ _sfh_tmp; \ _sfh_key += 2U*sizeof (uint16_t); \ hashv += hashv >> 11; \ } \ \ /* Handle end cases */ \ switch (_sfh_rem) { \ case 3: hashv += get16bits (_sfh_key); \ hashv ^= hashv << 16; \ hashv ^= (uint32_t)(_sfh_key[sizeof (uint16_t)]) << 18; \ hashv += hashv >> 11; \ break; \ case 2: hashv += get16bits (_sfh_key); \ hashv ^= hashv << 11; \ hashv += hashv >> 17; \ break; \ case 1: hashv += *_sfh_key; \ hashv ^= hashv << 10; \ hashv += hashv >> 1; \ } \ \ /* Force "avalanching" of final 127 bits */ \ hashv ^= hashv << 3; \ hashv += hashv >> 5; \ hashv ^= hashv << 4; \ hashv += hashv >> 17; \ hashv ^= hashv << 25; \ hashv += hashv >> 6; \ } while (0) #ifdef HASH_USING_NO_STRICT_ALIASING /* The MurmurHash exploits some CPU's (x86,x86_64) tolerance for unaligned reads. * For other types of CPU's (e.g. Sparc) an unaligned read causes a bus error. * MurmurHash uses the faster approach only on CPU's where we know it's safe. * * Note the preprocessor built-in defines can be emitted using: * * gcc -m64 -dM -E - < /dev/null (on gcc) * cc -## a.c (where a.c is a simple test file) (Sun Studio) */ #if (defined(__i386__) || defined(__x86_64__) || defined(_M_IX86)) #define MUR_GETBLOCK(p,i) p[i] #else /* non intel */ #define MUR_PLUS0_ALIGNED(p) (((unsigned long)p & 3UL) == 0UL) #define MUR_PLUS1_ALIGNED(p) (((unsigned long)p & 3UL) == 1UL) #define MUR_PLUS2_ALIGNED(p) (((unsigned long)p & 3UL) == 2UL) #define MUR_PLUS3_ALIGNED(p) (((unsigned long)p & 3UL) == 3UL) #define WP(p) ((uint32_t*)((unsigned long)(p) & ~3UL)) #if (defined(__BIG_ENDIAN__) || defined(SPARC) || defined(__ppc__) || defined(__ppc64__)) #define MUR_THREE_ONE(p) ((((*WP(p))&0x00ffffff) << 8) | (((*(WP(p)+1))&0xff000000) >> 24)) #define MUR_TWO_TWO(p) ((((*WP(p))&0x0000ffff) <<16) | (((*(WP(p)+1))&0xffff0000) >> 16)) #define MUR_ONE_THREE(p) ((((*WP(p))&0x000000ff) <<24) | (((*(WP(p)+1))&0xffffff00) >> 8)) #else /* assume little endian non-intel */ #define MUR_THREE_ONE(p) ((((*WP(p))&0xffffff00) >> 8) | (((*(WP(p)+1))&0x000000ff) << 24)) #define MUR_TWO_TWO(p) ((((*WP(p))&0xffff0000) >>16) | (((*(WP(p)+1))&0x0000ffff) << 16)) #define MUR_ONE_THREE(p) ((((*WP(p))&0xff000000) >>24) | (((*(WP(p)+1))&0x00ffffff) << 8)) #endif #define MUR_GETBLOCK(p,i) (MUR_PLUS0_ALIGNED(p) ? ((p)[i]) : \ (MUR_PLUS1_ALIGNED(p) ? MUR_THREE_ONE(p) : \ (MUR_PLUS2_ALIGNED(p) ? MUR_TWO_TWO(p) : \ MUR_ONE_THREE(p)))) #endif #define MUR_ROTL32(x,r) (((x) << (r)) | ((x) >> (32 - (r)))) #define MUR_FMIX(_h) \ do { \ _h ^= _h >> 16; \ _h *= 0x85ebca6bu; \ _h ^= _h >> 13; \ _h *= 0xc2b2ae35u; \ _h ^= _h >> 16; \ } while (0) #define HASH_MUR(key,keylen,hashv) \ do { \ const uint8_t *_mur_data = (const uint8_t*)(key); \ const int _mur_nblocks = (int)(keylen) / 4; \ uint32_t _mur_h1 = 0xf88D5353u; \ uint32_t _mur_c1 = 0xcc9e2d51u; \ uint32_t _mur_c2 = 0x1b873593u; \ uint32_t _mur_k1 = 0; \ const uint8_t *_mur_tail; \ const uint32_t *_mur_blocks = (const uint32_t*)(_mur_data+(_mur_nblocks*4)); \ int _mur_i; \ for(_mur_i = -_mur_nblocks; _mur_i!=0; _mur_i++) { \ _mur_k1 = MUR_GETBLOCK(_mur_blocks,_mur_i); \ _mur_k1 *= _mur_c1; \ _mur_k1 = MUR_ROTL32(_mur_k1,15); \ _mur_k1 *= _mur_c2; \ \ _mur_h1 ^= _mur_k1; \ _mur_h1 = MUR_ROTL32(_mur_h1,13); \ _mur_h1 = (_mur_h1*5U) + 0xe6546b64u; \ } \ _mur_tail = (const uint8_t*)(_mur_data + (_mur_nblocks*4)); \ _mur_k1=0; \ switch((keylen) & 3U) { \ case 3: _mur_k1 ^= (uint32_t)_mur_tail[2] << 16; /* FALLTHROUGH */ \ case 2: _mur_k1 ^= (uint32_t)_mur_tail[1] << 8; /* FALLTHROUGH */ \ case 1: _mur_k1 ^= (uint32_t)_mur_tail[0]; \ _mur_k1 *= _mur_c1; \ _mur_k1 = MUR_ROTL32(_mur_k1,15); \ _mur_k1 *= _mur_c2; \ _mur_h1 ^= _mur_k1; \ } \ _mur_h1 ^= (uint32_t)(keylen); \ MUR_FMIX(_mur_h1); \ hashv = _mur_h1; \ } while (0) #endif /* HASH_USING_NO_STRICT_ALIASING */ /* iterate over items in a known bucket to find desired item */ #define HASH_FIND_IN_BKT(tbl,hh,head,keyptr,keylen_in,hashval,out) \ do { \ if ((head).hh_head != NULL) { \ DECLTYPE_ASSIGN(out, ELMT_FROM_HH(tbl, (head).hh_head)); \ } else { \ (out) = NULL; \ } \ while ((out) != NULL) { \ if ((out)->hh.hashv == (hashval) && (out)->hh.keylen == (keylen_in)) { \ if (uthash_memcmp((out)->hh.key, keyptr, keylen_in) == 0) { \ break; \ } \ } \ if ((out)->hh.hh_next != NULL) { \ DECLTYPE_ASSIGN(out, ELMT_FROM_HH(tbl, (out)->hh.hh_next)); \ } else { \ (out) = NULL; \ } \ } \ } while (0) /* add an item to a bucket */ #define HASH_ADD_TO_BKT(head,addhh) \ do { \ head.count++; \ (addhh)->hh_next = head.hh_head; \ (addhh)->hh_prev = NULL; \ if (head.hh_head != NULL) { (head).hh_head->hh_prev = (addhh); } \ (head).hh_head=addhh; \ if ((head.count >= ((head.expand_mult+1U) * HASH_BKT_CAPACITY_THRESH)) \ && ((addhh)->tbl->noexpand != 1U)) { \ HASH_EXPAND_BUCKETS((addhh)->tbl); \ } \ } while (0) /* remove an item from a given bucket */ #define HASH_DEL_IN_BKT(hh,head,hh_del) \ (head).count--; \ if ((head).hh_head == hh_del) { \ (head).hh_head = hh_del->hh_next; \ } \ if (hh_del->hh_prev) { \ hh_del->hh_prev->hh_next = hh_del->hh_next; \ } \ if (hh_del->hh_next) { \ hh_del->hh_next->hh_prev = hh_del->hh_prev; \ } /* Bucket expansion has the effect of doubling the number of buckets * and redistributing the items into the new buckets. Ideally the * items will distribute more or less evenly into the new buckets * (the extent to which this is true is a measure of the quality of * the hash function as it applies to the key domain). * * With the items distributed into more buckets, the chain length * (item count) in each bucket is reduced. Thus by expanding buckets * the hash keeps a bound on the chain length. This bounded chain * length is the essence of how a hash provides constant time lookup. * * The calculation of tbl->ideal_chain_maxlen below deserves some * explanation. First, keep in mind that we're calculating the ideal * maximum chain length based on the *new* (doubled) bucket count. * In fractions this is just n/b (n=number of items,b=new num buckets). * Since the ideal chain length is an integer, we want to calculate * ceil(n/b). We don't depend on floating point arithmetic in this * hash, so to calculate ceil(n/b) with integers we could write * * ceil(n/b) = (n/b) + ((n%b)?1:0) * * and in fact a previous version of this hash did just that. * But now we have improved things a bit by recognizing that b is * always a power of two. We keep its base 2 log handy (call it lb), * so now we can write this with a bit shift and logical AND: * * ceil(n/b) = (n>>lb) + ( (n & (b-1)) ? 1:0) * */ #define HASH_EXPAND_BUCKETS(tbl) \ do { \ unsigned _he_bkt; \ unsigned _he_bkt_i; \ struct UT_hash_handle *_he_thh, *_he_hh_nxt; \ UT_hash_bucket *_he_new_buckets, *_he_newbkt; \ _he_new_buckets = (UT_hash_bucket*)uthash_malloc( \ 2UL * tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ if (!_he_new_buckets) { uthash_fatal( "out of memory"); } \ memset(_he_new_buckets, 0, \ 2UL * tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ tbl->ideal_chain_maxlen = \ (tbl->num_items >> (tbl->log2_num_buckets+1U)) + \ (((tbl->num_items & ((tbl->num_buckets*2U)-1U)) != 0U) ? 1U : 0U); \ tbl->nonideal_items = 0; \ for(_he_bkt_i = 0; _he_bkt_i < tbl->num_buckets; _he_bkt_i++) \ { \ _he_thh = tbl->buckets[ _he_bkt_i ].hh_head; \ while (_he_thh != NULL) { \ _he_hh_nxt = _he_thh->hh_next; \ HASH_TO_BKT( _he_thh->hashv, tbl->num_buckets*2U, _he_bkt); \ _he_newbkt = &(_he_new_buckets[ _he_bkt ]); \ if (++(_he_newbkt->count) > tbl->ideal_chain_maxlen) { \ tbl->nonideal_items++; \ _he_newbkt->expand_mult = _he_newbkt->count / \ tbl->ideal_chain_maxlen; \ } \ _he_thh->hh_prev = NULL; \ _he_thh->hh_next = _he_newbkt->hh_head; \ if (_he_newbkt->hh_head != NULL) { _he_newbkt->hh_head->hh_prev = \ _he_thh; } \ _he_newbkt->hh_head = _he_thh; \ _he_thh = _he_hh_nxt; \ } \ } \ uthash_free( tbl->buckets, tbl->num_buckets*sizeof(struct UT_hash_bucket) ); \ tbl->num_buckets *= 2U; \ tbl->log2_num_buckets++; \ tbl->buckets = _he_new_buckets; \ tbl->ineff_expands = (tbl->nonideal_items > (tbl->num_items >> 1)) ? \ (tbl->ineff_expands+1U) : 0U; \ if (tbl->ineff_expands > 1U) { \ tbl->noexpand=1; \ uthash_noexpand_fyi(tbl); \ } \ uthash_expand_fyi(tbl); \ } while (0) /* This is an adaptation of Simon Tatham's O(n log(n)) mergesort */ /* Note that HASH_SORT assumes the hash handle name to be hh. * HASH_SRT was added to allow the hash handle name to be passed in. */ #define HASH_SORT(head,cmpfcn) HASH_SRT(hh,head,cmpfcn) #define HASH_SRT(hh,head,cmpfcn) \ do { \ unsigned _hs_i; \ unsigned _hs_looping,_hs_nmerges,_hs_insize,_hs_psize,_hs_qsize; \ struct UT_hash_handle *_hs_p, *_hs_q, *_hs_e, *_hs_list, *_hs_tail; \ if (head != NULL) { \ _hs_insize = 1; \ _hs_looping = 1; \ _hs_list = &((head)->hh); \ while (_hs_looping != 0U) { \ _hs_p = _hs_list; \ _hs_list = NULL; \ _hs_tail = NULL; \ _hs_nmerges = 0; \ while (_hs_p != NULL) { \ _hs_nmerges++; \ _hs_q = _hs_p; \ _hs_psize = 0; \ for ( _hs_i = 0; _hs_i < _hs_insize; _hs_i++ ) { \ _hs_psize++; \ _hs_q = (UT_hash_handle*)((_hs_q->next != NULL) ? \ ((void*)((char*)(_hs_q->next) + \ (head)->hh.tbl->hho)) : NULL); \ if (! (_hs_q) ) { break; } \ } \ _hs_qsize = _hs_insize; \ while ((_hs_psize > 0U) || ((_hs_qsize > 0U) && (_hs_q != NULL))) {\ if (_hs_psize == 0U) { \ _hs_e = _hs_q; \ _hs_q = (UT_hash_handle*)((_hs_q->next != NULL) ? \ ((void*)((char*)(_hs_q->next) + \ (head)->hh.tbl->hho)) : NULL); \ _hs_qsize--; \ } else if ( (_hs_qsize == 0U) || (_hs_q == NULL) ) { \ _hs_e = _hs_p; \ if (_hs_p != NULL){ \ _hs_p = (UT_hash_handle*)((_hs_p->next != NULL) ? \ ((void*)((char*)(_hs_p->next) + \ (head)->hh.tbl->hho)) : NULL); \ } \ _hs_psize--; \ } else if (( \ cmpfcn(DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl,_hs_p)), \ DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl,_hs_q))) \ ) <= 0) { \ _hs_e = _hs_p; \ if (_hs_p != NULL){ \ _hs_p = (UT_hash_handle*)((_hs_p->next != NULL) ? \ ((void*)((char*)(_hs_p->next) + \ (head)->hh.tbl->hho)) : NULL); \ } \ _hs_psize--; \ } else { \ _hs_e = _hs_q; \ _hs_q = (UT_hash_handle*)((_hs_q->next != NULL) ? \ ((void*)((char*)(_hs_q->next) + \ (head)->hh.tbl->hho)) : NULL); \ _hs_qsize--; \ } \ if ( _hs_tail != NULL ) { \ _hs_tail->next = ((_hs_e != NULL) ? \ ELMT_FROM_HH((head)->hh.tbl,_hs_e) : NULL); \ } else { \ _hs_list = _hs_e; \ } \ if (_hs_e != NULL) { \ _hs_e->prev = ((_hs_tail != NULL) ? \ ELMT_FROM_HH((head)->hh.tbl,_hs_tail) : NULL); \ } \ _hs_tail = _hs_e; \ } \ _hs_p = _hs_q; \ } \ if (_hs_tail != NULL){ \ _hs_tail->next = NULL; \ } \ if ( _hs_nmerges <= 1U ) { \ _hs_looping=0; \ (head)->hh.tbl->tail = _hs_tail; \ DECLTYPE_ASSIGN(head,ELMT_FROM_HH((head)->hh.tbl, _hs_list)); \ } \ _hs_insize *= 2U; \ } \ HASH_FSCK(hh,head); \ } \ } while (0) /* This function selects items from one hash into another hash. * The end result is that the selected items have dual presence * in both hashes. There is no copy of the items made; rather * they are added into the new hash through a secondary hash * hash handle that must be present in the structure. */ #define HASH_SELECT(hh_dst, dst, hh_src, src, cond) \ do { \ unsigned _src_bkt, _dst_bkt; \ void *_last_elt=NULL, *_elt; \ UT_hash_handle *_src_hh, *_dst_hh, *_last_elt_hh=NULL; \ ptrdiff_t _dst_hho = ((char*)(&(dst)->hh_dst) - (char*)(dst)); \ if (src != NULL) { \ for(_src_bkt=0; _src_bkt < (src)->hh_src.tbl->num_buckets; _src_bkt++) { \ for(_src_hh = (src)->hh_src.tbl->buckets[_src_bkt].hh_head; \ _src_hh != NULL; \ _src_hh = _src_hh->hh_next) { \ _elt = ELMT_FROM_HH((src)->hh_src.tbl, _src_hh); \ if (cond(_elt)) { \ _dst_hh = (UT_hash_handle*)(((char*)_elt) + _dst_hho); \ _dst_hh->key = _src_hh->key; \ _dst_hh->keylen = _src_hh->keylen; \ _dst_hh->hashv = _src_hh->hashv; \ _dst_hh->prev = _last_elt; \ _dst_hh->next = NULL; \ if (_last_elt_hh != NULL) { _last_elt_hh->next = _elt; } \ if (dst == NULL) { \ DECLTYPE_ASSIGN(dst,_elt); \ HASH_MAKE_TABLE(hh_dst,dst); \ } else { \ _dst_hh->tbl = (dst)->hh_dst.tbl; \ } \ HASH_TO_BKT(_dst_hh->hashv, _dst_hh->tbl->num_buckets, _dst_bkt); \ HASH_ADD_TO_BKT(_dst_hh->tbl->buckets[_dst_bkt],_dst_hh); \ (dst)->hh_dst.tbl->num_items++; \ _last_elt = _elt; \ _last_elt_hh = _dst_hh; \ } \ } \ } \ } \ HASH_FSCK(hh_dst,dst); \ } while (0) #define HASH_CLEAR(hh,head) \ do { \ if (head != NULL) { \ uthash_free((head)->hh.tbl->buckets, \ (head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket)); \ HASH_BLOOM_FREE((head)->hh.tbl); \ uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ (head)=NULL; \ } \ } while (0) #define HASH_OVERHEAD(hh,head) \ ((head != NULL) ? ( \ (size_t)(((head)->hh.tbl->num_items * sizeof(UT_hash_handle)) + \ ((head)->hh.tbl->num_buckets * sizeof(UT_hash_bucket)) + \ sizeof(UT_hash_table) + \ (HASH_BLOOM_BYTELEN))) : 0U) #ifdef NO_DECLTYPE #define HASH_ITER(hh,head,el,tmp) \ for(((el)=(head)), ((*(char**)(&(tmp)))=(char*)((head!=NULL)?(head)->hh.next:NULL)); \ (el) != NULL; ((el)=(tmp)), ((*(char**)(&(tmp)))=(char*)((tmp!=NULL)?(tmp)->hh.next:NULL))) #else #define HASH_ITER(hh,head,el,tmp) \ for(((el)=(head)), ((tmp)=DECLTYPE(el)((head!=NULL)?(head)->hh.next:NULL)); \ (el) != NULL; ((el)=(tmp)), ((tmp)=DECLTYPE(el)((tmp!=NULL)?(tmp)->hh.next:NULL))) #endif /* obtain a count of items in the hash */ #define HASH_COUNT(head) HASH_CNT(hh,head) #define HASH_CNT(hh,head) ((head != NULL)?((head)->hh.tbl->num_items):0U) typedef struct UT_hash_bucket { struct UT_hash_handle *hh_head; unsigned count; /* expand_mult is normally set to 0. In this situation, the max chain length * threshold is enforced at its default value, HASH_BKT_CAPACITY_THRESH. (If * the bucket's chain exceeds this length, bucket expansion is triggered). * However, setting expand_mult to a non-zero value delays bucket expansion * (that would be triggered by additions to this particular bucket) * until its chain length reaches a *multiple* of HASH_BKT_CAPACITY_THRESH. * (The multiplier is simply expand_mult+1). The whole idea of this * multiplier is to reduce bucket expansions, since they are expensive, in * situations where we know that a particular bucket tends to be overused. * It is better to let its chain length grow to a longer yet-still-bounded * value, than to do an O(n) bucket expansion too often. */ unsigned expand_mult; } UT_hash_bucket; /* random signature used only to find hash tables in external analysis */ #define HASH_SIGNATURE 0xa0111fe1u #define HASH_BLOOM_SIGNATURE 0xb12220f2u typedef struct UT_hash_table { UT_hash_bucket *buckets; unsigned num_buckets, log2_num_buckets; unsigned num_items; struct UT_hash_handle *tail; /* tail hh in app order, for fast append */ ptrdiff_t hho; /* hash handle offset (byte pos of hash handle in element */ /* in an ideal situation (all buckets used equally), no bucket would have * more than ceil(#items/#buckets) items. that's the ideal chain length. */ unsigned ideal_chain_maxlen; /* nonideal_items is the number of items in the hash whose chain position * exceeds the ideal chain maxlen. these items pay the penalty for an uneven * hash distribution; reaching them in a chain traversal takes >ideal steps */ unsigned nonideal_items; /* ineffective expands occur when a bucket doubling was performed, but * afterward, more than half the items in the hash had nonideal chain * positions. If this happens on two consecutive expansions we inhibit any * further expansion, as it's not helping; this happens when the hash * function isn't a good fit for the key domain. When expansion is inhibited * the hash will still work, albeit no longer in constant time. */ unsigned ineff_expands, noexpand; uint32_t signature; /* used only to find hash tables in external analysis */ #ifdef HASH_BLOOM uint32_t bloom_sig; /* used only to test bloom exists in external analysis */ uint8_t *bloom_bv; uint8_t bloom_nbits; #endif } UT_hash_table; typedef struct UT_hash_handle { struct UT_hash_table *tbl; void *prev; /* prev element in app order */ void *next; /* next element in app order */ struct UT_hash_handle *hh_prev; /* previous hh in bucket order */ struct UT_hash_handle *hh_next; /* next hh in bucket order */ void *key; /* ptr to enclosing struct's key */ unsigned keylen; /* enclosing struct's key len */ unsigned hashv; /* result of hash-fcn(key) */ } UT_hash_handle; #endif /* UTHASH_H */ nsca-ng-1.6/src/000077500000000000000000000000001344421036200134745ustar00rootroot00000000000000nsca-ng-1.6/src/Makefile.am000066400000000000000000000030271344421036200155320ustar00rootroot00000000000000## Process this file with automake(1) to produce Makefile.in. ## Copyright (c) 2013 Holger Weiss ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1. Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## ## 2. Redistributions in binary form must reproduce the above copyright notice, ## this list of conditions and the following disclaimer in the documentation ## and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE ## LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ## CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF ## SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ## INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ## CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ## ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ## POSSIBILITY OF SUCH DAMAGE. SUBDIRS = common if BUILD_CLIENT SUBDIRS += client endif if BUILD_SERVER SUBDIRS += server endif nsca-ng-1.6/src/client/000077500000000000000000000000001344421036200147525ustar00rootroot00000000000000nsca-ng-1.6/src/client/Makefile.am000066400000000000000000000042731344421036200170140ustar00rootroot00000000000000## Process this file with automake(1) to produce Makefile.in. ## Copyright (c) 2013 Holger Weiss ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1. Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## ## 2. Redistributions in binary form must reproduce the above copyright notice, ## this list of conditions and the following disclaimer in the documentation ## and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE ## LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ## CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF ## SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ## INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ## CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ## ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ## POSSIBILITY OF SUCH DAMAGE. AM_CPPFLAGS = \ -DSYSCONFDIR='"$(sysconfdir)"' \ -I$(top_srcdir)/src/common \ -I$(top_srcdir)/lib \ $(EVCPPFLAGS) \ $(SSLCPPFLAGS) AM_LDFLAGS = \ $(EVLDFLAGS) \ $(SSLLDFLAGS) LDADD = \ ../common/libcommon.a \ ../../lib/libcompat.a \ $(EVLIBS) \ $(SSLLIBS) if USE_EMBEDDED_EV AM_CPPFLAGS += -I$(top_srcdir)/lib/ev LDADD += ../../lib/ev/libev.a endif sbin_PROGRAMS = send_nsca send_nsca_SOURCES = auth.c auth.h client.c client.h conf.c conf.h input.c \ input.h parse.c parse.h send_nsca.c send_nsca.h nsca-ng-1.6/src/client/auth.c000066400000000000000000000044261344421036200160650ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #if HAVE_CONFIG_H # include #endif #include #include #include "auth.h" #include "conf.h" #include "send_nsca.h" #include "system.h" unsigned int set_psk(SSL *ssl __attribute__((__unused__)), const char *hint __attribute__((__unused__)), char *identity, unsigned int max_identity_len, unsigned char *password, unsigned int max_password_len) { char *configured_id = conf_getstr(cfg, "identity"); char *configured_pw = conf_getstr(cfg, "password"); size_t identity_len = MIN(strlen(configured_id), max_identity_len - 1); size_t password_len = MIN(strlen(configured_pw), max_password_len); (void)memcpy(identity, configured_id, identity_len); (void)memcpy(password, configured_pw, password_len); identity[identity_len] = '\0'; return (unsigned int)password_len; } /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/src/client/auth.h000066400000000000000000000032641344421036200160710ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef AUTH_H # define AUTH_H # if HAVE_CONFIG_H # include # endif # include # include "system.h" unsigned int set_psk(SSL *, const char *, char *, unsigned int, unsigned char *, unsigned int); #endif /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/src/client/client.c000066400000000000000000000217071344421036200164030ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #if HAVE_CONFIG_H # include #endif #include #include #if HAVE_STRINGS_H # include #endif #include #include #include "auth.h" #include "client.h" #include "input.h" #include "log.h" #include "parse.h" #include "send_nsca.h" #include "system.h" #include "tls.h" #include "util.h" #include "wrappers.h" #ifndef NUM_SESSION_ID_BYTES # define NUM_SESSION_ID_BYTES 6 #endif struct client_state_s { /* This is typedef'd to `client_state' in client.h. */ tls_client_state *tls_client; tls_state *tls; input_state *input; char *command; size_t command_length; int mode; char delimiter; char separator; }; static void handle_input_chunk(input_state * restrict, char * restrict); static void handle_input_eof(input_state *); static void handle_tls_connect(tls_state *); static void handle_tls_moin_response(tls_state * restrict, char * restrict); static void handle_tls_push_response(tls_state * restrict, char * restrict); static void handle_tls_command_response(tls_state * restrict, char * restrict); static void handle_tls_quit_response(tls_state * restrict, char * restrict); static void send_request(tls_state * restrict, const char * restrict); static void bail(tls_state * restrict, const char * restrict, ...) __attribute__((__format__(__printf__, 2, 3))); static bool server_is_grumpy(tls_state * restrict, char * restrict); static char *generate_session_id(void); static char *base64(const unsigned char *, size_t); /* * Exported functions. */ client_state * client_start(const char *server, const char *ciphers, ev_tstamp timeout, int mode, char delimiter, char separator) { client_state *client = xmalloc(sizeof(client_state)); client->tls_client = tls_client_start(ciphers); client->tls_client->data = client; client->tls = NULL; client->input = NULL; client->mode = mode; client->delimiter = delimiter; client->separator = mode == CLIENT_MODE_COMMAND ? '\n' : separator; tls_connect(client->tls_client, server, timeout, TLS_AUTO_DIE, handle_tls_connect, NULL, set_psk); return client; } void client_stop(client_state *client) { if (client->input != NULL) input_stop(client->input); if (client->tls != NULL) tls_shutdown(client->tls); if (client->tls_client != NULL) tls_client_stop(client->tls_client); free(client); } /* * Static functions. */ static void handle_input_chunk(input_state * restrict input, char * restrict chunk) { client_state *client = input->data; char *request; char *data = skip_newlines(chunk); if (*data == '\0') { /* Ignore empty input lines. */ free(chunk); input_read_chunk(input, handle_input_chunk); return; } if (client->mode == CLIENT_MODE_CHECK_RESULT) { chomp(data); client->command = parse_check_result(data, client->delimiter); } else client->command = parse_command(data); free(chunk); client->command_length = strlen(client->command); client->command[client->command_length++] = '\n'; xasprintf(&request, "PUSH %u", client->command_length); info("%s C: %s", client->tls->peer, request); tls_write_line(client->tls, request); free(request); tls_read_line(client->tls, handle_tls_push_response); } static void handle_input_eof(input_state *input) { client_state *client = input->data; client->input = NULL; send_request(client->tls, "QUIT"); tls_read_line(client->tls, handle_tls_quit_response); } static void handle_tls_connect(tls_state *tls) { client_state *client = tls->data; char *session_id = generate_session_id(); char *request = concat("MOIN 1 ", session_id); client->tls = tls; tls_set_connection_id(tls, session_id); free(session_id); send_request(tls, request); free(request); tls_read_line(tls, handle_tls_moin_response); } static void handle_tls_moin_response(tls_state * restrict tls, char * restrict line) { client_state *client = tls->data; int protocol_version; char *args[2]; info("%s S: %s", tls->peer, line); if (strncasecmp("MOIN", line, 4) == 0) { if (!parse_line(line, args, 2)) bail(tls, "Cannot parse MOIN response"); else if ((protocol_version = atoi(args[1])) <= 0) bail(tls, "Expected protocol version"); else if (protocol_version != 1) bail(tls, "Protocol version %d not supported", protocol_version); else { /* The handshake succeeded. */ debug("Protocol handshake successful"); client->input = input_start(client->separator); client->input->data = client; input_on_eof(client->input, handle_input_eof); input_read_chunk(client->input, handle_input_chunk); } } else if (!server_is_grumpy(tls, line)) bail(tls, "Received unexpected MOIN response"); free(line); } static void handle_tls_push_response(tls_state * restrict tls, char * restrict line) { client_state *client = tls->data; info("%s S: %s", tls->peer, line); if (strcasecmp("OKAY", line) == 0) { notice("Transmitting to %s: %.*s", tls->peer, (int)client->command_length - 1, client->command); tls_write(tls, client->command, client->command_length, free); tls_read_line(tls, handle_tls_command_response); } else if (!server_is_grumpy(tls, line)) { free(client->command); bail(tls, "Received unexpected PUSH response"); } free(line); } static void handle_tls_command_response(tls_state * restrict tls, char * restrict line) { client_state *client = tls->data; info("%s S: %s", tls->peer, line); if (strcasecmp("OKAY", line) == 0) input_read_chunk(client->input, handle_input_chunk); else if (!server_is_grumpy(tls, line)) bail(tls, "Received unexpected response after sending command(s)"); free(line); } static void handle_tls_quit_response(tls_state * restrict tls, char * restrict line) { client_state *client = tls->data; info("%s S: %s", tls->peer, line); if (strcasecmp("OKAY", line) == 0) client_stop(client); else if (!server_is_grumpy(tls, line)) bail(tls, "Received unexpected QUIT response"); free(line); } static void send_request(tls_state * restrict tls, const char * restrict request) { info("%s C: %s", tls->peer, request); tls_write_line(tls, request); } static void bail(tls_state * restrict tls, const char * restrict fmt, ...) { va_list ap; char *message; client_state *client = tls->data; va_start(ap, fmt); xvasprintf(&message, fmt, ap); va_end(ap); info("%s C: %s %s", tls->peer, "BAIL", message); tls_write(tls, "BAIL ", sizeof("BAIL ") - 1, NULL); tls_write_line(tls, message); client_stop(client); critical("%s", message); free(message); exit_code = EXIT_FAILURE; } static bool server_is_grumpy(tls_state * restrict tls, char * restrict line) { client_state *client = tls->data; if (strncasecmp("FAIL", line, 4) == 0 || strncasecmp("BAIL", line, 4) == 0) { client_stop(client); critical("Server said: %s", line); exit_code = EXIT_FAILURE; return true; } return false; } static char * generate_session_id(void) { unsigned char random_bytes[NUM_SESSION_ID_BYTES]; (void)RAND_pseudo_bytes(random_bytes, sizeof(random_bytes)); return base64(random_bytes, sizeof(random_bytes)); } static char * base64(const unsigned char *input, size_t input_size) { BIO *bio_b64, *bio_mem; char *mem_data, *output; long output_size; bio_mem = BIO_new(BIO_s_mem()); bio_b64 = BIO_new(BIO_f_base64()); BIO_set_flags(bio_b64, BIO_FLAGS_BASE64_NO_NL); bio_b64 = BIO_push(bio_b64, bio_mem); (void)BIO_write(bio_b64, input, (int)input_size); (void)BIO_flush(bio_b64); output_size = BIO_get_mem_data(bio_b64, &mem_data) + 1; output = xmalloc((size_t)output_size); (void)memcpy(output, mem_data, (size_t)output_size); output[output_size - 1] = '\0'; BIO_free_all(bio_b64); return output; } /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/src/client/client.h000066400000000000000000000035001344421036200163770ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef CLIENT_H # define CLIENT_H # if HAVE_CONFIG_H # include # endif # include # include "system.h" enum { CLIENT_MODE_COMMAND, CLIENT_MODE_CHECK_RESULT }; typedef struct client_state_s client_state; client_state *client_start(const char *, const char *, ev_tstamp, int, char, char); void client_stop(client_state *); #endif /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/src/client/conf.c000066400000000000000000000166731344421036200160600ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #if HAVE_CONFIG_H # include #endif #include #include #include #include #include "conf.h" #include "log.h" #include "system.h" #include "util.h" #include "wrappers.h" #define DEFAULT_PASSWORD "change-me" #define DEFAULT_PORT "5668" #define DEFAULT_SERVER "localhost" #define DEFAULT_TIMEOUT 15 #define DEFAULT_TLS_CIPHERS \ "PSK-AES256-CBC-SHA:PSK-AES128-CBC-SHA:PSK-3DES-EDE-CBC-SHA:PSK-RC4-SHA" struct conf_s { /* This is typedef'd to `conf' in conf.h. */ const char *key; enum { TYPE_NONE, TYPE_STRING, TYPE_INTEGER } type; union { char *s; long i; } value; }; static unsigned long line_number = 0; static conf *lookup_conf(conf * restrict, const char * restrict); static void parse_conf_file(const char * restrict, conf * restrict); static char *read_conf_line(FILE *); /* * Exported functions. */ conf * conf_init(const char *path) { static conf cfg[] = { { "delay", TYPE_INTEGER, { 0 } }, { "encryption_method", TYPE_STRING, { NULL } }, { "identity", TYPE_STRING, { NULL } }, { "password", TYPE_STRING, { NULL } }, { "port", TYPE_STRING, { NULL } }, { "server", TYPE_STRING, { NULL } }, { "timeout", TYPE_INTEGER, { 0 } }, { "tls_ciphers", TYPE_STRING, { NULL } }, { NULL, TYPE_NONE, { NULL } } }; debug("Initializing configuration context"); conf_setstr(cfg, "password", DEFAULT_PASSWORD); conf_setstr(cfg, "port", DEFAULT_PORT); conf_setstr(cfg, "server", DEFAULT_SERVER); conf_setint(cfg, "timeout", DEFAULT_TIMEOUT); conf_setstr(cfg, "tls_ciphers", DEFAULT_TLS_CIPHERS); parse_conf_file(path, cfg); if (conf_getstr(cfg, "identity") == NULL) { char host_name[256]; if (gethostname(host_name, sizeof(host_name)) == -1) die("Cannot get host name: %m"); conf_setstr(cfg, "identity", host_name); } return cfg; } long conf_getint(conf * restrict cfg, const char * restrict key) { conf *c = lookup_conf(cfg, key); return c->value.i; } char * conf_getstr(conf * restrict cfg, const char * restrict key) { conf *c = lookup_conf(cfg, key); return c->value.s; } void conf_setint(conf * restrict cfg, const char * restrict key, long value) { conf *c = lookup_conf(cfg, key); c->value.i = value; } void conf_setstr(conf * restrict cfg, const char * restrict key, const char * restrict value) { conf *c = lookup_conf(cfg, key); if (c->value.s != NULL) free(c->value.s); c->value.s = xstrdup(value); } void conf_free(conf *cfg) { conf *c; debug("Destroying configuration context"); for (c = cfg; c->key != NULL; c++) if (c->type == TYPE_STRING && c->value.s != NULL) free(c->value.s); } /* * Static functions. */ static conf * lookup_conf(conf * restrict cfg, const char * restrict key) { conf *c; for (c = cfg; c->key != NULL && strcmp(key, c->key) != 0; c++) continue; if (c->key == NULL) die("Unknown variable `%s'", key); return c; } static void parse_conf_file(const char * restrict path, conf * restrict cfg) { FILE *f; char *line; if ((f = fopen(path, "r")) == NULL) die("Cannot open %s: %m", path); while ((line = read_conf_line(f)) != NULL) { conf *c; char *token, *in, *out; char quote_sign, value[2048]; size_t len; bool done = false, escape = false; /* * Parse the key. */ token = skip_whitespace(line); if (*token == '\0' || *token == '#') { /* The line is empty. */ free(line); continue; } if ((len = strcspn(token, " \t=")) == 0) die("%s:%lu: Cannot parse line", path, line_number); for (c = cfg; c->key != NULL && (strlen(c->key) != len || strncmp(token, c->key, len) != 0); c++) continue; if (c->key == NULL) die("%s:%lu: Unknown variable name `%.*s'", path, line_number, (int)len, token); /* * Eat the `='. */ token = skip_whitespace(token + len); if (*token != '=') die("%s:%lu: Expected `=' after `%s'", path, line_number, c->key); /* * Parse the value. */ token = skip_whitespace(token + 1); switch (*token) { case '#': case '\0': die("%s:%lu: No value assigned to `%s'", path, line_number, c->key); case '"': case '\'': quote_sign = *token; token++; break; default: quote_sign = 0; } for (in = token, out = value, len = 0; *in != '\0' && !done; in++) { if (len >= sizeof(value) - 1) die("%s:%lu: Value of `%s' is too long", path, line_number, c->key); if (escape) { *out++ = *in; len++; escape = false; continue; } if (*in == quote_sign || (quote_sign == 0 && (*in == '#' || *in == ' ' || *in == '\t'))) done = true; else if (*in == '\\') escape = true; else { *out++ = *in; len++; } } value[len] = '\0'; /* * Check the end of the line. */ token = skip_whitespace(in); if (*token != '\0' && *token != '#') die("%s:%lu: Unexpected stuff after `%s'", path, line_number, value); debug("%s:%lu: %s = %s", path, line_number, c->key, value); /* * Save the value. */ if (c->type == TYPE_STRING) conf_setstr(cfg, c->key, value); else { char *end; long num = strtol(value, &end, 0); if (*end != '\0') die("%s:%lu: Nonnumeric value assigned to `%s'", path, line_number, c->key); conf_setint(cfg, c->key, num); } /* Forget this copy of the value, in case it's sensitive. */ (void)memset(value, 0, strlen(value)); (void)memset(line, 0, strlen(line)); free(line); } if (fclose(f) == EOF) die("Cannot close %s: %m", path); } static char * read_conf_line(FILE *f) { size_t len, pos = 0, size = 512; char *line = xmalloc(size); while ((len = xfgets(line + pos, (int)(size - pos), f)) > 0) { pos += len; if (line[pos - 1] != '\n' && pos == size - 1) line = xrealloc(line, size *= 2); else { line_number++; if (pos >= 2) { if (line[pos - 2] == '\\') { pos -= 2; continue; } if (line[pos - 2] == '\r') { line[pos - 2] = '\n'; line[pos - 1] = '\0'; pos--; } } break; } } if (pos == 0) { /* EOF */ free(line); return NULL; } chomp(line); return xrealloc(line, pos + 1); } /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/src/client/conf.h000066400000000000000000000037031344421036200160530ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef CONF_H # define CONF_H # if HAVE_CONFIG_H # include # endif # include "system.h" # define DEFAULT_CONF_FILE SYSCONFDIR "/send_nsca.cfg" typedef struct conf_s conf; conf *conf_init(const char *); long conf_getint(conf * restrict, const char * restrict); char *conf_getstr(conf * restrict, const char * restrict); void conf_setint(conf * restrict, const char * restrict, long); void conf_setstr(conf * restrict, const char * restrict, const char * restrict); void conf_free(conf *); #endif /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/src/client/input.c000066400000000000000000000110001344421036200162450ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #if HAVE_CONFIG_H # include #endif #include #include /* Required by on some systems. */ #include #include #include #include "input.h" #include "log.h" #include "system.h" #include "util.h" #include "wrappers.h" static void read_cb(EV_P_ ev_io *, int); /* * Exported functions. */ input_state * input_start(char separator) { int flags; input_state *input = xmalloc(sizeof(input_state)); debug("Starting standard input reader"); input->watcher.data = input; input->buffer = buffer_new(); input->read_handler = NULL; input->eof_handler = NULL; input->fd = STDIN_FILENO; input->separator = separator; input->eof = false; if ((flags = fcntl(input->fd, F_GETFL, 0)) == -1) die("Cannot get standard input descriptor flags: %m"); if (fcntl(input->fd, F_SETFL, flags | O_NONBLOCK) == -1) die("Cannot mark standard input as non-blocking: %m"); ev_io_init(&input->watcher, read_cb, input->fd, EV_READ); return input; } void input_read_chunk(input_state *input, void handle_read(input_state *, char *)) { debug("Got request to read a chunk from standard input"); if (!input->eof) { input->read_handler = handle_read; ev_io_start(EV_DEFAULT_UC_ &input->watcher); ev_invoke(EV_DEFAULT_UC_ &input->watcher, EV_CUSTOM); } else { debug("There's no (more) data available"); if (input->eof_handler != NULL) input->eof_handler(input); input_stop(input); } } void input_stop(input_state *input) { debug("Stopping standard input reader"); if (ev_is_active(&input->watcher)) ev_io_stop(EV_DEFAULT_UC_ &input->watcher); buffer_free(input->buffer); free(input); } void input_on_eof(input_state *input, void handle_eof(input_state *)) { input->eof_handler = handle_eof; } /* * Static functions. */ static void read_cb(EV_P_ ev_io *w, int revents __attribute__((__unused__))) { input_state *input = w->data; char *chunk; ssize_t n; do { if ((chunk = buffer_read_chunk(input->buffer, input->separator)) != NULL) { debug("Got complete chunk from standard input"); ev_io_stop(EV_A_ w); input->read_handler(input, chunk); break; } if ((n = read(input->fd, input->input, sizeof(input->input))) < 0) { if (errno == EAGAIN #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN || errno == EWOULDBLOCK #endif || errno == EINTR) debug("Cannot read from standard input: %m"); else die("Cannot read from standard input: %m"); } else if (n == 0) { size_t len = buffer_size(input->buffer); debug("Got EOF from standard input"); input->eof = true; if (len > 0) { debug("Providing the available data"); ev_io_stop(EV_A_ w); chunk = xmalloc(len + 1); (void)buffer_read(input->buffer, chunk, len); chunk[len] = '\0'; input->read_handler(input, chunk); } else { debug("No (more) data available"); if (input->eof_handler != NULL) input->eof_handler(input); input_stop(input); } } else { debug("Got %zd bytes from standard input", n); buffer_append(input->buffer, input->input, (size_t)n); } } while (n > 0); } /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/src/client/input.h000066400000000000000000000043341344421036200162660ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef INPUT_H # define INPUT_H # if HAVE_CONFIG_H # include # endif # include # include "buffer.h" # include "system.h" typedef struct input_state_s { /* public: */ void *data; /* Can freely be used by the caller. */ /* private: */ ev_io watcher; buffer *buffer; char input[128]; void (*read_handler)(struct input_state_s * restrict, char * restrict); void (*eof_handler)(struct input_state_s *); int fd; char separator; bool eof; } input_state; input_state *input_start(char separator); void input_read_chunk(input_state *, void (*)(input_state * restrict, char * restrict)); void input_stop(input_state *); void input_on_eof(input_state *, void (*)(input_state *)); void input_on_error(input_state *, void (*)(input_state *)); #endif /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/src/client/parse.c000066400000000000000000000074731344421036200162430ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #if HAVE_CONFIG_H # include #endif #include #include #include #include "log.h" #include "parse.h" #include "system.h" #include "util.h" #include "wrappers.h" static char *escape(const char *); /* * Exported functions. */ char * parse_command(const char *line) { char *command; debug("Parsing monitoring command"); line = skip_whitespace(line); if (line[0] == '[') command = xstrdup(line); else xasprintf(&command, "[%lu] %s", (unsigned long)time(NULL), line); return command; } char * parse_check_result(const char *input, char delimiter) { const char *fields[4] = { NULL, NULL, NULL, NULL }; char *command, *escaped; int lengths[3]; int n, pos, start_pos; debug("Parsing check result"); if (strpbrk(input, "\\\n") != NULL) input = escaped = escape(input); else escaped = NULL; fields[0] = input; start_pos = 0; n = 1; for (pos = 0; n < 4 && input[pos] != '\0'; pos++) if (input[pos] == delimiter) { lengths[n - 1] = pos - start_pos; debug("Check result field %d has %d characters (%d-%d)", n, lengths[n - 1], start_pos, pos - 1); /* Handle the next field. */ start_pos = pos + 1; fields[n] = &input[start_pos]; n++; } switch (n) { case 3: debug("Got host check result"); xasprintf(&command, "[%lu] PROCESS_HOST_CHECK_RESULT;%.*s;%.*s;%s", (unsigned long)time(NULL), lengths[0], fields[0], lengths[1], fields[1], fields[2]); break; case 4: debug("Got service check result"); xasprintf(&command, "[%lu] PROCESS_SERVICE_CHECK_RESULT;%.*s;%.*s;%.*s;%s", (unsigned long)time(NULL), lengths[0], fields[0], lengths[1], fields[1], lengths[2], fields[2], fields[3]); break; default: die("Input format incorrect, see the %s(8) man page", getprogname()); } if (escaped != NULL) free(escaped); return command; } /* * Static functions. */ static char * escape(const char *input) { const char *in; char *escaped, *out; size_t size = strlen(input) + 1; for (in = input; *in != '\0'; in++) if (*in == '\\' || *in == '\n') size++; escaped = xmalloc(size); for (in = input, out = escaped; *in != '\0'; in++, out++) switch (*in) { case '\\': *out++ = '\\'; *out = '\\'; break; case '\n': *out++ = '\\'; *out = 'n'; break; default: *out = *in; } *out = '\0'; return escaped; } /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/src/client/parse.h000066400000000000000000000032041344421036200162340ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef PARSE_H # define PARSE_H # if HAVE_CONFIG_H # include # endif # include "system.h" char *parse_command(const char *); char *parse_check_result(const char *, char); #endif /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/src/client/send_nsca.c000066400000000000000000000231701344421036200170560ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #if HAVE_CONFIG_H # include #endif #include #if HAVE_INTTYPES_H # include #endif #include #include #include #include #if HAVE_NANOSLEEP # include #endif #include #include #include #include "client.h" #include "conf.h" #include "log.h" #include "send_nsca.h" #include "system.h" #include "util.h" #include "wrappers.h" typedef struct { char *conf_file; char *port; char *server; int delay; int log_level; int log_target; int timeout; char delimiter; char separator; bool raw_commands; } options; conf *cfg = NULL; int exit_code = EXIT_SUCCESS; static options *get_options(int, char **); static void free_options(options *); static int parse_backslash_escape(const char *); static void delay_execution(unsigned int); static unsigned long random_number(unsigned long); static void forget_config(void); static void usage(int) __attribute__((__noreturn__)); int main(int argc, char **argv) { options *opt; char *host_port; setprogname(argv[0]); log_set(LOG_LEVEL_WARNING, LOG_TARGET_STDERR); if (atexit(log_close) != 0 || atexit(forget_config)) die("Cannot register function to be called on exit"); if (!ev_default_loop(0)) die("Cannot initialize libev"); opt = get_options(argc, argv); cfg = conf_init(opt->conf_file != NULL ? opt->conf_file : DEFAULT_CONF_FILE); if (opt->port != NULL) conf_setstr(cfg, "port", opt->port); if (opt->server != NULL) conf_setstr(cfg, "server", opt->server); if (opt->delay != -1) conf_setint(cfg, "delay", opt->delay); if (opt->timeout != -1) conf_setint(cfg, "timeout", opt->timeout); log_set(opt->log_level, opt->log_target); debug("%s starting up", nsca_version()); if (conf_getint(cfg, "delay") != 0) delay_execution((unsigned int)conf_getint(cfg, "delay")); xasprintf(&host_port, "%s:%s", conf_getstr(cfg, "server"), conf_getstr(cfg, "port")); (void)client_start(host_port, conf_getstr(cfg, "tls_ciphers"), conf_getint(cfg, "timeout"), opt->raw_commands ? CLIENT_MODE_COMMAND : CLIENT_MODE_CHECK_RESULT, opt->delimiter, opt->separator); (void)ev_run(EV_DEFAULT_UC_ 0); free(host_port); free_options(opt); return exit_code; } static options * get_options(int argc, char **argv) { extern int optind; extern char *optarg; options *opt = xmalloc(sizeof(options)); int option; opt->conf_file = NULL; opt->port = NULL; opt->server = NULL; opt->delay = -1; opt->log_level = -1; opt->log_target = -1; opt->timeout = -1; opt->delimiter = '\t'; opt->separator = '\27'; opt->raw_commands = false; if (argc == 2) { if (strcmp(argv[1], "--help") == 0) usage(EXIT_SUCCESS); if (strcmp(argv[1], "--version") == 0) { (void)puts(nsca_version()); exit(EXIT_SUCCESS); } } while ((option = getopt(argc, argv, "Cc:D:d:e:H:ho:p:SstVv")) != -1) { int character; switch (option) { case 'C': opt->raw_commands = true; break; case 'c': if (opt->conf_file != NULL) free(opt->conf_file); opt->conf_file = xstrdup(optarg); break; case 'D': opt->delay = atoi(optarg); if (opt->delay < 0) die("-D argument must be a positive integer"); break; case 'd': if ((character = parse_backslash_escape(optarg)) == EOF) die("-d argument must be a single character"); if (character == '\27' || character == '\n' || character == '\0' || character == '\\') die("Illegal delimiter specified with -d"); opt->delimiter = (char)character; break; case 'e': if ((character = parse_backslash_escape(optarg)) == EOF) die("-e argument must be a single character"); opt->separator = (char)character; break; case 'H': if (opt->server != NULL) free(opt->server); opt->server = xstrdup(optarg); break; case 'h': usage(EXIT_SUCCESS); case 'o': opt->timeout = atoi(optarg); if (opt->timeout < 0) die("-o argument must be a positive integer"); break; case 'p': if (opt->port != NULL) free(opt->port); opt->port = xstrdup(optarg); break; case 'S': opt->log_target = opt->log_target != -1 ? LOG_TARGET_STDERR | opt->log_target : LOG_TARGET_STDERR; break; case 's': opt->log_target = opt->log_target != -1 ? LOG_TARGET_SYSLOG | opt->log_target : LOG_TARGET_SYSLOG; break; case 't': notice("Ignoring -t option for backward compatibility"); break; case 'V': (void)puts(nsca_version()); exit(EXIT_SUCCESS); case 'v': if (opt->log_level == -1) opt->log_level = LOG_LEVEL_NOTICE; else if (opt->log_level < LOG_LEVEL_DEBUG) opt->log_level++; break; default: usage(EXIT_FAILURE); } } if (opt->delimiter == opt->separator) die("Field delimiter must be different from record separator"); if (argc - optind > 0) die("Unexpected non-option argument: %s", argv[optind]); return opt; } static void free_options(options *opt) { if (opt->conf_file != NULL) free(opt->conf_file); if (opt->port != NULL) free(opt->port); if (opt->server != NULL) free(opt->server); free(opt); } static int parse_backslash_escape(const char *sequence) { char numeric[6]; /* Space for "0x345". */ switch (strlen(sequence)) { case 1: return (unsigned char)sequence[0]; case 2: if (sequence[0] == '\\') switch (sequence[1]) { case 'a': return '\a'; case 'b': return '\b'; case 'f': return '\f'; case 'n': return '\n'; case 'r': return '\r'; case 't': return '\t'; case 'v': return '\v'; case 'x': /* Fall through. */ case '0': break; } /* Otherwise, fall through. */ case 3: /* Fall through. */ case 4: /* Fall through. */ case 5: /* * We support octal numbers with a leading zero and hexadecimal * numbers prefixed with "0x" in addition to numeric backslash * escape sequences. */ if (sequence[0] == '0' || sequence[0] == '\\') { char *end; long value; (void)strcpy(numeric, sequence); if (numeric[0] == '\\') /* \x42 -> 0x42 */ numeric[0] = '0'; value = strtol(numeric, &end, 0); if (*end == '\0' && value >= 0 && value <= CHAR_MAX) return (unsigned char)value; /* Otherwise, fall through. */ } /* Otherwise, fall through. */ default: return EOF; } } static void delay_execution(unsigned int max_delay) { #if HAVE_NANOSLEEP struct timespec delay; delay.tv_sec = (time_t)random_number(max_delay); delay.tv_nsec = (long)random_number(1000000000U); debug("Sleeping %ld seconds and %ld nanoseconds", (long)delay.tv_sec, delay.tv_nsec); (void)nanosleep(&delay, NULL); #else unsigned int delay = random_number(max_delay + 1); debug("Sleeping %u seconds", delay); (void)sleep(delay); #endif } static unsigned long random_number(unsigned long range) { unsigned long random_value; (void)RAND_pseudo_bytes((unsigned char *)&random_value, sizeof(random_value)); /* See http://c-faq.com/lib/randrange.html for some caveats. */ return random_value % range; } static void forget_config(void) { if (cfg != NULL) { char *password = conf_getstr(cfg, "password"); if (password != NULL) (void)memset(password, 0, strlen(password)); conf_free(cfg); } } static void usage(int status) { (void)fprintf(status == EXIT_SUCCESS ? stdout : stderr, "Usage: %s []\n\n" "Options:\n" " -C Accept `raw' monitoring commands.\n" " -c Use the specified configuration .\n" " -D Sleep up to seconds on startup.\n" " -d Expect to separate input fields.\n" " -e Expect to separate check results.\n" " -H Connect and talk to the specified .\n" " -h Print this usage information and exit.\n" " -o Use the specified connection .\n" " -p Connect to the specified on the server.\n" " -S Write messages to the standard error output.\n" " -s Write messages to syslog.\n" " -t Ignore this option for backward compatibility.\n" " -V Print version information and exit.\n" " -v [-v [-v]] Increase the verbosity level.\n", getprogname()); exit(status); } /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/src/client/send_nsca.h000066400000000000000000000031661344421036200170660ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef SEND_NSCA_H # define SEND_NSCA_H # if HAVE_CONFIG_H # include # endif # include "conf.h" # include "system.h" extern conf *cfg; extern int exit_code; #endif /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/src/common/000077500000000000000000000000001344421036200147645ustar00rootroot00000000000000nsca-ng-1.6/src/common/Makefile.am000066400000000000000000000043011344421036200170160ustar00rootroot00000000000000## Process this file with automake(1) to produce Makefile.in. ## Copyright (c) 2013 Holger Weiss ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1. Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## ## 2. Redistributions in binary form must reproduce the above copyright notice, ## this list of conditions and the following disclaimer in the documentation ## and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE ## LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ## CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF ## SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ## INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ## CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ## ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ## POSSIBILITY OF SUCH DAMAGE. GIT_DESCRIBE = git describe --tags --match 'v[0-9]*' --dirty 2>/dev/null NSCA_VERSION = `($(GIT_DESCRIBE) || echo $(PACKAGE_VERSION)) | sed 's/^v//'` AM_CPPFLAGS = \ -DNSCA_VERSION=\"$(NSCA_VERSION)\" \ -I$(top_srcdir)/lib \ $(EVCPPFLAGS) \ $(SSLCPPFLAGS) AM_LDFLAGS = \ $(EVLDFLAGS) \ $(SSLLDFLAGS) LDADD = \ ../../lib/libcompat.a \ $(EVLIBS) \ $(SSLLIBS) if USE_EMBEDDED_EV AM_CPPFLAGS += -I$(top_srcdir)/lib/ev LDADD += ../../lib/ev/libev.a endif noinst_LIBRARIES = libcommon.a libcommon_a_SOURCES = buffer.c buffer.h log.c log.h tls.c tls.h util.c util.h nsca-ng-1.6/src/common/buffer.c000066400000000000000000000150071344421036200164040ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #if HAVE_CONFIG_H # include #endif #include #include #include #include "buffer.h" #include "log.h" #include "system.h" #include "wrappers.h" #define BUFFER_BLOCK_SIZE 128 /* * If the block_detach() function is used, `data' must be the first member of * the `block' struct, so that it can be free(3)d. */ typedef struct block_s { unsigned char data[BUFFER_BLOCK_SIZE]; struct block_s *next; } block; struct buffer_s { block *first; block *last; size_t start_offset; size_t end_offset; size_t size; }; static size_t buffer_find_char(buffer *, char); static void block_add(buffer *); static void block_remove(buffer *); static void *block_detach(buffer *, size_t); /* * Exported functions. */ buffer * buffer_new(void) { buffer *new = xmalloc(sizeof(buffer)); debug("Creating buffer (address: %p)", (void *)new); new->first = NULL; new->last = NULL; new->start_offset = 0; new->end_offset = 0; new->size = 0; return new; } void buffer_append(buffer * restrict buf, const void * restrict input, size_t size) { const unsigned char *in = input; size_t n, n_todo; debug("Writing %zu bytes to buffer (address: %p)", size, (void *)buf); for (n_todo = size; n_todo > 0; n_todo -= n, in += n) { size_t available = buf->last == NULL ? 0 : BUFFER_BLOCK_SIZE - buf->end_offset; if (available == 0) { block_add(buf); buf->end_offset = 0; available = BUFFER_BLOCK_SIZE; } n = MIN(n_todo, available); (void)memcpy(buf->last->data + buf->end_offset, in, n); buf->end_offset += n; } buf->size += size; } size_t buffer_read(buffer * restrict buf, void * restrict output, size_t size) { unsigned char *out = output; size_t n_total = MIN(size, buf->size); size_t n_todo, n; debug("Reading %zu bytes from buffer (address: %p)", size, (void *)buf); for (n_todo = n_total; n_todo > 0; n_todo -= n, out += n) { assert(buf->first != NULL); n = MIN(n_todo, BUFFER_BLOCK_SIZE - buf->start_offset); (void)memcpy(out, buf->first->data + buf->start_offset, n); buf->start_offset += n; if (buf->start_offset == BUFFER_BLOCK_SIZE) { block_remove(buf); buf->start_offset = 0; } } buf->size -= n_total; /* * Removing the remaining block of an empty buffer increases the * likelihood that buffer_detach() will succeed if the buffer is reused. */ if (buf->size == 0 && buf->first != NULL) { block_remove(buf); buf->start_offset = 0; } return n_total; } void * buffer_read_alloc(buffer * restrict buf, size_t * restrict size) { void *data; if ((data = block_detach(buf, *size)) == NULL) { data = xmalloc(*size); *size = buffer_read(buf, data, *size); } return data; } char * buffer_read_line(buffer *buf) { char *line; size_t size; if ((size = buffer_find_char(buf, '\n')) == 0) return NULL; line = buffer_read_alloc(buf, &size); if (size >= 2 && line[size - 2] == '\r') line[size - 2] = '\0'; else line[size - 1] = '\0'; return line; } char * buffer_read_chunk(buffer *buf, char terminator) { char *chunk; size_t size; if ((size = buffer_find_char(buf, terminator)) == 0) return NULL; chunk = buffer_read_alloc(buf, &size); chunk[size - 1] = '\0'; return chunk; } void * buffer_slurp(buffer * restrict buf, size_t * restrict size) { *size = buf->size; return buffer_read_alloc(buf, size); } size_t buffer_size(buffer *buf) { return buf->size; } void buffer_free(buffer *buf) { block *blk = buf->first; debug("Destroying buffer (address: %p)", (void *)buf); while (blk != NULL) { block *next = blk->next; free(blk); blk = next; } free(buf); } /* * Static functions. */ static size_t buffer_find_char(buffer *buf, char character) { block *b; size_t pos = 1; for (b = buf->first; b != NULL; b = b->next) { size_t i = b == buf->first ? buf->start_offset : 0; size_t end_offset = b == buf->last ? buf->end_offset : BUFFER_BLOCK_SIZE; while (i < end_offset) { if ((char)b->data[i] == character) return pos; i++, pos++; } } return 0; } static void block_add(buffer *buf) { block *blk = xmalloc(sizeof(block)); debug("Adding buffer block (buffer: %p, block: %p)", (void *)buf, (void *)blk); if (buf->first == NULL) buf->first = blk; else { /* The buffer isn't empty. */ assert(buf->last != NULL); buf->last->next = blk; } buf->last = blk; buf->last->next = NULL; } static void block_remove(buffer *buf) { block *blk = buf->first; debug("Removing buffer block (buffer: %p, block: %p)", (void *)buf, (void *)blk); assert(blk != NULL); buf->first = blk->next; free(blk); if (buf->first == NULL) buf->last = NULL; } static void * block_detach(buffer *buf, size_t size) { block *blk = buf->first; if (blk != NULL && buf->first == buf->last && buf->start_offset == 0 && buf->size == size) { debug("Detaching buffer block (buffer: %p, block: %p)", (void *)buf, (void *)blk); buf->first = NULL; buf->last = NULL; buf->start_offset = 0; buf->end_offset = 0; buf->size = 0; return blk->data; } else { debug("Cannot detach buffer block (buffer: %p, block: %p)", (void *)buf, (void *)blk); return NULL; } } /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/src/common/buffer.h000066400000000000000000000040331344421036200164060ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef BUFFER_H # define BUFFER_H # if HAVE_CONFIG_H # include # endif # include /* For size_t. */ # include "system.h" typedef struct buffer_s buffer; buffer *buffer_new(void); void buffer_append(buffer * restrict, const void * restrict, size_t); size_t buffer_read(buffer * restrict, void * restrict, size_t); void *buffer_read_alloc(buffer * restrict, size_t * restrict); char *buffer_read_line(buffer *); char *buffer_read_chunk(buffer *, char); void *buffer_slurp(buffer * restrict, size_t * restrict); size_t buffer_size(buffer *); void buffer_free(buffer *); #endif /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/src/common/log.c000066400000000000000000000103751344421036200157170ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #if HAVE_CONFIG_H # include #endif #include #include #include #include #include #include #include "log.h" #include "system.h" #include "wrappers.h" #ifndef LOG_BUFFER_SIZE # define LOG_BUFFER_SIZE 768 #endif int log_level = LOG_LEVEL_INFO; static int log_target = LOG_TARGET_STDERR; static bool log_opened = false; static inline const char *level_to_string(int); /* * Exported functions. */ void log_set(int level, int flags) { if (level != -1) log_level = level; if (flags != -1) { log_target = flags; if (flags & LOG_TARGET_SYSLOG && !log_opened) { openlog(getprogname(), LOG_PID, LOG_DAEMON); log_opened = true; } } } void vlog(int level, const char *in_fmt, va_list ap) { size_t in_pos, out_pos; char message[LOG_BUFFER_SIZE], out_fmt[512]; enum { STATE_NORMAL, STATE_PERCENT } state = STATE_NORMAL; /* * This loop handles `%m'. * * Why do we check for "out_pos < sizeof(out_fmt) - 2"? We need one * extra character when dealing with input such as `%s' (as we write * both of these characters in one iteration), and another one for * nul-termination. */ for (in_pos = out_pos = 0; in_fmt[in_pos] != '\0' && out_pos < sizeof(out_fmt) - 2; in_pos++) switch (in_fmt[in_pos]) { case '%': if (state == STATE_PERCENT) { out_fmt[out_pos++] = '%'; state = STATE_NORMAL; } else state = STATE_PERCENT; break; case 'm': if (state == STATE_PERCENT) { const char *err_str = strerror(errno); size_t err_pos; for (err_pos = 0; err_str[err_pos] != '\0' && out_pos < sizeof(out_fmt) - 1; err_pos++) out_fmt[out_pos++] = err_str[err_pos]; state = STATE_NORMAL; break; } /* Otherwise, fall through. */ default: if (state == STATE_PERCENT) out_fmt[out_pos++] = '%'; out_fmt[out_pos++] = in_fmt[in_pos]; state = STATE_NORMAL; } out_fmt[out_pos] = '\0'; if (vsnprintf(message, sizeof(message), out_fmt, ap) > (int)sizeof(message) - 1) (void)memcpy(message + sizeof(message) - 7, " [...]", 7); if (log_target & LOG_TARGET_SYSTEMD) { (void)fprintf(stderr, "<%d>%s\n", level, message); (void)fflush(stderr); } if (log_target & LOG_TARGET_STDERR) { (void)fprintf(stderr, "%s: [%s] %s\n", getprogname(), level_to_string(level), message); (void)fflush(stderr); } if (log_target & LOG_TARGET_SYSLOG) syslog(level, "[%s] %s", level_to_string(level), message); } void log_close(void) { closelog(); } /* * Static functions. */ static inline const char * level_to_string(int level) { switch (level) { case LOG_CRIT: return "FATAL"; case LOG_ERR: return "ERROR"; case LOG_WARNING: return "WARNING"; case LOG_NOTICE: return "NOTICE"; case LOG_INFO: return "INFO"; case LOG_DEBUG: return "DEBUG"; default: return "UNKNOWN"; } } /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/src/common/log.h000066400000000000000000000066631344421036200157310ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef SESSION_H # define SESSION_H # if HAVE_CONFIG_H # include # endif # include # include # include # include "system.h" # define LOG_TARGET_SYSLOG 0x1 # define LOG_TARGET_STDERR 0x2 # define LOG_TARGET_SYSTEMD 0x4 enum { LOG_LEVEL_CRITICAL, LOG_LEVEL_ERROR, LOG_LEVEL_WARNING, LOG_LEVEL_NOTICE, LOG_LEVEL_INFO, LOG_LEVEL_DEBUG }; extern int log_level; void log_set(int, int); void vlog(int, const char *, va_list); void log_close(void); static inline void __attribute__((__format__(__printf__, 1, 2))) debug(const char *format, ...) { if (log_level >= LOG_LEVEL_DEBUG) { va_list ap; va_start(ap, format); vlog(LOG_DEBUG, format, ap); va_end(ap); } } static inline void __attribute__((__format__(__printf__, 1, 2))) info(const char *format, ...) { if (log_level >= LOG_LEVEL_INFO) { va_list ap; va_start(ap, format); vlog(LOG_INFO, format, ap); va_end(ap); } } static inline void __attribute__((__format__(__printf__, 1, 2))) notice(const char *format, ...) { if (log_level >= LOG_LEVEL_NOTICE) { va_list ap; va_start(ap, format); vlog(LOG_NOTICE, format, ap); va_end(ap); } } static inline void __attribute__((__format__(__printf__, 1, 2))) warning(const char *format, ...) { if (log_level >= LOG_LEVEL_WARNING) { va_list ap; va_start(ap, format); vlog(LOG_WARNING, format, ap); va_end(ap); } } static inline void __attribute__((__format__(__printf__, 1, 2))) error(const char *format, ...) { if (log_level >= LOG_LEVEL_ERROR) { va_list ap; va_start(ap, format); vlog(LOG_ERR, format, ap); va_end(ap); } } static inline void __attribute__((__format__(__printf__, 1, 2))) critical(const char *format, ...) { va_list ap; va_start(ap, format); vlog(LOG_CRIT, format, ap); va_end(ap); } static inline void __attribute__((__format__(__printf__, 1, 2), __noreturn__)) die(const char *format, ...) { va_list ap; va_start(ap, format); vlog(LOG_CRIT, format, ap); va_end(ap); exit(EXIT_FAILURE); } #endif /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/src/common/tls.c000066400000000000000000000676361344421036200157540ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * This is an implementation of a single-threaded event-based TLS client and * server which supports both synchronous and asynchronous protocols. * * Coping with OpenSSL's retry semantics is a bit hairy when operating with * non-blocking sockets: * * - When calling SSL_read(), we cannot simply replace our `tls->input_buffer' * with a buffer on the stack, as this would break the following requirement * (documented in the SSL_read() man page): "When an SSL_read() operation has * to be repeated because of SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE, it * must be repeated with the same arguments." In the following thread, David * Schwartz says that one could get around this requirement by setting some * (seemingly unrelated) OpenSSL options: * * http://thread.gmane.org/gmane.comp.encryption.openssl.devel/12242 * * However, even if this were true for the current OpenSSL code, we'll rather * not rely on the behaviour until the documentation is updated. * * - We set the SSL_MODE_ENABLE_PARTIAL_WRITE option because SSL_write() splits * up the data into 16 kB chunks, so sending larger pieces of data would * result in multiple trips around the event loop, as the first SSL_write() * attempt(s) would always be rejected with SSL_ERROR_WANT_WRITE. * * - An application must not wait for I/O readiness of the underlying socket * unless an OpenSSL call explicitly returned SSL_ERROR_WANT_READ or * SSL_ERROR_WANT_WRITE. Therefore, we kick off new SSL I/O requests via * ev_feed_event() instead of having libev wait for actual socket readiness * before calling the OpenSSL functions. * * - As an SSL_read() call invalidates the current state of the SSL_write() * stream and vice versa (i.e., there's only a single state of an SSL * connection), such a call has to be followed by a check whether the `ev_io' * watcher for the opposite I/O direction is currently active. If so, we use * ev_feed_event() to feed the event that watcher is waiting for into the * event loop (we check the `events' member of the `ev_io' struct to find out * whether it's EV_READ or EV_WRITE). This forces an SSL_read()/SSL_write() * call, which updates the state of that stream. * * For additional explanations, see the relevant OpenSSL man pages and the * following thread: * * http://thread.gmane.org/gmane.comp.encryption.openssl.devel/15766 * * An alternative approach would be to use a BIO_s_mem() layer instead of * letting OpenSSL handle the socket I/O itself. This is what the Perl module * AnyEvent::Handle does, as explained here: * * http://lists.schmorp.de/pipermail/libev/2008q2/000325.html * http://funcptr.net/2012/04/08/openssl-as-a-filter-(or-non-blocking-openssl)/ */ #if HAVE_CONFIG_H # include #endif #include #if HAVE_SYS_SOCKET_H # include #endif #ifdef HAVE_NETINET_IN_H # include #endif #if HAVE_ARPA_INET_H # include #endif #include #include #include #include #include #include #include #include #include #include #include "log.h" #include "system.h" #include "tls.h" #include "wrappers.h" #if !HAVE_STRUCT_SOCKADDR_STORAGE # if HAVE_STRUCT_SOCKADDR_IN6 # define sockaddr_storage sockaddr_in6 # else # define sockaddr_storage sockaddr_in # endif #endif #ifndef INET6_ADDRSTRLEN # define INET6_ADDRSTRLEN 46 #endif #define LINE_MAX_SIZE 2048 #define LINE_BUFFER_SIZE 128 #define LINE_TERMINATOR "\r\n" enum { READ_LINE, /* The read() function relies on READ_LINE == 0. */ READ_BYTES }; enum { TLS_CLIENT, TLS_SERVER }; static void (*warning_f)(const char *, ...); static void (*error_f)(const char *, ...); static SSL_CTX *initialize_openssl(const SSL_METHOD *, const char *); static tls_state *tls_new(int, int); static void tls_free(tls_state *); static void connect_cb(EV_P_ ev_io *, int); static void accept_tcp_cb(EV_P_ ev_io *, int); static void accept_ssl_cb(EV_P_ ev_io *, int); static void read_cb(EV_P_ ev_io *, int); static void write_cb(EV_P_ ev_io *, int); static void shutdown_cb(EV_P_ ev_io *, int); static void timeout_cb(EV_P_ ev_timer *, int); static void default_timeout_handler(tls_state *); static void default_line_too_long_handler(tls_state *); static void start_shutdown(tls_state *); static char *read_line(tls_state *); static char *read_bytes(tls_state *); static void write_buffered(tls_state * restrict, const void * restrict, size_t); static void reset_watcher_state(EV_P_ ev_io *); static void check_tls_error(EV_P_ ev_io *, int); static void log_tls_message(void (*)(const char *, ...), const char *, ...); static bool get_peer_address(int, char *, socklen_t); /* * Exported functions. */ tls_client_state * tls_client_start(const char *ciphers) { tls_client_state *ctx = xmalloc(sizeof(tls_client_state)); debug("Starting TLS client"); ctx->ssl = initialize_openssl(SSLv23_client_method(), ciphers); return ctx; } tls_server_state * tls_server_start(const char * restrict host_port, const char * restrict ciphers, ev_tstamp timeout, void handle_connect(tls_state *), unsigned int check_psk(SSL *, const char *, unsigned char *, unsigned int)) { tls_server_state *ctx = xmalloc(sizeof(tls_server_state)); int listen_socket; debug("Starting TLS server"); ctx->ssl = initialize_openssl(SSLv23_server_method(), ciphers); SSL_CTX_set_psk_server_callback(ctx->ssl, check_psk); if (sscanf(host_port, "descriptor=%d", &listen_socket) != 1) listen_socket = -1; if (listen_socket == -1) { if ((ctx->bio = BIO_new_accept((char *)host_port)) == NULL) die("Cannot create socket: %m"); (void)BIO_set_bind_mode(ctx->bio, BIO_BIND_REUSEADDR); } else { if ((ctx->bio = BIO_new(BIO_s_accept())) == NULL) die("Cannot create BIO object"); (void)BIO_set_fd(ctx->bio, listen_socket, BIO_NOCLOSE); } /* * We call BIO_set_nbio() in addition to BIO_set_nbio_accept() in order * to set non-blocking I/O mode also for the *accepted* sockets, not * only for the listening socket: * * http://permalink.gmane.org/gmane.comp.encryption.openssl.user/27438 */ (void)BIO_set_nbio_accept(ctx->bio, 1); (void)BIO_set_nbio(ctx->bio, 1); /* For the *accepted* sockets. */ if (listen_socket == -1) { if (BIO_do_accept(ctx->bio) <= 0) log_tls_message(die, "Cannot bind to %s", host_port); debug("Listening on %s", host_port); } else debug("Listening on file descriptor %d", listen_socket); ctx->connect_handler = handle_connect; ctx->timeout = timeout; ctx->accept_watcher.data = ctx; ev_io_init(&ctx->accept_watcher, accept_tcp_cb, (int)BIO_get_fd(ctx->bio, NULL), EV_READ); ev_io_start(EV_DEFAULT_UC_ &ctx->accept_watcher); return ctx; } void tls_connect(tls_client_state *ctx, const char * restrict server, ev_tstamp timeout, int flags, void handle_connect(tls_state *), void handle_timeout(tls_state *), unsigned int set_psk(SSL *, const char *, char *, unsigned int, unsigned char *, unsigned int)) { tls_state *tls = tls_new(TLS_CLIENT, flags); char *colon; tls->data = ctx->data; tls->connect_handler = handle_connect; tls->timeout = timeout; tls->peer = xstrdup(server); if ((colon = strrchr(tls->peer, ':')) != NULL) *colon = '\0'; /* Strip off the port. */ tls_on_timeout(tls, handle_timeout); if ((tls->bio = BIO_new_connect((char *)server)) == NULL) log_tls_message(die, "Cannot create BIO object"); (void)BIO_set_nbio(tls->bio, 1); if ((tls->ssl = SSL_new(ctx->ssl)) == NULL) log_tls_message(die, "Cannot create SSL object"); SSL_set_bio(tls->ssl, tls->bio, tls->bio); SSL_set_psk_client_callback(tls->ssl, set_psk); ev_invoke(EV_DEFAULT_UC_ &tls->init_watcher, EV_CUSTOM); } void tls_read(tls_state *tls, void handle_read(tls_state *, char *), size_t size) { if (ev_is_active(&tls->read_watcher)) die("Internal error: Concurrent read requests issued"); if (size == READ_LINE) { tls->read_mode = READ_LINE; tls->input_size = LINE_BUFFER_SIZE; debug("Waiting for a line from %s", tls->peer); } else { tls->read_mode = READ_BYTES; tls->input_size = size; debug("Waiting for %zu byte(s) from %s", size, tls->peer); } tls->read_handler = handle_read; ev_io_set(&tls->read_watcher, tls->fd, EV_READ); ev_io_start(EV_DEFAULT_UC_ &tls->read_watcher); ev_feed_event(EV_DEFAULT_UC_ &tls->read_watcher, EV_READ); } void tls_read_line(tls_state *tls, void handle_read_line(tls_state *, char *)) { tls_read(tls, handle_read_line, READ_LINE); } void tls_write(tls_state * restrict tls, void * restrict data, size_t size, void free_data(void *)) { if (tls->output == NULL && buffer_size(tls->output_buffer) == 0 && free_data != NULL) { debug("Zero-copying %zu byte(s) for %s", size, tls->peer); tls->output = data; tls->output_size = size; tls->free_output = free_data; if (!ev_is_active(&tls->write_watcher)) { ev_io_set(&tls->write_watcher, tls->fd, EV_WRITE); ev_io_start(EV_DEFAULT_UC_ &tls->write_watcher); ev_feed_event(EV_DEFAULT_UC_ &tls->write_watcher, EV_WRITE); } } else { write_buffered(tls, data, size); if (free_data != NULL) free_data(data); } } void tls_write_line(tls_state * restrict tls, const char * restrict string) { write_buffered(tls, string, strlen(string)); write_buffered(tls, LINE_TERMINATOR, sizeof(LINE_TERMINATOR) - 1); } void tls_shutdown(tls_state *tls) { /* * Make sure this function won't be called recursively if an error or * timeout occurs during the TLS shutdown. */ tls->error_handler = NULL; tls->timeout_handler = default_timeout_handler; tls_on_drain(tls, start_shutdown); } void tls_client_stop(tls_client_state *ctx) { debug("Stopping TLS client"); SSL_CTX_free(ctx->ssl); free(ctx); } void tls_server_stop(tls_server_state *ctx) { debug("Stopping TLS server"); SSL_CTX_free(ctx->ssl); BIO_free_all(ctx->bio); free(ctx); } void tls_set_connection_id(tls_state *tls, const char *id) { char *peer; xasprintf(&peer, "%s (ID: %s)", tls->peer, id); free(tls->peer); tls->peer = peer; } void tls_on_drain(tls_state *tls, void handle_drain(tls_state *)) { tls->drain_handler = handle_drain; if (!ev_is_active(&tls->write_watcher)) tls->drain_handler(tls); } void tls_on_error(tls_state *tls, void handle_error(tls_state *)) { tls->error_handler = handle_error; } void tls_on_timeout(tls_state *tls, void handle_timeout(tls_state *)) { if (ev_is_active(&tls->timeout_watcher)) ev_timer_stop(EV_DEFAULT_UC_ &tls->timeout_watcher); tls->timeout_handler = handle_timeout != NULL ? handle_timeout : default_timeout_handler; if (tls->timeout > 0.0) { ev_timer_set(&tls->timeout_watcher, tls->timeout, 0.0); ev_timer_start(EV_DEFAULT_UC_ &tls->timeout_watcher); tls->last_activity = ev_now(EV_DEFAULT_UC); } } void tls_on_line_too_long(tls_state *tls, void handle_line_too_long(tls_state *)) { tls->line_too_long_handler = handle_line_too_long; } /* * Static functions. */ static SSL_CTX * initialize_openssl(const SSL_METHOD *method, const char *ciphers) { SSL_CTX *ssl_ctx; #if OPENSSL_VERSION_NUMBER < 0x10100000L (void)SSL_library_init(); SSL_load_error_strings(); (void)atexit(ERR_free_strings); #endif /* * In earlier versions, we called * * OPENSSL_config(NULL); * (void)atexit(CONF_modules_free); * * at this point. The OPENSSL_config(3) man page claims that this * function "ignores all errors", but that's not true: at least OpenSSL * 1.0.1e exit(3)s in OPENSSL_config(3) on certain error conditions. */ if ((ssl_ctx = SSL_CTX_new(method)) == NULL) die("Cannot create SSL context"); if (SSL_CTX_set_cipher_list(ssl_ctx, ciphers) != 1) die("Cannot set SSL cipher(s)"); (void)SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3); (void)SSL_CTX_set_mode(ssl_ctx, SSL_MODE_ENABLE_PARTIAL_WRITE); (void)signal(SIGPIPE, SIG_IGN); return ssl_ctx; } static tls_state * tls_new(int type, int flags) { tls_state *tls = xmalloc(sizeof(tls_state)); debug("Initializing connection context"); tls->data = NULL; tls->id = NULL; tls->addr = NULL; tls->peer = NULL; tls->init_watcher.data = tls; tls->read_watcher.data = tls; tls->write_watcher.data = tls; tls->shutdown_watcher.data = tls; tls->timeout_watcher.data = tls; tls->timeout = 0.0; tls->last_activity = ev_now(EV_DEFAULT_UC); tls->input_buffer = buffer_new(); tls->output_buffer = buffer_new(); tls->input = NULL; tls->output = NULL; tls->input_size = 0; tls->input_offset = 0; tls->output_size = 0; tls->output_offset = 0; tls->connect_handler = NULL; tls->read_handler = NULL; tls->drain_handler = NULL; tls->error_handler = NULL; tls->timeout_handler = default_timeout_handler; tls->line_too_long_handler = default_line_too_long_handler; tls->free_output = free; tls->ssl = NULL; tls->bio = NULL; tls->fd = -1; tls->read_mode = 0; if (flags & TLS_AUTO_DIE) { warning_f = die; error_f = die; } else { warning_f = warning; error_f = error; } ev_init(&tls->init_watcher, type == TLS_CLIENT ? connect_cb : accept_ssl_cb); ev_init(&tls->read_watcher, read_cb); ev_init(&tls->write_watcher, write_cb); ev_init(&tls->shutdown_watcher, shutdown_cb); ev_init(&tls->timeout_watcher, timeout_cb); /* Check for data before checking for timeout. */ ev_set_priority(&tls->timeout_watcher, -1); return tls; } static void tls_free(tls_state *tls) { debug("Destroying connection context"); if (ev_is_active(&tls->init_watcher)) ev_io_stop(EV_DEFAULT_UC_ &tls->init_watcher); if (ev_is_active(&tls->read_watcher)) ev_io_stop(EV_DEFAULT_UC_ &tls->read_watcher); if (ev_is_active(&tls->write_watcher)) ev_io_stop(EV_DEFAULT_UC_ &tls->write_watcher); if (ev_is_active(&tls->shutdown_watcher)) ev_io_stop(EV_DEFAULT_UC_ &tls->shutdown_watcher); if (ev_is_active(&tls->timeout_watcher)) ev_timer_stop(EV_DEFAULT_UC_ &tls->timeout_watcher); buffer_free(tls->input_buffer); buffer_free(tls->output_buffer); if (tls->input != NULL) free(tls->input); if (tls->output != NULL) free(tls->output); if (tls->addr != NULL) free(tls->addr); if (tls->id != NULL) free(tls->id); if (tls->peer != NULL) free(tls->peer); if (tls->ssl != NULL) SSL_free(tls->ssl); free(tls); } static void connect_cb(EV_P_ ev_io *w, int revents) { tls_state *tls = w->data; int result; tls->last_activity = ev_now(EV_A); result = SSL_connect(tls->ssl); /* * Initially, connect_cb() is called by ev_invoke() from tls_connect() * with `revents' set to EV_CUSTOM. The above SSL_connect() call then * creates the socket descriptor (`tls->fd') we can watch. */ if (revents & EV_CUSTOM && (tls->fd = (int)BIO_get_fd(tls->bio, NULL)) == -1) log_tls_message(die, "Cannot create socket"); if (result <= 0) { debug("TLS connection not (yet) established"); if (revents & EV_CUSTOM) { ev_io_set(w, tls->fd, EV_WRITE); ev_io_start(EV_A_ &tls->init_watcher); ev_feed_event(EV_A_ &tls->init_watcher, EV_WRITE); } check_tls_error(EV_A_ w, result); } else { debug("TLS connection established"); if (!(revents & EV_CUSTOM)) ev_io_stop(EV_A_ w); tls->connect_handler(tls); } } static void accept_tcp_cb(EV_P_ ev_io *w, int revents __attribute__((__unused__))) { tls_server_state *ctx = w->data; while (1) { /* Accept all available TCP connections. */ tls_state *tls; if (BIO_do_accept(ctx->bio) <= 0) { if (BIO_should_retry(ctx->bio)) debug("Cannot accept connection right now"); else log_tls_message(warning, "Cannot accept connection"); return; /* Let's do something else. */ } tls = tls_new(TLS_SERVER, TLS_NO_AUTO_DIE); tls->bio = BIO_pop(ctx->bio); tls->fd = (int)BIO_get_fd(tls->bio, NULL); tls->addr = xmalloc(INET6_ADDRSTRLEN); tls->connect_handler = ctx->connect_handler; tls->timeout = ctx->timeout; tls->data = ctx->data; if (!get_peer_address(tls->fd, tls->addr, INET6_ADDRSTRLEN)) { tls_free(tls); return; /* Let's do something else. */ } tls_on_timeout(tls, default_timeout_handler); if ((tls->ssl = SSL_new(ctx->ssl)) == NULL) { log_tls_message(error, "Cannot create SSL object for %s", tls->addr); tls_free(tls); return; /* Let's do something else. */ } SSL_set_bio(tls->ssl, tls->bio, tls->bio); ev_io_set(&tls->init_watcher, tls->fd, EV_READ); ev_io_start(EV_A_ &tls->init_watcher); ev_feed_event(EV_A_ &tls->init_watcher, EV_READ); debug("Accepted connection from %s", tls->addr); } } static void accept_ssl_cb(EV_P_ ev_io *w, int revents __attribute__((__unused__))) { tls_state *tls = w->data; int result; tls->last_activity = ev_now(EV_A); if ((result = SSL_accept(tls->ssl)) <= 0) { debug("TLS handshake with %s not (yet) successful", tls->addr); check_tls_error(EV_A_ w, result); } else { /* The TLS connection is established. */ if ((tls->id = SSL_get_app_data(tls->ssl)) == NULL) { error("Cannot retrieve client identity"); tls_free(tls); } else { xasprintf(&tls->peer, "%s@%s", tls->id, tls->addr); debug("TLS handshake with %s successful", tls->peer); ev_io_stop(EV_A_ w); tls->connect_handler(tls); } } } static void read_cb(EV_P_ ev_io *w, int revents __attribute__((__unused__))) { tls_state *tls = w->data; char *data; reset_watcher_state(EV_A_ &tls->write_watcher); tls->last_activity = ev_now(EV_A); data = tls->read_mode == READ_LINE ? read_line(tls) : read_bytes(tls); if (data != NULL) { ev_io_stop(EV_A_ w); tls->read_handler(tls, data); } } static void write_cb(EV_P_ ev_io *w, int revents __attribute__((__unused__))) { tls_state *tls = w->data; int n; reset_watcher_state(EV_A_ &tls->read_watcher); tls->last_activity = ev_now(EV_A); do { int n_todo; if (tls->output == NULL) { tls->output = buffer_slurp(tls->output_buffer, &tls->output_size); tls->free_output = free; } do { n_todo = (int)(tls->output_size - tls->output_offset); if ((n = SSL_write(tls->ssl, tls->output + tls->output_offset, n_todo)) <= 0) { debug("Sent 0 of %d bytes to %s", n_todo, tls->peer); check_tls_error(EV_A_ w, n); } else if (n < n_todo) { debug("Sent %d of %d bytes to %s", n, n_todo, tls->peer); tls->output_offset += (size_t)n; } else { /* We're done (n == n_todo). */ debug("Sent %d bytes to %s, as requested", n, tls->peer); tls->free_output(tls->output); tls->output = NULL; tls->output_size = 0; tls->output_offset = 0; if (buffer_size(tls->output_buffer) == 0) { ev_io_stop(EV_A_ w); if (tls->drain_handler != NULL) tls->drain_handler(tls); } } } while (n > 0 && n < n_todo); } while (n > 0 && buffer_size(tls->output_buffer) > 0); } static void shutdown_cb(EV_P_ ev_io *w, int revents __attribute__((__unused__))) { tls_state *tls = w->data; int result; tls->last_activity = ev_now(EV_A); do { switch (result = SSL_shutdown(tls->ssl)) { case 1: /* We sent and received peer's `close notify'. */ debug("TLS shutdown with %s successful", tls->peer); tls_free(tls); break; case 0: /* We sent `close notify', let's wait for the peer. */ debug("Sent TLS `close notify' alert to %s", tls->peer); break; default: /* We must wait for I/O, or an error occurred. */ debug("TLS shutdown with %s not (yet) successful", tls->peer); check_tls_error(EV_A_ w, result); } } while (result == 0); } static void timeout_cb(EV_P_ ev_timer *w, int revents __attribute__((__unused__))) { tls_state *tls = w->data; ev_tstamp diff = tls->last_activity + tls->timeout - ev_now(EV_A); if (diff > 0.0) { debug("Resetting timeout watcher for %s, %.2f seconds left", tls->peer, (double)diff); ev_timer_set(w, diff, 0.0); ev_timer_start(EV_A_ w); } else { warning_f("Connection to %s timed out", tls->peer != NULL ? tls->peer : tls->addr); if (ev_is_active(&tls->init_watcher)) ev_io_stop(EV_DEFAULT_UC_ &tls->init_watcher); if (ev_is_active(&tls->read_watcher)) ev_io_stop(EV_DEFAULT_UC_ &tls->read_watcher); if (ev_is_active(&tls->write_watcher)) ev_io_stop(EV_DEFAULT_UC_ &tls->write_watcher); if (ev_is_active(&tls->shutdown_watcher)) ev_io_stop(EV_DEFAULT_UC_ &tls->shutdown_watcher); ev_timer_set(w, tls->timeout, 0.0); ev_timer_start(EV_A_ w); tls->timeout_handler(tls); } } static void default_timeout_handler(tls_state *tls) { tls_free(tls); } static void default_line_too_long_handler(tls_state *tls) { tls_free(tls); } static void start_shutdown(tls_state *tls) { debug("Initiating shutdown of connection to %s", tls->peer); ev_io_set(&tls->shutdown_watcher, tls->fd, EV_WRITE); ev_io_start(EV_DEFAULT_UC_ &tls->shutdown_watcher); ev_feed_event(EV_DEFAULT_UC_ &tls->shutdown_watcher, EV_WRITE); } static char * read_line(tls_state *tls) { char *line = NULL; int n; if (tls->input == NULL) tls->input = xmalloc(tls->input_size); do { if ((line = buffer_read_line(tls->input_buffer)) != NULL) { debug("Received complete line from %s", tls->peer); free(tls->input); tls->input = NULL; tls->input_size = 0; break; } if (buffer_size(tls->input_buffer) + tls->input_size > LINE_MAX_SIZE) { warning_f("Line received from %s is too long", tls->peer); ev_io_stop(EV_DEFAULT_UC_ &tls->read_watcher); tls->line_too_long_handler(tls); break; } if ((n = SSL_read(tls->ssl, tls->input, (int)tls->input_size)) <= 0) { debug("Didn't receive line from %s (yet)", tls->peer); check_tls_error(EV_DEFAULT_UC_ &tls->read_watcher, n); } else { debug("Buffered %d bytes from %s", n, tls->peer); buffer_append(tls->input_buffer, tls->input, (size_t)n); } } while (n > 0); return line; } static char * read_bytes(tls_state *tls) { char *bytes = NULL; int n, n_todo; if (tls->input == NULL) tls->input = xmalloc(tls->input_size + 1); /* 1 for '\0'. */ do { n_todo = (int)(tls->input_size - tls->input_offset); if ((n = SSL_read(tls->ssl, tls->input + tls->input_offset, n_todo)) <= 0) { debug("Received 0 of %d bytes from %s", n_todo, tls->peer); check_tls_error(EV_DEFAULT_UC_ &tls->read_watcher, n); } else if (n < n_todo) { debug("Received %d of %d bytes from %s", n, n_todo, tls->peer); tls->input_offset += (size_t)n; } else { /* We're done (n == n_todo). */ debug("Received %d bytes from %s, as requested", n, tls->peer); tls->input[tls->input_size] = '\0'; bytes = (char *)tls->input; tls->input = NULL; tls->input_size = 0; tls->input_offset = 0; break; /* Make Clang's Static Analyzer happy. */ } } while (n > 0 && n < n_todo); return bytes; } static void write_buffered(tls_state * restrict tls, const void * restrict data, size_t size) { debug("Queueing %zu byte(s) for %s", size, tls->peer); buffer_append(tls->output_buffer, data, size); if (!ev_is_active(&tls->write_watcher)) { ev_io_set(&tls->write_watcher, tls->fd, EV_WRITE); ev_io_start(EV_DEFAULT_UC_ &tls->write_watcher); ev_feed_event(EV_DEFAULT_UC_ &tls->write_watcher, EV_WRITE); } } static void reset_watcher_state(EV_P_ ev_io *w) { tls_state *tls = w->data; if (ev_is_active(w)) { debug("Resetting %s watcher state for %s", w == &tls->read_watcher ? "input" : "output", tls->peer); ev_feed_event(EV_A_ w, w->events); } } static void check_tls_error(EV_P_ ev_io *w, int code) { tls_state *tls = w->data; const char *peer = tls->peer != NULL ? tls->peer : tls->addr; /* See the SSL_get_error() man page. */ switch (SSL_get_error(tls->ssl, code)) { case SSL_ERROR_WANT_ACCEPT: case SSL_ERROR_WANT_READ: if (!(w->events & EV_READ)) { ev_io_stop(EV_A_ w); ev_io_set(w, w->fd, EV_READ); ev_io_start(EV_A_ w); } debug("Waiting for input from %s", peer); return; case SSL_ERROR_WANT_CONNECT: case SSL_ERROR_WANT_WRITE: if (!(w->events & EV_WRITE)) { ev_io_stop(EV_A_ w); ev_io_set(w, w->fd, EV_WRITE); ev_io_start(EV_A_ w); } debug("Waiting for output to %s", peer); return; case SSL_ERROR_SYSCALL: if (ERR_peek_error() != 0) log_tls_message(warning_f, "TLS I/O error (%s)", peer); else if (code == 0) warning_f("%s aborted the TLS connection", peer); else if (code == -1) switch (errno) { case EINTR: debug("TLS I/O call has been interrupted"); return; case 0: /* * As far as I know, the only situation which * might trigger this is an EOF during TLS * shutdown. See: * * http://marc.info/?m=127100694709805 */ warning_f("%s aborted the TLS shutdown", peer); break; default: warning_f("Socket error (%s): %m", peer); } else error_f("TLS I/O error (%s)", peer); break; case SSL_ERROR_ZERO_RETURN: warning_f("%s closed the TLS connection", peer); (void)SSL_shutdown(tls->ssl); /* Try to send `close notify'. */ break; case SSL_ERROR_SSL: if (ERR_peek_error() != 0) log_tls_message(warning_f, "TLS error (%s)", peer); else error_f("TLS error (%s)", peer); break; case SSL_ERROR_NONE: /* Should never happen if code <= 0. */ case SSL_ERROR_WANT_X509_LOOKUP: default: error_f("Unknown OpenSSL error (%s)", peer); } if (tls->error_handler != NULL) tls->error_handler(tls); tls_free(tls); } static void log_tls_message(void log(const char *, ...), const char *format, ...) { unsigned long e; va_list ap; char *message; va_start(ap, format); xvasprintf(&message, format, ap); va_end(ap); if ((e = ERR_get_error()) != 0) log("%s: %s", message, ERR_reason_error_string(e)); else log("%s", message); free(message); ERR_clear_error(); } static bool get_peer_address(int fd, char *destination, socklen_t size) { struct sockaddr_storage sa_storage; struct sockaddr *sa = (struct sockaddr *)&sa_storage; socklen_t len = sizeof(struct sockaddr_storage); if (getpeername(fd, sa, &len) == -1) { error("Cannot get peer's IP address: %m"); return false; } switch (sa->sa_family) { case AF_INET: if (inet_ntop(AF_INET, &((struct sockaddr_in *)(void *)sa)->sin_addr, destination, size) == NULL) { error("Cannot convert IPv4 address to text form: %m"); return false; } break; #ifdef AF_INET6 case AF_INET6: if (inet_ntop(AF_INET6, &((struct sockaddr_in6 *)(void *)sa)->sin6_addr, destination, size) == NULL) { error("Cannot convert IPv6 address to text form: %m"); return false; } break; #endif default: error("Unknown address familiy: %d", sa->sa_family); return false; } return true; } /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/src/common/tls.h000066400000000000000000000127751344421036200157530ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * The API is somewhat similar to the interface of the AnyEvent::Handle Perl * module. Limitations include: * * - We don't provide AnyEvent::Handle's on_read() and on_eof() methods, though * they'd be trivial to add if required. * * - Also, we don't support calling tls_read() or tls_read_line() before the * previous read operation has been completed. That is, a tls_read() or * tls_read_line() call cannot be followed by another such call except in the * callback function (or subsequent functions). Adding a read request queue * wouldn't be hard, but we never want to read new stuff before looking at the * data received by the previous read operation, so we really don't need such * functionality. */ #ifndef TLS_H # define TLS_H # if HAVE_CONFIG_H # include # endif # include # include # include # include "buffer.h" # include "system.h" # define TLS_NO_AUTO_DIE 0x0 # define TLS_AUTO_DIE 0x1 typedef struct tls_state_s { /* public: */ void *data; /* Can freely be used by the caller. */ char *id; /* Client ID (e.g., "foo"). */ char *addr; /* Client IP address (e.g., "192.0.2.2"). */ char *peer; /* Client ID and IP address (e.g., "foo@192.0.2.2"). */ /* private: */ ev_io init_watcher; ev_io read_watcher; ev_io write_watcher; ev_io shutdown_watcher; ev_timer timeout_watcher; ev_tstamp timeout; ev_tstamp last_activity; buffer *input_buffer; buffer *output_buffer; unsigned char *input; unsigned char *output; size_t input_size; size_t input_offset; size_t output_size; size_t output_offset; void (*connect_handler)(struct tls_state_s *); void (*read_handler)(struct tls_state_s * restrict, char * restrict); void (*drain_handler)(struct tls_state_s *); void (*error_handler)(struct tls_state_s *); void (*timeout_handler)(struct tls_state_s *); void (*line_too_long_handler)(struct tls_state_s *); void (*free_output)(void *); SSL *ssl; BIO *bio; int fd; unsigned int read_mode : 1; } tls_state; typedef struct { /* public: */ void *data; /* private: */ void (*connect_handler)(tls_state *); SSL_CTX *ssl; ev_tstamp timeout; } tls_client_state; typedef struct { /* public: */ void *data; /* private: */ void (*connect_handler)(tls_state *); ev_io accept_watcher; SSL_CTX *ssl; BIO *bio; ev_tstamp timeout; } tls_server_state; tls_client_state *tls_client_start(const char * restrict); tls_server_state *tls_server_start(const char * restrict, const char * restrict, ev_tstamp, void (*)(tls_state *), unsigned int (*)(SSL *, const char *, unsigned char *, unsigned int)); void tls_connect(tls_client_state *, const char * restrict, ev_tstamp timeout, int flags, void (*)(tls_state *), void (*)(tls_state *), unsigned int (*)(SSL *, const char *, char *, unsigned int, unsigned char *, unsigned int)); void tls_read(tls_state *, void (*)(tls_state *, char *), size_t); void tls_read_line(tls_state *, void (*)(tls_state * restrict, char * restrict)); void tls_write(tls_state * restrict, void * restrict, size_t, void (*)(void *)); void tls_write_line(tls_state * restrict, const char * restrict); void tls_shutdown(tls_state *); void tls_client_stop(tls_client_state *); void tls_server_stop(tls_server_state *); void tls_set_connection_id(tls_state *, const char *); void tls_on_drain(tls_state *, void (*)(tls_state *)); void tls_on_timeout(tls_state *, void (*)(tls_state *)); void tls_on_error(tls_state *, void (*)(tls_state *)); void tls_on_line_too_long(tls_state *, void (*)(tls_state *)); #endif /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/src/common/util.c000066400000000000000000000101261344421036200161050ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #if HAVE_CONFIG_H # include #endif #include #include #include #include #include #include "log.h" #include "system.h" #include "util.h" #include "wrappers.h" static const char *get_ev_backend(EV_P); static const char *get_openssl_version(void); /* * Exported functions. */ char * concat(const char *str1, const char *str2) { size_t len1 = strlen(str1); size_t len2 = strlen(str2); size_t size; char *catenated; if ((size = len1 + len2 + 1) <= len1) die("String concatenation would overflow"); catenated = xmalloc(size); (void)memcpy(catenated, str1, len1); (void)memcpy(catenated + len1, str2, len2); catenated[len1 + len2] = '\0'; return catenated; } bool parse_line(char * restrict line, char ** restrict args, int n_args) { char *p; int i; for (i = 0, p = strtok(line, " \t"); p != NULL; i++, p = strtok(NULL, " \t")) if (i < n_args) args[i] = p; else { if (i > 0) debug("%s message has more than %d argument(s)", args[0], n_args - 1); return false; } if (i > 0) debug("%s message has %d argument(s)", args[0], i - 1); return (bool)(i == n_args); } char * skip_newlines(const char *string) { const char *p = string; while (*p == '\r' || *p == '\n') p++; return (char *)p; } char * skip_whitespace(const char *string) { const char *p = string; while (*p == ' ' || *p == '\t') p++; return (char *)p; } void chomp(char *string) { size_t len; if ((len = strlen(string)) > 0 && string[len - 1] == '\n') string[len - 1] = '\0'; } const char * nsca_version(void) { static char version_string[128]; (void)snprintf(version_string, sizeof(version_string), "%s %s (%s, libev %d.%d with %s)", getprogname(), NSCA_VERSION, get_openssl_version(), ev_version_major(), ev_version_minor(), get_ev_backend(EV_DEFAULT_UC)); return version_string; } /* * Static functions. */ static const char * get_ev_backend(EV_P) { switch (ev_backend(EV_A)) { case EVBACKEND_SELECT: return "select"; case EVBACKEND_POLL: return "poll"; case EVBACKEND_EPOLL: return "epoll"; case EVBACKEND_KQUEUE: return "kqueue"; case EVBACKEND_DEVPOLL: return "/dev/poll"; case EVBACKEND_PORT: return "event port"; default: return "(unknown)"; } } static const char * get_openssl_version(void) { static char version_string[32]; const char *p; size_t i, spaces = 0; for (i = 0, p = SSLeay_version(SSLEAY_VERSION); i < sizeof(version_string) - 2 && *p != '\0'; i++, p++) { if (*p == ' ') spaces++; if (spaces == 2) break; version_string[i] = *p; } version_string[++i] = '\0'; return version_string; } /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/src/common/util.h000066400000000000000000000034211344421036200161120ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef UTIL_H # define UTIL_H # if HAVE_CONFIG_H # include # endif # include "system.h" char *concat(const char *, const char *); bool parse_line(char * restrict , char ** restrict, int); char *skip_newlines(const char *); char *skip_whitespace(const char *); void chomp(char *); const char *nsca_version(void); #endif /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/src/server/000077500000000000000000000000001344421036200150025ustar00rootroot00000000000000nsca-ng-1.6/src/server/Makefile.am000066400000000000000000000052321344421036200170400ustar00rootroot00000000000000## Process this file with automake(1) to produce Makefile.in. ## Copyright (c) 2013 Holger Weiss ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1. Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## ## 2. Redistributions in binary form must reproduce the above copyright notice, ## this list of conditions and the following disclaimer in the documentation ## and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE ## LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ## CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF ## SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ## INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ## CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ## ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ## POSSIBILITY OF SUCH DAMAGE. AM_CPPFLAGS = \ -DSYSCONFDIR='"$(sysconfdir)"' \ -DLOCALSTATEDIR='"$(localstatedir)"' \ -I$(top_srcdir)/src/common \ -I$(top_srcdir)/lib \ $(CONFUSECPPFLAGS) \ $(EVCPPFLAGS) \ $(SSLCPPFLAGS) \ $(SYSTEMDLDFLAGS) AM_LDFLAGS = \ $(CONFUSELDFLAGS) \ $(EVLDFLAGS) \ $(SSLLDFLAGS) \ $(SYSTEMDLDFLAGS) LDADD = \ ../common/libcommon.a \ ../../lib/libcompat.a \ $(CONFUSELIBS) \ $(EVLIBS) \ $(SSLLIBS) \ $(SYSTEMDLIBS) \ $(AIOLIBS) \ $(PIDFILELIBS) if USE_EMBEDDED_EV AM_CPPFLAGS += -I$(top_srcdir)/lib/ev LDADD += ../../lib/ev/libev.a endif if USE_EMBEDDED_PIDFILE AM_CPPFLAGS += -I$(top_srcdir)/lib/pidfile LDADD += ../../lib/pidfile/libpidfile.a endif sbin_PROGRAMS = nsca-ng nsca_ng_SOURCES = auth.c auth.h conf.c conf.h fifo.c fifo.h hash.c hash.h \ nsca-ng.c server.c server.h nsca-ng-1.6/src/server/auth.c000066400000000000000000000104241344421036200161100ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #if HAVE_CONFIG_H # include #endif #include #include #include #include #include #include "auth.h" #include "hash.h" #include "log.h" #include "system.h" #include "util.h" #include "wrappers.h" static bool match(regex_t * restrict, const char * restrict); /* * Exported functions. */ unsigned int check_psk(SSL *ssl, const char *identity, unsigned char *password, unsigned int max_password_len) { cfg_t *auth; const char *configured_pw; size_t password_len; if ((auth = hash_lookup(identity)) == NULL && (auth = hash_lookup("*")) == NULL) { warning("Client-supplied ID `%s' is unknown", identity); return 0; } debug("Verifying key provided by %s", identity); /* * With (at least) OpenSSL 1.1.1b, SSL_get_psk_identity(3) returns NULL * when TLSv1.3 is used. As a workaround, we store the ID ourselves: */ if (SSL_set_app_data(ssl, xstrdup(identity)) != 1) { error("Cannot store client-supplied ID (`%s')", identity); return 0; } configured_pw = cfg_getstr(auth, "password"); password_len = MIN(strlen(configured_pw), max_password_len); (void)memcpy(password, configured_pw, password_len); return (unsigned int)password_len; } bool is_authorized(const char * restrict identity, const char * restrict command) { const char *settings[] = { "hosts", "services", "commands" }; cfg_t *auth; char *newline; size_t i; if ((auth = hash_lookup(identity)) == NULL && (auth = hash_lookup("*")) == NULL) { /* Shouldn't happen, as the client is authenticated. */ error("Cannot find authorizations for %s", identity); return false; } if ((newline = strchr(command, '\n')) == NULL) { warning("Command submitted by %s isn't newline-terminated", identity); return false; } if (*(newline + 1) != '\0') { warning("Command submitted by %s contains embedded newline(s)", identity); return false; } /* Match against the command without the leading bracketed timestamp. */ if ((command = strchr(command, ']')) == NULL) { warning("Timestamp missing from command submitted by %s", identity); return false; } command = skip_whitespace(command + 1); for (i = 0; i < sizeof(settings) / sizeof(*settings); i++) { cfg_opt_t *opt = cfg_getopt(auth, settings[i]); unsigned int j; for (j = 0; j < cfg_opt_size(opt); j++) { regex_t *pattern = cfg_opt_getnptr(opt, j); if (match(pattern, command)) return true; } } return false; } /* * Static functions. */ static bool match(regex_t * restrict pattern, const char * restrict command) { char errbuf[128]; int result = regexec(pattern, command, 0, NULL, 0); switch (result) { case 0: return true; case REG_NOMATCH: return false; default: (void)regerror(result, pattern, errbuf, sizeof(errbuf)); error("Error matching command: %s", errbuf); return false; } } /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/src/server/auth.h000066400000000000000000000033321344421036200161150ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef AUTH_H # define AUTH_H # if HAVE_CONFIG_H # include # endif # include # include "system.h" unsigned int check_psk(SSL *, const char *, unsigned char *, unsigned int); bool is_authorized(const char * restrict, const char * restrict); #endif /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/src/server/conf.c000066400000000000000000000275211344421036200161020ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #if HAVE_CONFIG_H # include #endif #include #include #include #include #include #include #include #include #include "conf.h" #include "hash.h" #include "log.h" #include "system.h" #include "wrappers.h" #define MAX_INCLUDE 1000000UL #define DEFAULT_COMMAND_FILE LOCALSTATEDIR "/nagios/rw/nagios.cmd" #define DEFAULT_LISTEN "*" #define DEFAULT_LOG_LEVEL LOG_LEVEL_NOTICE #define DEFAULT_MAX_COMMAND_SIZE 16384 #define DEFAULT_MAX_QUEUE_SIZE 1024 #define DEFAULT_TEMP_DIRECTORY "/tmp" #define DEFAULT_TIMEOUT 60.0 /* For considerations, see RFC 5482, section 6. */ #define DEFAULT_TLS_CIPHERS \ "PSK-AES256-CBC-SHA:PSK-AES128-CBC-SHA:PSK-3DES-EDE-CBC-SHA:PSK-RC4-SHA" static unsigned long n_included = 0; static cfg_t *include_cfg; static int parse_include(cfg_t * restrict, const char * restrict); static void check_parse_success(int); static void process_auth_sections(cfg_t *); static void validate_auth_section(cfg_t *); static void fallback_to_defaults(cfg_t * restrict, cfg_t * restrict); static char *host_to_command(const char *); static char *service_to_command(const char *); static int parse_host_pattern_cb(cfg_t * restrict, cfg_opt_t * restrict, const char * restrict, void * restrict); static int parse_service_pattern_cb(cfg_t * restrict, cfg_opt_t * restrict, const char * restrict, void * restrict); static int parse_command_pattern_cb(cfg_t * restrict, cfg_opt_t * restrict, const char * restrict, void * restrict); static void free_auth_pattern_cb(void *); static int validate_unsigned_int_cb(cfg_t *, cfg_opt_t *); static int validate_unsigned_float_cb(cfg_t *, cfg_opt_t *); static int include_cb(cfg_t * restrict, cfg_opt_t * restrict, int, const char ** restrict); static int include_file_cb(const char *, const struct stat *, int, struct FTW *); /* * Exported functions. */ cfg_t * conf_parse(const char *path) { struct stat sb; /* * To let the user specify a global default value for an "authorize" * setting, also add the setting as a CFG_STR to the list of global * options, and add the setting's name to the "settings" array in the * fallback_to_defaults() function. This should be done for all * authorization settings. */ cfg_opt_t auth_opts[] = { CFG_STR("password", NULL, CFGF_NODEFAULT), CFG_PTR_LIST_CB("commands", NULL, CFGF_NODEFAULT, parse_command_pattern_cb, free_auth_pattern_cb), CFG_PTR_LIST_CB("hosts", NULL, CFGF_NODEFAULT, parse_host_pattern_cb, free_auth_pattern_cb), CFG_PTR_LIST_CB("services", NULL, CFGF_NODEFAULT, parse_service_pattern_cb, free_auth_pattern_cb), CFG_END() }; cfg_opt_t opts[] = { CFG_FUNC("include", include_cb), CFG_STR("chroot", NULL, CFGF_NODEFAULT), CFG_STR("command_file", DEFAULT_COMMAND_FILE, CFGF_NONE), CFG_STR("commands", NULL, CFGF_NODEFAULT), CFG_STR("hosts", NULL, CFGF_NODEFAULT), CFG_STR("listen", DEFAULT_LISTEN, CFGF_NONE), CFG_INT("log_level", DEFAULT_LOG_LEVEL, CFGF_NONE), CFG_INT("max_command_size", DEFAULT_MAX_COMMAND_SIZE, CFGF_NONE), CFG_INT("max_queue_size", DEFAULT_MAX_QUEUE_SIZE, CFGF_NONE), CFG_STR("password", NULL, CFGF_NODEFAULT), CFG_STR("pid_file", NULL, CFGF_NODEFAULT), CFG_STR("services", NULL, CFGF_NODEFAULT), CFG_STR("temp_directory", DEFAULT_TEMP_DIRECTORY, CFGF_NONE), CFG_STR("tls_ciphers", DEFAULT_TLS_CIPHERS, CFGF_NONE), CFG_FLOAT("timeout", DEFAULT_TIMEOUT, CFGF_NONE), CFG_STR("user", NULL, CFGF_NODEFAULT), CFG_SEC("authorize", auth_opts, CFGF_MULTI | CFGF_TITLE | CFGF_NO_TITLE_DUPES), CFG_END() }; cfg_t *cfg = cfg_init(opts, CFGF_NONE); /* Aborts on error. */ cfg_set_validate_func(cfg, "log_level", validate_unsigned_int_cb); cfg_set_validate_func(cfg, "max_command_size", validate_unsigned_int_cb); cfg_set_validate_func(cfg, "max_queue_size", validate_unsigned_int_cb); cfg_set_validate_func(cfg, "timeout", validate_unsigned_float_cb); debug("Parsing configuration file %s", path); if (stat(path, &sb) == -1) die("Cannot access %s: %m", path); if (S_ISDIR(sb.st_mode)) check_parse_success(parse_include(cfg, path)); else check_parse_success(cfg_parse(cfg, path)); process_auth_sections(cfg); return cfg; } /* * Static functions. */ static int parse_include(cfg_t * restrict cfg, const char * restrict path) { char *include_statement; int status; xasprintf(&include_statement, "include('%s')", path); status = cfg_parse_buf(cfg, include_statement); free(include_statement); return status; } static void check_parse_success(int status) { switch (status) { case CFG_SUCCESS: break; case CFG_PARSE_ERROR: /* An error message has been printed already. */ exit(EXIT_FAILURE); case CFG_FILE_ERROR: die("Cannot open configuration file for reading"); default: /* Won't happen unless the libConfuse API changes. */ die("Cannot parse the configuration"); } } static void process_auth_sections(cfg_t *cfg) { unsigned int i, n_auth_blocks; if ((n_auth_blocks = cfg_size(cfg, "authorize")) == 0) die("No authorizations configured"); hash_new((size_t)(n_auth_blocks /* Minimize collisions: */ * 1.5)); for (i = 0; i < n_auth_blocks; i++) { cfg_t *auth = cfg_getnsec(cfg, "authorize", i); const char *identity = cfg_title(auth); debug("Processing authorizations for %s", identity); fallback_to_defaults(cfg, auth); validate_auth_section(auth); hash_insert(identity, auth); } } static void validate_auth_section(cfg_t *auth) { const char *identity = cfg_title(auth); if (cfg_size(auth, "password") == 0) die("No password specified for %s", identity); } static void fallback_to_defaults(cfg_t * restrict cfg, cfg_t * restrict auth) { const char *settings[] = { "hosts", "services", "commands", "password" }; size_t i; for (i = 0; i < sizeof(settings) / sizeof(*settings); i++) { cfg_opt_t *global_opt = cfg_getopt(cfg, settings[i]); unsigned int j; if (cfg_size(auth, settings[i]) == 0 && cfg_opt_size(global_opt) > 0) for (j = 0; j < cfg_opt_size(global_opt); j++) if (cfg_setopt(auth, cfg_getopt(auth, settings[i]), cfg_opt_getnstr(global_opt, j)) == NULL) exit(EXIT_FAILURE); } } static char * host_to_command(const char *host_pattern) { char *command_pattern; xasprintf(&command_pattern, "PROCESS_HOST_CHECK_RESULT;%s;.+", host_pattern); return command_pattern; } static char * service_to_command(const char *service_pattern) { const char *host_part, *service_part; char *at, *command_pattern, *pattern = xstrdup(service_pattern); if ((at = strrchr(pattern, '@')) == NULL) host_part = "[^;]+"; else { host_part = at + 1; *at = '\0'; } service_part = pattern; xasprintf(&command_pattern, "PROCESS_SERVICE_CHECK_RESULT;%s;%s;.+;.+", host_part, service_part); free(pattern); return command_pattern; } static int parse_host_pattern_cb(cfg_t * restrict cfg, cfg_opt_t * restrict opt, const char * restrict value, void * restrict result) { char *command_pattern = host_to_command(value); int success = parse_command_pattern_cb(cfg, opt, command_pattern, result); free(command_pattern); return success; } static int parse_service_pattern_cb(cfg_t * restrict cfg, cfg_opt_t * restrict opt, const char * restrict value, void * restrict result) { char *command_pattern = service_to_command(value); int success = parse_command_pattern_cb(cfg, opt, command_pattern, result); free(command_pattern); return success; } static int parse_command_pattern_cb(cfg_t * restrict cfg, cfg_opt_t * restrict opt, const char * restrict value, void * restrict result) { regex_t **re = result; char *pattern; char errbuf[128]; int success; xasprintf(&pattern, "^%s\n?$", value); *re = xmalloc(sizeof(regex_t)); if ((success = regcomp(*re, pattern, REG_EXTENDED | REG_NOSUB)) != 0) { (void)regerror(success, *re, errbuf, sizeof(errbuf)); cfg_error(cfg, "Error in `%s' pattern `%s': %s", opt->name, value, errbuf); } free(pattern); return success; } static void free_auth_pattern_cb(void *value) { regfree(value); free(value); } /* * See . */ static int validate_unsigned_int_cb(cfg_t * restrict cfg, cfg_opt_t * restrict opt) { long int value = cfg_opt_getnint(opt, cfg_opt_size(opt) - 1); if (value < 0) { cfg_error(cfg, "`%s' must be a positive integer", opt->name); return -1; /* Abort. */ } return 0; } static int validate_unsigned_float_cb(cfg_t * restrict cfg, cfg_opt_t * restrict opt) { double value = cfg_opt_getnfloat(opt, cfg_opt_size(opt) - 1); if (value < 0.0) { cfg_error(cfg, "`%s' must be a positive value", opt->name); return -1; /* Abort. */ } return 0; } static int include_cb(cfg_t * restrict cfg, cfg_opt_t * restrict opt, int argc, const char ** restrict argv) { struct stat sb; char *path; int status; if (++n_included > MAX_INCLUDE) { cfg_error(cfg, "Processed too many `%s' directives", opt->name); return 1; } if (argc != 1) { cfg_error(cfg, "`%s' expects one argument", opt->name); return 1; } if ((path = cfg_tilde_expand(argv[0])) == NULL) { cfg_error(cfg, "Cannot tilde-expand %s", argv[0]); return 1; } if (stat(path, &sb) == -1) { cfg_error(cfg, "Cannot access %s: %s", path, strerror(errno)); status = 1; } else if (S_ISREG(sb.st_mode)) { status = cfg_include(cfg, opt, argc, argv); } else if (S_ISDIR(sb.st_mode)) { include_cfg = cfg; if (nftw(path, include_file_cb, /* Arbitrary: */ 20, 0) == -1) { cfg_error(cfg, "Cannot traverse %s tree: %s", path, strerror(errno)); status = 1; } else status = 0; } else { cfg_error(cfg, "%s is not a file or directory", path); status = 1; } free(path); return status; } static int include_file_cb(const char *path, const struct stat *sb __attribute__((__unused__)), int type, struct FTW *info __attribute__((__unused__))) { char *dot; if (type != FTW_F) { debug("Not including %s, as it's not a regular file", path); return 0; } if ((dot = strrchr(path, '.')) == NULL || (strcmp(dot, ".cfg") != 0 && strcmp(dot, ".conf") != 0)) { debug("Not including %s, as it's not a .cfg/.conf file", path); return 0; } debug("Parsing %s", path); check_parse_success(parse_include(include_cfg, path)); return 0; } /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/src/server/conf.h000066400000000000000000000032741344421036200161060ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef CONF_H # define CONF_H # if HAVE_CONFIG_H # include # endif # include # include "system.h" # define DEFAULT_CONF_FILE SYSCONFDIR "/nsca-ng.cfg" # define DEFAULT_PORT "5668" cfg_t *conf_parse(const char *); #endif /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/src/server/fifo.c000066400000000000000000000375071344421036200161050ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #if HAVE_CONFIG_H # include #endif #include #include #if HAVE_POSIX_AIO # include #endif #include #include #include #include #include #include #include #include #include #include "buffer.h" #include "fifo.h" #include "log.h" #include "system.h" #include "wrappers.h" #define TIMEOUT 10.0 #if HAVE_POSIX_AIO # ifdef SIGRTMIN # define SIG_AIO (SIGRTMIN + 1) # else # define SIG_AIO SIGUSR1 # endif #endif #ifdef _AIX # undef PIPE_BUF /* See . */ #endif #ifndef PIPE_BUF # define PIPE_BUF 512 /* POSIX guarantees PIPE_BUF >= 512. */ #endif struct fifo_state_s { /* This is typedef'd to `fifo_state' in fifo.h. */ #if HAVE_POSIX_AIO struct aiocb async_cb; void (*free_aio_buf)(void *); ev_async async_watcher; #else ev_idle idle_watcher; ev_timer timeout_watcher; #endif ev_timer open_watcher; ev_io write_watcher; buffer *output_buffer; char *dump_file; const char *dump_dir; const char *path; unsigned char *output; size_t output_size; void (*free_output)(void *); size_t max_queue_size; int dump_fd; int fd; }; static void open_cb(EV_P_ ev_timer *, int); static void write_cb(EV_P_ ev_io *, int); #if HAVE_POSIX_AIO static void async_dump_data(fifo_state *); static void async_signal_handler(int, siginfo_t *, void *); static void async_cb(EV_P_ ev_async *, int); #else static void idle_cb(EV_P_ ev_idle *, int); static void timeout_cb(EV_P_ ev_timer *, int); static void sync_dump_data(fifo_state *); #endif static void dispatch_data(fifo_state *); static char *make_process_file_command(fifo_state *); static bool open_dump_file(fifo_state *); static bool close_dump_file(fifo_state *); static bool buffers_are_empty(fifo_state *); static bool buffers_exceed_pipe_size(fifo_state *); static void join_buffers(fifo_state *); static void free_output(fifo_state *); /* * Exported functions. */ fifo_state * fifo_start(const char * restrict path, const char * restrict dump_dir, size_t max_queue_size) { fifo_state *fifo = xmalloc(sizeof(fifo_state)); #if HAVE_POSIX_AIO struct sigaction action; #endif debug("Starting command file writer"); #if HAVE_POSIX_AIO debug("Using the POSIX AIO API"); action.sa_sigaction = async_signal_handler; action.sa_flags = SA_SIGINFO; (void)sigemptyset(&action.sa_mask); if (sigaction(SIG_AIO, &action, NULL) == -1) die("Cannot associate action with POSIX AIO signal: %m"); fifo->free_aio_buf = NULL; fifo->async_watcher.data = fifo; #else fifo->idle_watcher.data = fifo; fifo->timeout_watcher.data = fifo; #endif fifo->open_watcher.data = fifo; fifo->write_watcher.data = fifo; fifo->output_buffer = buffer_new(); fifo->dump_file = NULL; fifo->dump_dir = dump_dir; fifo->path = path; fifo->output = NULL; fifo->output_size = 0; fifo->free_output = free; fifo->max_queue_size = max_queue_size * 1024 * 1024; fifo->dump_fd = -1; fifo->fd = -1; #if HAVE_POSIX_AIO ev_init(&fifo->async_watcher, async_cb); #else ev_init(&fifo->idle_watcher, idle_cb); ev_init(&fifo->timeout_watcher, timeout_cb); #endif ev_init(&fifo->open_watcher, open_cb); ev_init(&fifo->write_watcher, write_cb); ev_invoke(EV_DEFAULT_UC_ &fifo->open_watcher, EV_CUSTOM); return fifo; } void fifo_write(fifo_state * restrict fifo, void * restrict data, size_t size, void free_data(void *)) { if (buffers_are_empty(fifo) && free_data != NULL) { debug("Zero-copying %zu byte(s) to command file", size); fifo->output = data; fifo->output_size = size; fifo->free_output = free_data; dispatch_data(fifo); } else { if (fifo->max_queue_size > 0 && buffer_size(fifo->output_buffer) + size > fifo->max_queue_size) { warning("Queued more than %zu MB, THROWING DATA AWAY", fifo->max_queue_size / 1024 / 1024); buffer_free(fifo->output_buffer); fifo->output_buffer = buffer_new(); } debug("Queueing %zu byte(s) for command file", size); buffer_append(fifo->output_buffer, data, size); dispatch_data(fifo); if (free_data != NULL) free_data(data); } } void fifo_stop(fifo_state *fifo) { debug("Stopping command file writer"); #if HAVE_POSIX_AIO if (ev_is_active(&fifo->async_watcher)) ev_async_stop(EV_DEFAULT_UC_ &fifo->async_watcher); #else if (ev_is_active(&fifo->idle_watcher)) ev_idle_stop(EV_DEFAULT_UC_ &fifo->idle_watcher); if (ev_is_active(&fifo->timeout_watcher)) ev_timer_stop(EV_DEFAULT_UC_ &fifo->timeout_watcher); #endif if (ev_is_active(&fifo->open_watcher)) ev_timer_stop(EV_DEFAULT_UC_ &fifo->open_watcher); if (ev_is_active(&fifo->write_watcher)) ev_io_stop(EV_DEFAULT_UC_ &fifo->write_watcher); buffer_free(fifo->output_buffer); if (fifo->output != NULL) free(fifo->output); if (fifo->fd != -1) (void)close(fifo->fd); free(fifo); } /* * Static functions. */ static void open_cb(EV_P_ ev_timer *w, int revents) { fifo_state *fifo = w->data; struct stat sb; int result; do fifo->fd = open(fifo->path, O_WRONLY | O_NONBLOCK); while (fifo->fd == -1 && errno == EINTR); if (fifo->fd == -1) { if (errno == ENXIO) /* Spit out a proper error message. */ warning("No process is reading the command file"); else warning("Cannot open %s: %m", fifo->path); } else if (((result = fstat(fifo->fd, &sb)) == -1) || !S_ISFIFO(sb.st_mode)) { if (result == -1) warning("Cannot get status of %s: %m", fifo->path); else warning("%s is not a named pipe", fifo->path); (void)close(fifo->fd); fifo->fd = -1; } else { if (revents == EV_CUSTOM) /* We were invoked by fifo_start(). */ debug("Opened command file for writing"); else notice("Opened the command file successfully"); ev_io_set(&fifo->write_watcher, fifo->fd, EV_WRITE); if (!buffers_are_empty(fifo)) dispatch_data(fifo); } if (fifo->fd == -1) { ev_timer_set(&fifo->open_watcher, TIMEOUT, 0.0); ev_timer_start(EV_A_ w); } } static void write_cb(EV_P_ ev_io *w, int revents __attribute__((__unused__))) { fifo_state *fifo = w->data; ssize_t n; do { if (fifo->output == NULL) { fifo->output = buffer_slurp(fifo->output_buffer, &fifo->output_size); fifo->free_output = free; } if ((n = write(fifo->fd, fifo->output, fifo->output_size)) == -1) switch (errno) { #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN case EWOULDBLOCK: /* Fall through. */ #endif case EAGAIN: debug("Writing to command file failed: %m"); return; case EINTR: debug("Writing to command file failed: %m"); continue; default: error("Cannot write to command file: %m"); (void)close(fifo->fd); fifo->fd = -1; ev_io_stop(EV_A_ w); ev_timer_set(&fifo->open_watcher, TIMEOUT, 0.0); ev_timer_start(EV_A_ &fifo->open_watcher); } else { /* * POSIX guarantees n == fifo->output_size, as we've * written no more than PIPE_BUF bytes. See the * write(2) documentation. */ debug("Wrote %zd bytes to command file", n); free_output(fifo); if (buffer_size(fifo->output_buffer) == 0) ev_io_stop(EV_A_ w); } } while (n > 0 && buffer_size(fifo->output_buffer) > 0); } #if HAVE_POSIX_AIO /* * We serialize our POSIX AIO operations (so that only a single write request is * queued at any given time). This is done for the following reasons: * * - It allows us to support systems which don't provide realtime signals (such * as NetBSD 6) without having to check the status of every request each time * the AIO signal is received. * * - With realtime signals, there is the problem that the signal buffer might * overflow, which means signals could be lost; and the POSIX API provides no * notification of such overflow. See: * * http://aricwang.blogspot.de/2010/08/asynchronous-io-on-linux.html * * - With serialized I/O, there's no need to block the signal handler in the * ev_async watcher callback (as suggested in the ev_async documentation of * the ev(3) man page). * * - Parallelizing our disk I/O makes little sense anyway. */ static void async_dump_data(fifo_state *fifo) { join_buffers(fifo); if (!open_dump_file(fifo)) { free_output(fifo); return; } (void)memset(&fifo->async_cb, 0, sizeof(fifo->async_cb)); fifo->free_aio_buf = fifo->free_output; fifo->async_cb.aio_buf = fifo->output; fifo->async_cb.aio_nbytes = fifo->output_size; fifo->async_cb.aio_fildes = fifo->dump_fd; fifo->async_cb.aio_offset = 0; fifo->async_cb.aio_sigevent.sigev_notify = SIGEV_SIGNAL; fifo->async_cb.aio_sigevent.sigev_signo = SIG_AIO; fifo->async_cb.aio_sigevent.sigev_value.sival_ptr = fifo; ev_async_start(EV_DEFAULT_UC_ &fifo->async_watcher); debug("Queuing %zu bytes for writing to %s", fifo->output_size, fifo->dump_file); if (aio_write(&fifo->async_cb) == -1) { error("Cannot queue asynchrous write request: %m"); ev_async_stop(EV_DEFAULT_UC_ &fifo->async_watcher); (void)close_dump_file(fifo); free_output(fifo); return; } /* The output buffer is now owned by fifo->async_cb.aio_buf. */ fifo->output = NULL; fifo->output_size = 0; } static void async_signal_handler(int signal_number __attribute__((__unused__)), siginfo_t *signal_info, void *context __attribute__((__unused__))) { if (signal_info->si_code == SI_ASYNCIO) { fifo_state *fifo = signal_info->si_value.sival_ptr; ev_async_send(EV_DEFAULT_UC_ &fifo->async_watcher); } } static void async_cb(EV_P_ ev_async *w, int revents __attribute__((__unused__))) { fifo_state *fifo = w->data; ssize_t n; int result; debug("Handling POSIX AIO signal"); ev_async_stop(EV_DEFAULT_UC_ &fifo->async_watcher); fifo->free_aio_buf((void *)fifo->async_cb.aio_buf); fifo->async_cb.aio_buf = NULL; if ((result = aio_error(&fifo->async_cb)) != 0) error("Cannot write to %s: %s", fifo->dump_file, strerror(result)); else if ((n = aio_return(&fifo->async_cb)) != (ssize_t)fifo->async_cb.aio_nbytes) /* Presumably an error. */ error("Wrote %zd instead of %zu bytes to %s", n, fifo->async_cb.aio_nbytes, fifo->dump_file); else { char *command = make_process_file_command(fifo); debug("Wrote %zd bytes to %s", n, fifo->dump_file); if (close_dump_file(fifo)) fifo_write(fifo, command, strlen(command), free); } if (buffers_exceed_pipe_size(fifo)) dispatch_data(fifo); } #else static void idle_cb(EV_P_ ev_idle *w, int revents __attribute__((__unused__))) { fifo_state *fifo = w->data; ev_idle_stop(EV_A_ &fifo->idle_watcher); if (ev_is_active(&fifo->timeout_watcher)) ev_timer_stop(EV_A_ &fifo->timeout_watcher); sync_dump_data(fifo); } static void timeout_cb(EV_P_ ev_timer *w, int revents) { fifo_state *fifo = w->data; debug("Idle watcher timed out"); ev_invoke(EV_A_ &fifo->idle_watcher, revents); } static void sync_dump_data(fifo_state *fifo) { char *command; size_t offset; ssize_t n; join_buffers(fifo); if (!open_dump_file(fifo)) { free_output(fifo); return; } for (offset = 0; fifo->output_size > offset; offset += (size_t)n) { do n = write(fifo->dump_fd, fifo->output + offset, fifo->output_size - offset); while (n == -1 && errno == EINTR); if (n == -1) { error("Cannot write to %s: %m", fifo->dump_file); (void)close_dump_file(fifo); free_output(fifo); return; } debug("Wrote %zu bytes to %s", fifo->output_size, fifo->dump_file); } free_output(fifo); command = make_process_file_command(fifo); if (close_dump_file(fifo)) fifo_write(fifo, command, strlen(command), free); } #endif static void dispatch_data(fifo_state *fifo) { if (fifo->fd == -1) return; /* Queue the data if Nagios is down. */ if (!buffers_exceed_pipe_size(fifo)) { if (!ev_is_active(&fifo->write_watcher)) { debug("Starting command file output watcher"); ev_io_start(EV_DEFAULT_UC_ &fifo->write_watcher); /* * Invoke write_cb() immediately to minimize the risk of * exceeding the PIPE_BUF threshold. */ ev_invoke(EV_DEFAULT_UC_ &fifo->write_watcher, EV_CUSTOM); } else debug("Command file output watcher is active"); } else { if (ev_is_active(&fifo->write_watcher)) { debug("Stopping command file output watcher"); ev_io_stop(EV_DEFAULT_UC_ &fifo->write_watcher); } #if HAVE_POSIX_AIO if (!ev_is_active(&fifo->async_watcher)) { debug("Initiating asynchronous output request"); async_dump_data(fifo); } else debug("Asynchronous output watcher is active"); #else if (!ev_is_active(&fifo->idle_watcher)) { debug("Starting idle and timer watchers"); ev_timer_set(&fifo->timeout_watcher, TIMEOUT, 0.0); ev_timer_start(EV_DEFAULT_UC_ &fifo->timeout_watcher); ev_idle_start(EV_DEFAULT_UC_ &fifo->idle_watcher); } else debug("Idle and timer watchers are active"); #endif } } static char * make_process_file_command(fifo_state *fifo) { char *command; xasprintf(&command, "[%lu] PROCESS_FILE;%s;1\n", (unsigned long)time(NULL), fifo->dump_file); return command; } static bool open_dump_file(fifo_state *fifo) { xasprintf(&fifo->dump_file, "%s/nsca.XXXXXX", fifo->dump_dir); if ((fifo->dump_fd = mkstemp(fifo->dump_file)) == -1) { error("Cannot create %s: %m", fifo->dump_file); free(fifo->dump_file); fifo->dump_file = NULL; return false; } return true; } static bool close_dump_file(fifo_state *fifo) { int result; do result = close(fifo->dump_fd); while (result == -1 && errno == EINTR); if (result == -1) error("Cannot close %s: %m", fifo->dump_file); free(fifo->dump_file); fifo->dump_file = NULL; return (bool)(result == 0); } static bool buffers_are_empty(fifo_state *fifo) { return (bool)(fifo->output == NULL && buffer_size(fifo->output_buffer) == 0); } static bool buffers_exceed_pipe_size(fifo_state *fifo) { return (bool)(fifo->output_size > PIPE_BUF || buffer_size(fifo->output_buffer) > PIPE_BUF); } static void join_buffers(fifo_state *fifo) { unsigned char *new_output; size_t new_size; if (buffer_size(fifo->output_buffer) == 0) return; new_size = fifo->output_size + buffer_size(fifo->output_buffer); new_output = xmalloc(new_size); debug("Joining output buffers (new size: %zu bytes)", new_size); if (fifo->output != NULL) (void)memcpy(new_output, fifo->output, fifo->output_size); (void)buffer_read(fifo->output_buffer, new_output + fifo->output_size, new_size - fifo->output_size); if (fifo->output != NULL) free_output(fifo); fifo->output = new_output; fifo->output_size = new_size; fifo->free_output = free; } static void free_output(fifo_state *fifo) { fifo->free_output(fifo->output); fifo->output = NULL; fifo->output_size = 0; } /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/src/server/fifo.h000066400000000000000000000034511344421036200161010ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef FIFO_H # define FIFO_H # if HAVE_CONFIG_H # include # endif # include "system.h" typedef struct fifo_state_s fifo_state; fifo_state *fifo_start(const char * restrict, const char * restrict, size_t); void fifo_write(fifo_state * restrict, void * restrict, size_t, void (*)(void *)); void fifo_stop(fifo_state *); #endif /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/src/server/hash.c000066400000000000000000000060441344421036200160750ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * NOTE: hdestroy(3) cannot be used in a sane and portable way. On BSD, * hdestroy(3) calls free(3) on all keys; on Linux, it doesn't. So, if we ever * need multiple hash tables, we should use a different implementation, such as * . */ #if HAVE_CONFIG_H # include #endif #include #include "hash.h" #include "log.h" #include "system.h" void hash_new(size_t size) { debug("Creating hash table for %zu entries", size); if (hcreate(size) == 0) die("Cannot create hash table: %m"); } void hash_insert(const char * restrict key, void * restrict value) { ENTRY e, *p; e.key = (char *)key; e.data = NULL; /* Initialize to make Clang's Static Analyzer happy. */ /* * Quoting the Linux man page: * * | SVr4 and POSIX.1-2001 specify that 'action' is significant only for * | unsuccessful searches, so that an ENTER should not do anything for * | a successful search. In libc and glibc (before version 2.3), the * | implementation violates the specification, updating the 'data' for * | the given 'key' in this case. * * In order to replace existing entries on all systems, we update the * value after searching for the entry. (However, nsca-ng will never * call this function with an existing key.) */ if ((p = hsearch(e, ENTER)) == NULL) die("Cannot insert `%s' into hash table: %m", key); p->data = value; } void * hash_lookup(const char *key) { ENTRY e, *p; e.key = (char *)key; e.data = NULL; /* Initialize to make Clang's Static Analyzer happy. */ if ((p = hsearch(e, FIND)) == NULL) return NULL; else return p->data; } /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/src/server/hash.h000066400000000000000000000033121344421036200160750ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef HASH_H # define HASH_H # if HAVE_CONFIG_H # include # endif # include /* For size_t. */ # include "system.h" void hash_new(size_t); void hash_insert(const char * restrict, void * restrict); void *hash_lookup(const char *); #endif /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/src/server/nsca-ng.c000066400000000000000000000320661344421036200165030ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #if HAVE_CONFIG_H # include #endif #if HAVE_SYS_PARAM_H # include #endif #include #if HAVE_SYSTEMD_SD_DAEMON_H # include #endif #include #include #include #if HAVE_INTTYPES_H # include #endif #if HAVE_BSD_LIBUTIL_H # include #else # include /* Either in /usr/include or in ../../lib/pidfile. */ #endif #include #include #include #include #include #include #include #include "conf.h" #include "log.h" #include "server.h" #include "system.h" #include "util.h" #include "wrappers.h" typedef struct { char *bind; char *conf_file; char *command_file; char *pid_file; int log_level; int log_target; bool foreground; } options; static cfg_t *cfg = NULL; static struct pidfh *pfh = NULL; static char *pid_file = NULL; static bool restart = false; static ev_timer keep_alive_watcher; static ev_signal sighup_watcher, sigint_watcher, sigterm_watcher; static options *get_options(int, char **); static void free_options(options *); static void close_descriptors(void); static void drop_privileges(const char *, const char *); static void remove_pidfile(void); static void forget_config(void); static void stop_keep_alive(void); static void notify_systemd(void); static void keep_alive_cb(EV_P_ ev_timer *, int); static void signal_cb(EV_P_ ev_signal *, int); static void usage(int) __attribute__((__noreturn__)); int main(int argc, char **argv) { server_state *server; options *opt; pid_t other_pid; int socket_activated; setprogname(argv[0]); log_set(LOG_LEVEL_INFO, LOG_TARGET_STDERR); if ((socket_activated = sd_listen_fds(0)) < 0) die("Cannot receive socket from init system: %m"); else if (socket_activated > 1) die("Received too many sockets from init system"); else if (socket_activated == 1) log_set(-1, LOG_TARGET_SYSTEMD); else /* socket_activated == 0 */ close_descriptors(); if (atexit(log_close) != 0 || atexit(forget_config) != 0) die("Cannot register function to be called on exit"); if (!ev_default_loop(0)) die("Cannot initialize libev"); opt = get_options(argc, argv); cfg = conf_parse(opt->conf_file != NULL ? opt->conf_file : DEFAULT_CONF_FILE); if (cfg_size(cfg, "user") > 0 || cfg_size(cfg, "chroot") > 0) drop_privileges(cfg_size(cfg, "user") > 0 ? cfg_getstr(cfg, "user") : NULL, cfg_size(cfg, "chroot") > 0 ? cfg_getstr(cfg, "chroot") : NULL); if (opt->log_target == -1) { if (socket_activated) opt->log_target = LOG_TARGET_SYSTEMD; else if (opt->foreground) opt->log_target = LOG_TARGET_STDERR; else opt->log_target = LOG_TARGET_SYSLOG; } else if (!opt->foreground && opt->log_target & LOG_TARGET_STDERR) die("The `-S' option may not be specified without `-F'"); if (opt->log_level != -1) cfg_setint(cfg, "log_level", opt->log_level); if (opt->command_file != NULL) cfg_setstr(cfg, "command_file", opt->command_file); if (opt->pid_file != NULL) cfg_setstr(cfg, "pid_file", opt->pid_file); if (opt->bind != NULL) cfg_setstr(cfg, "listen", opt->bind); if (access(cfg_getstr(cfg, "temp_directory"), X_OK | W_OK) == -1) die("Cannot write temporary files into %s: %m", cfg_getstr(cfg, "temp_directory")); pid_file = cfg_size(cfg, "pid_file") > 0 ? cfg_getstr(cfg, "pid_file") : NULL; if (opt->log_target & (LOG_TARGET_STDERR | LOG_TARGET_SYSTEMD)) log_set((int)cfg_getint(cfg, "log_level"), -1); else log_set((int)cfg_getint(cfg, "log_level"), opt->log_target | LOG_TARGET_STDERR); if (socket_activated) { char *descriptor; if (strcmp(cfg_getstr(cfg, "listen"), "*") != 0) notice("Ignoring `-b'/`listen' when socket activated"); xasprintf(&descriptor, "descriptor=%d", SD_LISTEN_FDS_START); cfg_setstr(cfg, "listen", descriptor); free(descriptor); } else if (strchr(cfg_getstr(cfg, "listen"), ':') == NULL) { char *host_port; xasprintf(&host_port, "%s:%s", cfg_getstr(cfg, "listen"), DEFAULT_PORT); cfg_setstr(cfg, "listen", host_port); free(host_port); } if (pid_file != NULL) { if ((pfh = pidfile_open(pid_file, 0600, &other_pid)) == NULL) { if (errno == EEXIST) die("%s seems to be running already (PID: %jd)", PACKAGE_NAME, (intmax_t)other_pid); else die("Cannot create %s: %m", pid_file); } if (atexit(remove_pidfile) != 0) die("Cannot register function to be called on exit"); } server = server_start( cfg_getstr(cfg, "listen"), cfg_getstr(cfg, "tls_ciphers"), cfg_getstr(cfg, "command_file"), cfg_getstr(cfg, "temp_directory"), (size_t)cfg_getint(cfg, "max_command_size"), (size_t)cfg_getint(cfg, "max_queue_size"), cfg_getfloat(cfg, "timeout")); if (!opt->foreground && !socket_activated) { if (daemon(0, 0) == -1) die("Cannot daemonize: %m"); ev_loop_fork(EV_DEFAULT_UC); } log_set((int)cfg_getint(cfg, "log_level"), opt->log_target); if (pid_file != NULL && pidfile_write(pfh) == -1) die("Cannot write PID to %s: %m", pid_file); notice("%s starting up", nsca_version()); ev_signal_init(&sighup_watcher, signal_cb, SIGHUP); ev_signal_init(&sigint_watcher, signal_cb, SIGINT); ev_signal_init(&sigterm_watcher, signal_cb, SIGTERM); ev_signal_start(EV_DEFAULT_UC_ &sighup_watcher); ev_signal_start(EV_DEFAULT_UC_ &sigint_watcher); ev_signal_start(EV_DEFAULT_UC_ &sigterm_watcher); notify_systemd(); (void)ev_run(EV_DEFAULT_UC_ 0); server_stop(server); free_options(opt); if (restart) { notice("Restarting"); /* The atexit(3) functions won't be called on exec(3). */ remove_pidfile(); forget_config(); stop_keep_alive(); execvp(argv[0], argv); die("Cannot restart myself: %m"); } notice("Exiting"); return EXIT_SUCCESS; } static options * get_options(int argc, char **argv) { extern int optind; extern char *optarg; options *opt = xmalloc(sizeof(options)); int option; opt->bind = NULL; opt->conf_file = NULL; opt->command_file = NULL; opt->pid_file = NULL; opt->log_level = -1; opt->log_target = -1; opt->foreground = false; if (argc == 2) { if (strcmp(argv[1], "--help") == 0) usage(EXIT_SUCCESS); if (strcmp(argv[1], "--version") == 0) { (void)puts(nsca_version()); exit(EXIT_SUCCESS); } } while ((option = getopt(argc, argv, "b:C:c:Fhl:P:SsV")) != -1) switch (option) { case 'b': if (opt->bind != NULL) free(opt->bind); opt->bind = xstrdup(optarg); break; case 'C': if (opt->command_file != NULL) free(opt->command_file); opt->command_file = xstrdup(optarg); break; case 'c': if (opt->conf_file != NULL) free(opt->conf_file); opt->conf_file = xstrdup(optarg); break; case 'F': opt->foreground = true; break; case 'h': usage(EXIT_SUCCESS); case 'l': opt->log_level = atoi(optarg); break; case 'P': if (opt->pid_file != NULL) free(opt->pid_file); opt->pid_file = xstrdup(optarg); break; case 'S': opt->log_target = LOG_TARGET_SYSLOG | LOG_TARGET_STDERR; break; case 's': opt->log_target = opt->log_target != -1 ? LOG_TARGET_SYSLOG | opt->log_target : LOG_TARGET_SYSLOG; break; case 'V': (void)puts(nsca_version()); exit(EXIT_SUCCESS); default: usage(EXIT_FAILURE); } if (argc - optind > 0) die("Unexpected non-option argument: %s", argv[optind]); return opt; } static void free_options(options *opt) { if (opt->bind != NULL) free(opt->bind); if (opt->conf_file != NULL) free(opt->conf_file); if (opt->command_file != NULL) free(opt->command_file); if (opt->pid_file != NULL) free(opt->pid_file); free(opt); } static void close_descriptors(void) { int min_fd = STDERR_FILENO + 1; #if HAVE_CLOSEFROM /* BSD and Solaris. */ (void)closefrom(min_fd); #elif defined(F_CLOSEM) /* AIX and IRIX. */ (void)fcntl(min_fd, F_CLOSEM, 0); #else int max_fd = MIN(sysconf(_SC_OPEN_MAX), /* Arbitrary limit: */ 1048576); int fd; for (fd = min_fd; fd < max_fd; fd++) (void)close(fd); #endif } static void drop_privileges(const char *user, const char *new_root) { struct passwd *pw; errno = 0; if (user != NULL) { if ((pw = getpwnam(user)) == NULL) { if (errno == 0) die("Cannot find user %s", user); else die("Cannot lookup user %s: %m", user); } if (initgroups(user, pw->pw_gid) == -1) die("Cannot set up group list for user %s: %m", user); } if (new_root != NULL && (chroot(new_root) == -1 || chdir("/") == -1)) die("Cannot change root directory to %s: %m", new_root); if (user != NULL && (setgid(pw->pw_gid) == -1 || setuid(pw->pw_uid) == -1)) die("Cannot switch to user %s: %m", user); } static void remove_pidfile(void) { if (pid_file != NULL && pidfile_remove(pfh) == -1) { error("Cannot remove %s: %m", pid_file); pid_file = NULL; /* Don't retry removing the PID file. */ } } static void forget_config(void) { if (cfg != NULL) { unsigned int i, n_auth_blocks = cfg_size(cfg, "authorize"); for (i = 0; i < n_auth_blocks; i++) { cfg_t *auth = cfg_getnsec(cfg, "authorize", i); if (cfg_size(auth, "password") > 0) { char *password = cfg_getstr(auth, "password"); (void)memset(password, 0, strlen(password)); } } cfg_free(cfg); } } static void stop_keep_alive(void) { if (ev_is_active(&keep_alive_watcher)) ev_timer_stop(EV_DEFAULT_UC_ &keep_alive_watcher); } static void notify_systemd(void) { char *usec; ev_tstamp sec; if ((usec = getenv("WATCHDOG_USEC")) != NULL && (sec = (ev_tstamp)atol(usec) / 1000 / 1000) > 0.0) { /* * The sd_notify() man page says: "It is recommended to send * this message if the WATCHDOG_USEC= environment variable has * been set for the service process, in every half the time * interval that is specified in the variable." Due to our * paranoia, we use an even shorter interval. */ sec /= 2.5; ev_timer_init(&keep_alive_watcher, keep_alive_cb, sec, sec); ev_timer_start(EV_DEFAULT_UC_ &keep_alive_watcher); if (atexit(stop_keep_alive) != 0) die("Cannot register function to be called on exit"); debug("Sending keep-alive messages every %.1f seconds", (double)sec); } (void)sd_notify(0, "READY=1"); } static void keep_alive_cb(EV_P_ ev_timer *w __attribute__((__unused__)), int revents __attribute__((__unused__))) { debug("Sending keep-alive message to init system"); (void)sd_notify(0, "WATCHDOG=1"); } static void signal_cb(EV_P_ ev_signal *w, int revents __attribute__((__unused__))) { const char *sig_string; ev_signal_stop(EV_A_ &sighup_watcher); ev_signal_stop(EV_A_ &sigint_watcher); ev_signal_stop(EV_A_ &sigterm_watcher); switch (w->signum) { case SIGHUP: sig_string = "SIGHUP"; break; case SIGINT: sig_string = "SIGINT"; break; case SIGTERM: sig_string = "SIGTERM"; break; default: sig_string = "unknown signal"; /* Huh? */ } notice("Received %s, shutting down connections", sig_string); ev_break(EV_A_ EVBREAK_ALL); if (w->signum == SIGHUP) restart = true; } static void usage(int status) { (void)fprintf(status == EXIT_SUCCESS ? stdout : stderr, "Usage: %s []\n\n" "Options:\n" " -b Bind to .\n" " -C Submit commands into the specified .\n" " -c Use the specified configuration .\n" " -F Don't detach from the controlling terminal.\n" " -h Print this usage information and exit.\n" " -l Set the specified log .\n" " -P Write the PID into the specified .\n" " -S Write messages to syslog and standard error.\n" " -s Write messages to syslog.\n" " -V Print version information and exit.\n", getprogname()); exit(status); } /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/src/server/server.c000066400000000000000000000212531344421036200164570ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #if HAVE_CONFIG_H # include #endif #if HAVE_AIO_INIT # include #endif #include #include #include #if HAVE_STRINGS_H # include #endif #include #include "auth.h" #include "fifo.h" #include "log.h" #include "server.h" #include "system.h" #include "tls.h" #include "util.h" #include "wrappers.h" struct server_state_s { /* This is typedef'd to `server_state' in server.h. */ tls_server_state *tls_server; fifo_state *fifo; size_t max_command_size; }; typedef struct { server_state *ctx; size_t input_length; } connection_state; static void handle_connect(tls_state *); static void handle_handshake(tls_state * restrict, char * restrict); static void handle_connection(tls_state * restrict, char * restrict); static void handle_push(tls_state * restrict, char * restrict); static void handle_error(tls_state *); static void handle_timeout(tls_state *); static void handle_line_too_long(tls_state *); static void send_response(tls_state * restrict, const char * restrict); static void bail(tls_state * restrict, const char * restrict, ...) __attribute__((__format__(__printf__, 2, 3))); static bool client_exited(tls_state * restrict, const char * restrict); static void connection_stop(tls_state *); /* * Exported functions. */ server_state * server_start(const char * restrict listen, const char * restrict ciphers, const char * restrict command_file, const char * restrict temp_directory, size_t max_command_size, size_t max_queue_size, ev_tstamp timeout) { server_state *ctx = xmalloc(sizeof(server_state)); #if HAVE_AIO_INIT struct aioinit ai; (void)memset(&ai, 0, sizeof(ai)); # if HAVE_STRUCT_AIOINIT_AIO_THREADS ai.aio_threads = 2; # endif # if HAVE_STRUCT_AIOINIT_AIO_NUM ai.aio_num = 2; # endif # if HAVE_STRUCT_AIOINIT_AIO_LOCKS ai.aio_locks = 0; # endif # if HAVE_STRUCT_AIOINIT_AIO_USEDBA ai.aio_usedba = 0; # endif # if HAVE_STRUCT_AIOINIT_AIO_DEBUG ai.aio_debug = 0; # endif # if HAVE_STRUCT_AIOINIT_AIO_NUMUSERS ai.aio_numusers = 0; # endif # if HAVE_STRUCT_AIOINIT_AIO_IDLE_TIME ai.aio_idle_time = 1; # endif aio_init(&ai); #endif ctx->max_command_size = max_command_size; ctx->fifo = fifo_start(command_file, temp_directory, max_queue_size); ctx->tls_server = tls_server_start(listen, ciphers, timeout, handle_connect, check_psk); ctx->tls_server->data = ctx; return ctx; } void server_stop(server_state *ctx) { tls_server_stop(ctx->tls_server); fifo_stop(ctx->fifo); free(ctx); } /* * Static functions. */ static void handle_connect(tls_state *tls) { connection_state *connection = xmalloc(sizeof(connection_state)); connection->ctx = tls->data; tls->data = connection; tls_on_timeout(tls, handle_timeout); tls_on_error(tls, handle_error); tls_on_line_too_long(tls, handle_line_too_long); tls_read_line(tls, handle_handshake); } static void handle_handshake(tls_state * restrict tls, char * restrict line) { char *args[3]; info("%s C: %s", tls->peer, line); if (strncasecmp("MOIN", line, 4) == 0) { if (!parse_line(line, args, 3)) { warning("Cannot parse MOIN request from %s", tls->peer); send_response(tls, "FAIL Cannot parse MOIN request"); tls_read_line(tls, handle_handshake); } else if (atoi(args[1]) <= 0) { warning("Expected protocol version from %s", tls->peer); send_response(tls, "FAIL Expected protocol version"); tls_read_line(tls, handle_handshake); } else { debug("MOIN handshake successful"); tls_set_connection_id(tls, args[2]); send_response(tls, "MOIN 1"); tls_read_line(tls, handle_connection); } } else if (strncasecmp("PING", line, 4) == 0) { send_response(tls, "PONG 1"); tls_shutdown(tls); connection_stop(tls); } else if (!client_exited(tls, line)) { warning("Expected MOIN or PING or BAIL from %s", tls->peer); send_response(tls, "FAIL Expected MOIN or PING or BAIL"); tls_read_line(tls, handle_handshake); } free(line); } static void handle_connection(tls_state * restrict tls, char * restrict line) { connection_state *connection = tls->data; char *args[2]; int data_size; info("%s C: %s", tls->peer, line); if (strncasecmp("NOOP", line, 4) == 0) send_response(tls, "OKAY"); else if (strncasecmp("PUSH", line, 4) == 0) { if (!parse_line(line, args, 2)) { warning("Cannot parse PUSH request from %s", tls->peer); send_response(tls, "FAIL Cannot parse PUSH request"); tls_read_line(tls, handle_connection); } else if ((data_size = atoi(args[1])) <= 0) { warning("Expected number of bytes from %s", tls->peer); send_response(tls, "FAIL Expected number of bytes"); tls_read_line(tls, handle_connection); } else if (connection->ctx->max_command_size > 0 && (size_t)data_size > connection->ctx->max_command_size) { warning("Command from %s too long", tls->peer); send_response(tls, "FAIL PUSH data size too large"); tls_read_line(tls, handle_connection); } else { send_response(tls, "OKAY"); connection->input_length = (size_t)data_size; tls_read(tls, handle_push, connection->input_length); } } else if (!client_exited(tls, line)) { warning("Expected PUSH or NOOP or QUIT from %s", tls->peer); send_response(tls, "FAIL Expected PUSH or NOOP or QUIT"); tls_read_line(tls, handle_connection); } free(line); } static void handle_push(tls_state * restrict tls, char * restrict data) { connection_state *connection = tls->data; int width = connection->input_length > 0 && data[connection->input_length - 1] == '\n' ? (int)connection->input_length - 1 : (int)connection->input_length; info("%s C: %.*s", tls->peer, width, data); if (is_authorized(tls->id, data)) { notice("Queuing data from %s: %.*s", tls->peer, width, data); fifo_write(connection->ctx->fifo, data, connection->input_length, free); send_response(tls, "OKAY"); } else { warning("Refusing data from %s: %.*s", tls->peer, width, data); free(data); send_response(tls, "FAIL You're not authorized"); } tls_read_line(tls, handle_connection); } static void handle_error(tls_state *tls) { connection_stop(tls); } static void handle_timeout(tls_state *tls) { bail(tls, "Connection timed out"); } static void handle_line_too_long(tls_state *tls) { bail(tls, "Request line too long"); } static void send_response(tls_state * restrict tls, const char * restrict response) { info("%s S: %s", tls->peer, response); tls_write_line(tls, response); } static void bail(tls_state * restrict tls, const char * restrict fmt, ...) { va_list ap; char *message; va_start(ap, fmt); xvasprintf(&message, fmt, ap); va_end(ap); info("%s S: %s %s", tls->peer, "BAIL", message); tls_write(tls, "BAIL ", sizeof("BAIL ") - 1, NULL); tls_write_line(tls, message); tls_shutdown(tls); connection_stop(tls); free(message); } static bool client_exited(tls_state * restrict tls, const char * restrict line) { if (strncasecmp("QUIT", line, 4) == 0) { send_response(tls, "OKAY"); tls_shutdown(tls); connection_stop(tls); return true; } else if (strncasecmp("BAIL", line, 4) == 0) { error("%s said: %s", tls->peer, line); tls_shutdown(tls); connection_stop(tls); return true; } return false; } static void connection_stop(tls_state *tls) { connection_state *connection = tls->data; free(connection); } /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/src/server/server.h000066400000000000000000000035371344421036200164710ustar00rootroot00000000000000/* * Copyright (c) 2013 Holger Weiss * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef SERVER_H # define SERVER_H # if HAVE_CONFIG_H # include # endif # include # include "system.h" typedef struct server_state_s server_state; server_state *server_start(const char * restrict, const char * restrict, const char * restrict, const char * restrict, size_t, size_t, ev_tstamp); void server_stop(server_state *); #endif /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/tests/000077500000000000000000000000001344421036200140475ustar00rootroot00000000000000nsca-ng-1.6/tests/Makefile.am000066400000000000000000000062511344421036200161070ustar00rootroot00000000000000## Process this file with automake(1) to produce Makefile.in. ## Copyright (c) 2013 Holger Weiss ## All rights reserved. ## ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are met: ## ## 1. Redistributions of source code must retain the above copyright notice, ## this list of conditions and the following disclaimer. ## ## 2. Redistributions in binary form must reproduce the above copyright notice, ## this list of conditions and the following disclaimer in the documentation ## and/or other materials provided with the distribution. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ## AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ## ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE ## LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ## CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF ## SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ## INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ## CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ## ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ## POSSIBILITY OF SUCH DAMAGE. EXTRA_DIST = $(TESTSUITE) $(TESTSUITE_AT) package.m4 atlocal.in DISTCLEANFILES = atconfig # # Build test_nsca. # AM_CPPFLAGS = -I$(top_srcdir)/lib LDADD = ../lib/libcompat.a noinst_PROGRAMS = test_nsca # # Build the rest of our test suite (see the Autoconf manual). # TESTSUITE_AT = \ $(srcdir)/testsuite.at \ $(srcdir)/local.at \ $(srcdir)/basic.at \ $(srcdir)/input.at \ $(srcdir)/auth.at TESTSUITE = $(srcdir)/testsuite AUTOM4TE = $(SHELL) $(top_srcdir)/build-aux/missing --run autom4te AUTOTEST = $(AUTOM4TE) --language=autotest check-local: $(TESTSUITE) atconfig atlocal test_nsca $(AM_V_at)$(SHELL) '$(TESTSUITE)' $(TESTSUITEFLAGS) installcheck-local: $(TESTSUITE) atconfig atlocal test_nsca $(AM_V_at)$(SHELL) '$(TESTSUITE)' AUTOTEST_PATH='tests:$(sbindir)' \ $(TESTSUITEFLAGS) clean-local: test ! -f '$(TESTSUITE)' || $(SHELL) '$(TESTSUITE)' --clean $(TESTSUITE): $(TESTSUITE_AT) $(srcdir)/package.m4 $(AM_V_GEN)$(AUTOTEST) -I '$(srcdir)' -o $@.tmp $@.at $(AM_V_at)mv $@.tmp $@ # The `:;' works around a Bash 3.2 bug when the output is not writable. $(srcdir)/package.m4: $(top_srcdir)/configure.ac $(AM_V_at):;{ \ echo '# Signature of the current package.' && \ echo 'm4_define([AT_PACKAGE_NAME],' && \ echo ' [$(PACKAGE_NAME)])' && \ echo 'm4_define([AT_PACKAGE_TARNAME],' && \ echo ' [$(PACKAGE_TARNAME)])' && \ echo 'm4_define([AT_PACKAGE_VERSION],' && \ echo ' [$(PACKAGE_VERSION)])' && \ echo 'm4_define([AT_PACKAGE_STRING],' && \ echo ' [$(PACKAGE_STRING)])' && \ echo 'm4_define([AT_PACKAGE_BUGREPORT],' && \ echo ' [$(PACKAGE_BUGREPORT)])'; \ echo 'm4_define([AT_PACKAGE_URL],' && \ echo ' [$(PACKAGE_URL)])'; \ } >'$(srcdir)/package.m4' nsca-ng-1.6/tests/atlocal.in000066400000000000000000000027001344421036200160150ustar00rootroot00000000000000# @configure_input@ # Copyright (c) 2013 Holger Weiss # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. nsca_pipe_buf='@nsca_pipe_buf@' # vim:set joinspaces noexpandtab textwidth=80: nsca-ng-1.6/tests/auth.at000066400000000000000000000055461344421036200153500ustar00rootroot00000000000000# Copyright (c) 2013 Holger Weiss # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AT_BANNER([Authentication and authorization.]) AT_SETUP([Incorrect password]) NSCA_CHECK([jupiter 0 jupiter is alive], [], [stderr], [], [], [password = "incorrect"], [], [1]) AT_CHECK([[grep '^send_nsca: \[FATAL\] TLS error (127.0.0.1): ' stderr]], [0], [ignore]) AT_CLEANUP AT_SETUP([Unauthorized submission]) NSCA_CHECK([jupiter 0 jupiter is alive], [], [[send_nsca: [FATAL] Server said: FAIL You're not authorized]], [], [], [], [authorize "*" { password = "forty-two" commands = "none" }], [1]) AT_CLEANUP AT_SETUP([Legitimate host check result]) NSCA_CHECK([jupiter 0 jupiter is alive], [PROCESS_HOST_CHECK_RESULT;jupiter;0;jupiter is alive], [], [], [], [], [authorize "*" { password = "forty-two" hosts = "jupiter" }]) AT_CLEANUP AT_SETUP([Legitimate service check result]) NSCA_CHECK([jupiter disk 0 disk is fine], [PROCESS_SERVICE_CHECK_RESULT;jupiter;disk;0;disk is fine], [], [], [], [], [authorize "*" { password = "forty-two" services = "disk" }]) AT_CLEANUP AT_SETUP([Malicious host check result]) NSCA_CHECK([saturn 0 jupiter;0;tricked you!], [], [[send_nsca: [FATAL] Server said: FAIL You're not authorized]], [], [], [], [authorize "*" { password = "forty-two" hosts = "jupiter" }], [1]) AT_CLEANUP AT_SETUP([Malicious service check result]) NSCA_CHECK([jupiter http 0 disk;0;tricked you!], [], [[send_nsca: [FATAL] Server said: FAIL You're not authorized]], [], [], [], [authorize "*" { password = "forty-two" services = "disk" }], [1]) AT_CLEANUP dnl vim:set joinspaces textwidth=80 filetype=m4: nsca-ng-1.6/tests/basic.at000066400000000000000000000046561344421036200154710ustar00rootroot00000000000000# Copyright (c) 2013 Holger Weiss # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AT_BANNER([Basic functionality.]) AT_SETUP([Host check result]) NSCA_CHECK([jupiter 0 jupiter is alive], [PROCESS_HOST_CHECK_RESULT;jupiter;0;jupiter is alive]) AT_CLEANUP AT_SETUP([Host check result, special delimiter]) NSCA_CHECK([jupiter/0/jupiter is alive], [PROCESS_HOST_CHECK_RESULT;jupiter;0;jupiter is alive], [], [-d /]) AT_CLEANUP AT_SETUP([Service check result]) NSCA_CHECK([saturn http 0 HTTP is happy], [PROCESS_SERVICE_CHECK_RESULT;saturn;http;0;HTTP is happy]) AT_CLEANUP AT_SETUP([Service check result, special delimiter]) NSCA_CHECK([saturn/http/0/HTTP is happy], [PROCESS_SERVICE_CHECK_RESULT;saturn;http;0;HTTP is happy], [], [-d /]) AT_CLEANUP AT_SETUP([Monitoring command]) NSCA_CHECK([[[1360095440]] ADD_HOST_COMMENT;jupiter;1;John Doe;Useless comment], [ADD_HOST_COMMENT;jupiter;1;John Doe;Useless comment], [], [-C]) AT_CLEANUP AT_SETUP([Monitoring command, no timestamp]) NSCA_CHECK([ADD_HOST_COMMENT;jupiter;1;John Doe;Useless comment], [ADD_HOST_COMMENT;jupiter;1;John Doe;Useless comment], [], [-C]) AT_CLEANUP dnl vim:set joinspaces textwidth=80 filetype=m4: nsca-ng-1.6/tests/input.at000066400000000000000000000073111344421036200155360ustar00rootroot00000000000000# Copyright (c) 2013 Holger Weiss # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AT_BANNER([Unusual input.]) AT_SETUP([Multiline check result]) NSCA_CHECK([jupiter 0 jupiter is alive], [PROCESS_HOST_CHECK_RESULT;jupiter;0;jupiter\n is alive]) AT_CLEANUP AT_SETUP([Multiple check results]) printf 'jupiter\t0\tresult 1\n' >input printf '\27' >>input printf 'jupiter\t0\tresult 2\n' >>input printf '\27' >>input printf 'jupiter\t0\tresult 3\n' >>input NSCA_CHECK([input], [dnl PROCESS_HOST_CHECK_RESULT;jupiter;0;result 1 PROCESS_HOST_CHECK_RESULT;jupiter;0;result 2 PROCESS_HOST_CHECK_RESULT;jupiter;0;result 3], [], [], [], [], [], [0], [3]) AT_CLEANUP AT_SETUP([Multiple results, colon-separated]) printf 'jupiter\t0\tresult 1\n' >input printf ':' >>input printf 'jupiter\t0\tresult 2\n' >>input printf ':' >>input printf 'jupiter\t0\tresult 3\n' >>input NSCA_CHECK([input], [dnl PROCESS_HOST_CHECK_RESULT;jupiter;0;result 1 PROCESS_HOST_CHECK_RESULT;jupiter;0;result 2 PROCESS_HOST_CHECK_RESULT;jupiter;0;result 3], [], [-e :], [], [], [], [0], [3]) AT_CLEANUP AT_SETUP([Multiple monitoring commands]) cat >input <<'NSCA_EOF' PROCESS_HOST_CHECK_RESULT;saturn;0;result 1 PROCESS_HOST_CHECK_RESULT;saturn;0;result 2 PROCESS_HOST_CHECK_RESULT;saturn;0;result 3 NSCA_EOF ln input expout NSCA_CHECK([input], [expout], [], [-C], [], [], [], [0], [3]) AT_CLEANUP AT_SETUP([Result with trailing ETB and newline]) printf 'jupiter\t0\tjupiter is alive\n' >input printf '\27\n' >>input NSCA_CHECK([input], [PROCESS_HOST_CHECK_RESULT;jupiter;0;jupiter is alive]) AT_CLEANUP AT_SETUP([Incorrect input format]) NSCA_CHECK([garbage], [], [[send_nsca: [FATAL] Input format incorrect, see the send_nsca(8) man page]], [], [], [], [], [1]) AT_CLEANUP AT_SETUP([Data size exceeds max_command_size]) NSCA_CHECK([jupiter 0 jupiter is alive], [], [[send_nsca: [FATAL] Server said: FAIL PUSH data size too large]], [], [], [], [max_command_size = 10 authorize "*" { password = "forty-two" commands = ".*" }], [1]) AT_CLEANUP AT_SETUP([Data size exceeds PIPE_BUF]) cat >input <server.cfg < # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # Initialize Autotest. AT_INIT # Enable colored test output. AT_COLOR_TESTS # Log the `--version' of our programs. AT_TESTED([test_nsca]) # NSCA_CHECK([INPUT], [STDOUT], [STDERR], [CLIENT-FLAGS], [SERVER-FLAGS], # [CLIENT-CONF], [SERVER-CONF], [STATUS = 0], [COMMANDS = 1]) # ----------------------------------------------------------------------- # Transmit the given INPUT to the nsca-ng(8) server using send_nsca(8). If the # INPUT consists of multiple monitoring commands, the number of COMMANDS must be # specified. The data written to the FIFO by the server is then checked against # STDOUT, send_nsca(8)'s standard error output is checked against STDERR, and # the exit status is checked against STATUS. Non-default CLIENT-CONF and/or # SERVER-CONF contents may be specified. See also the AT_CHECK documentation. m4_define([NSCA_CHECK], [ dnl Put together the command line. m4_define([nsca_cmd_line], [ * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #if HAVE_CONFIG_H # include #endif #include "system.h" #define PROGRAM_NAME "test_nsca" #define LISTEN_ADDRESS "127.0.0.1" #define LISTEN_PORT "12345" /* Don't interfere with a poduction server. */ #define COMMAND_FILE "fifo" #define SERVER_PID_FILE "server.pid" #define CLIENT_CONF_FILE "client.cfg" #define SERVER_CONF_FILE "server.cfg" #define TIMEOUT 10 #define DEFAULT_CLIENT_CONF "# Created by " PROGRAM_NAME "\n" \ "password = \"forty-two\"\n" #define DEFAULT_SERVER_CONF "# Created by " PROGRAM_NAME "\n" \ "authorize \"*\" {\n" \ " password = \"forty-two\"\n" \ " commands = \".*\"\n" \ "}\n" #define CLIENT_COMMAND_LINE "send_nsca " \ "-c `pwd`/" CLIENT_CONF_FILE " " \ "-H " LISTEN_ADDRESS " " \ "-p " LISTEN_PORT #define SERVER_COMMAND_LINE "nsca-ng " \ "-c `pwd`/" SERVER_CONF_FILE " " \ "-C `pwd`/" COMMAND_FILE " " \ "-P `pwd`/" SERVER_PID_FILE " " \ "-b " LISTEN_ADDRESS ":" LISTEN_PORT " " \ "-l 0" #include #include #include #include #include #include #include #include #include #include #include #include static long expected_num_lines = 1; static volatile char got_signal = 0; static void get_options(int, char **); static char *join(const char *, const char *); static void run_command(const char *); static void write_file(const char *, const char *); static void create_fifo(void); static void cat_fifo(long); static void remove_fifo(void); static void kill_server(void); static void print_usage(FILE *); static void print_version(void); static void handle_signal(int); static void xatexit(void (*)(void)); static void xsigaction(int, const struct sigaction * restrict, struct sigaction * restrict); static void __attribute__((__format__(__printf__, 1, 2), __noreturn__)) die(const char *, ...); int main(int argc, char **argv) { struct sigaction sa; #ifndef __gnu_hurd__ int fd; #endif get_options(argc, argv); sa.sa_flags = 0; sa.sa_handler = handle_signal; (void)sigemptyset(&sa.sa_mask); xsigaction(SIGINT, &sa, NULL); xsigaction(SIGTERM, &sa, NULL); xsigaction(SIGALRM, &sa, NULL); (void)alarm(TIMEOUT); if (access(CLIENT_CONF_FILE, F_OK) == -1) write_file(CLIENT_CONF_FILE, DEFAULT_CLIENT_CONF); if (access(SERVER_CONF_FILE, F_OK) == -1) write_file(SERVER_CONF_FILE, DEFAULT_SERVER_CONF); create_fifo(); xatexit(remove_fifo); /* * Make sure there's a FIFO reader when the server starts up, in order * to avoid having to wait ten seconds until the server notices that we * opened the FIFO for reading (in the cat_fifo() function). GNU Hurd * doesn't like this trick, though. */ #ifndef __gnu_hurd__ if ((fd = open(COMMAND_FILE, O_RDONLY | O_NONBLOCK)) == -1) die("Cannot open %s: %s", COMMAND_FILE, strerror(errno)); #endif run_command(join(SERVER_COMMAND_LINE, getenv("NSCA_SERVER_FLAGS"))); xatexit(kill_server); run_command(join(CLIENT_COMMAND_LINE, getenv("NSCA_CLIENT_FLAGS"))); cat_fifo(expected_num_lines); #ifndef __gnu_hurd__ (void)close(fd); #endif return EXIT_SUCCESS; } static void get_options(int argc, char **argv) { extern int optind; extern char *optarg; int option; if (argc == 2) { if (strcmp(argv[1], "--help") == 0) { print_usage(stdout); exit(EXIT_SUCCESS); } if (strcmp(argv[1], "--version") == 0) { print_version(); exit(EXIT_SUCCESS); } } while ((option = getopt(argc, argv, "hl:V")) != -1) switch (option) { case 'h': print_usage(stdout); exit(EXIT_SUCCESS); case 'l': if ((expected_num_lines = atol(optarg)) < 1) die("-l must be a number greater than zero"); break; case 'V': print_version(); exit(EXIT_SUCCESS); default: print_usage(stderr); exit(EXIT_FAILURE); } if (argc - optind > 0) die("Unexpected non-option argument: %s", argv[optind]); } static char * join(const char *part1, const char *part2) { static char joined[4096]; size_t len1 = strlen(part1); if (len1 > sizeof(joined)) die("Command line too long"); (void)strcpy(joined, part1); if (part2 != NULL) { size_t len2 = strlen(part2); if (len1 + 1 + len2 + 1 > sizeof(joined)) die("Command line too long"); (void)strcat(joined, " "); (void)strcat(joined, part2); } return joined; } static void run_command(const char *command) { int status; if ((status = system(command)) == -1) die("Cannot execute %s: %s", command, strerror(errno)); if (WIFEXITED(status) && WEXITSTATUS(status) == 127) exit(77); /* Tell Autotest to skip this test. */ if (status != 0) exit(1); } static void write_file(const char *file, const char *contents) { FILE *f; if ((f = fopen(file, "w")) == NULL) die("Cannot open %s: %s", file, strerror(errno)); if (fputs(contents, f) == EOF) die("Cannot write %s: %s", file, strerror(errno)); if (fclose(f) == EOF) die("Cannot close %s: %s", file, strerror(errno)); } static void create_fifo(void) { if (mkfifo(COMMAND_FILE, 0666) == -1) (void)fprintf(stderr, "%s: Cannot create %s: %s\n", PROGRAM_NAME, COMMAND_FILE, strerror(errno)); } static void cat_fifo(long n_lines) { FILE *fifo; int c; enum { STATE_EAT_TIMESTAMP, STATE_PRINT_COMMAND } state = STATE_EAT_TIMESTAMP; do fifo = fopen(COMMAND_FILE, "r"); while (fifo == NULL && errno == EINTR); /* Happens on GNU Hurd. */ if (fifo == NULL) die("Cannot open %s: %s", COMMAND_FILE, strerror(errno)); while ((c = getc(fifo)) != EOF) { if (state == STATE_EAT_TIMESTAMP) { if (c == ' ') state = STATE_PRINT_COMMAND; else if (c != '[' && !isdigit(c) && c != ']') die("Got unexpected `%c' from FIFO", c); } else { if (putchar(c) == EOF) die("Cannot write to stdout: %s", strerror(errno)); if (c == '\n') { if (--n_lines > 0) state = STATE_EAT_TIMESTAMP; else break; } } } if (ferror(fifo)) die("Cannot read %s: %s", COMMAND_FILE, got_signal ? "Interrupted" : strerror(errno)); } static void remove_fifo(void) { if (unlink(COMMAND_FILE) == -1) (void)fprintf(stderr, "%s: Cannot remove %s: %s\n", PROGRAM_NAME, COMMAND_FILE, strerror(errno)); } static void kill_server(void) { FILE *f; char buf[64]; pid_t pid; /* * To minimize the risk that the server process interferes with any * following test(s), we KILL the process instead of using the TERM * signal. */ if ((f = fopen(SERVER_PID_FILE, "r")) == NULL) { (void)fprintf(stderr, "%s: Cannot open %s: %s\n", PROGRAM_NAME, SERVER_PID_FILE, strerror(errno)); return; } if (fgets(buf, sizeof(buf), f) == NULL) (void)fprintf(stderr, "%s: Cannot read %s: %s\n", PROGRAM_NAME, SERVER_PID_FILE, ferror(f) ? strerror(errno) : "EOF"); else if ((pid = (pid_t)atol(buf)) < 1) (void)fprintf(stderr, "%s: PID file %s contains garbage\n", PROGRAM_NAME, SERVER_PID_FILE); else if (kill(pid, SIGKILL) == -1) (void)fprintf(stderr, "%s: Cannot kill server PID %lu: %s\n", PROGRAM_NAME, (unsigned long)pid, strerror(errno)); if (fclose(f) == EOF) (void)fprintf(stderr, "%s: Cannot close %s: %s\n", PROGRAM_NAME, SERVER_PID_FILE, strerror(errno)); } static void print_usage(FILE *stream) { (void)fprintf(stream, "Usage: %s []\n\n" "Options:\n" " -h Print this usage information and exit.\n" " -l Read this number of lines from FIFO (default: 1).\n" " -V Print version information and exit.\n", PROGRAM_NAME); } static void print_version(void) { (void)system("send_nsca -V"); (void)system("nsca-ng -V"); #if HAVE_POSIX_AIO (void)puts("The NSCA-ng server uses the POSIX AIO API on this system."); #endif } static void handle_signal(int signal_number __attribute__((__unused__))) { got_signal = 1; } static void xatexit(void function(void)) { if (atexit(function) != 0) die("Cannot register exit function"); } static void xsigaction(int signal_number, const struct sigaction * restrict action, struct sigaction * restrict old_action) { if (sigaction(signal_number, action, old_action) == -1) die("Cannot set handler for signal %d: %s", signal_number, strerror(errno)); } static void die(const char *format, ...) { va_list ap; (void)fputs(PROGRAM_NAME ": ", stderr); va_start(ap, format); (void)vfprintf(stderr, format, ap); va_end(ap); (void)putc('\n', stderr); exit(EXIT_FAILURE); } /* vim:set joinspaces noexpandtab textwidth=80 cinoptions=(4,u0: */ nsca-ng-1.6/tests/testsuite.at000066400000000000000000000027211344421036200164300ustar00rootroot00000000000000# Copyright (c) 2013 Holger Weiss # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. m4_include([basic.at]) m4_include([input.at]) m4_include([auth.at]) dnl vim:set joinspaces textwidth=80 filetype=m4: