pax_global_header00006660000000000000000000000064147272454410014524gustar00rootroot0000000000000052 comment=bb3b96b99668e544618c5aec427c1f4b6b9ee9bb catatonit-0.2.1/000077500000000000000000000000001472724544100135125ustar00rootroot00000000000000catatonit-0.2.1/.github/000077500000000000000000000000001472724544100150525ustar00rootroot00000000000000catatonit-0.2.1/.github/workflows/000077500000000000000000000000001472724544100171075ustar00rootroot00000000000000catatonit-0.2.1/.github/workflows/ci.yml000066400000000000000000000022361472724544100202300ustar00rootroot00000000000000# SPDX-License-Identifier: GPL-2.0-or-later # # catatonit: a container init so simple it's effectively brain-dead # Copyright (C) 2018-2023 SUSE LLC # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . name: ci on: push: branches: [ main ] pull_request: branches: [ main ] release: types: [ published ] schedule: - cron: '0 0 * * *' jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - run: | autoreconf -fi && ./configure && make file ./catatonit | grep 'statically linked' # TODO: Add unit tests. catatonit-0.2.1/.gitignore000066400000000000000000000004061472724544100155020ustar00rootroot00000000000000# Our binary. /catatonit /release/ # Autoconf generated files for binaries. /Makefile /Makefile.in /aclocal.m4 /autom4te.cache/ /config.* !/config.h.in /compile /configure /depcomp /install-sh /missing /ltmain.sh /libtool /m4/ /stamp-h? .deps/ .dirstamp *.o *~ catatonit-0.2.1/.lgtm000066400000000000000000000000401472724544100144500ustar00rootroot00000000000000approvals = 1 pattern = "^LGTM" catatonit-0.2.1/CHANGELOG.md000066400000000000000000000063341472724544100153310ustar00rootroot00000000000000# Changelog # All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). ## [Unreleased] ## ## [0.2.1] - 2024-12-14 ## ### Fixed ### * `catatonit` will now `chdir` to `/` in order to avoid keeping the directory it was running in busy. This was causing issues with rootless Podman's pause container keeping some `/home/...` paths busy and blocking `umount`s. (#28, #33) ## [0.2.0] - 2023-10-02 ### Changed ### * `catatonit` has now been relicensed to GPLv2-or-later. (#27) ## [0.1.7] - 2021-11-01 ### Added ### * Running `catatonit` as the only process in a pause container (i.e. no children are spawned, `catatonit` just runs in a busy loop) is now supported in the form of `catatonit -P`. ## [0.1.6] - 2021-09-16 ### Fixed ### * File descriptors passed to the pid2 process were not closed by `catatonit` after starting pid2 which could lead to several negative scenarios (such as resources being kept around unnecessarily). Now `catatonit` will close all `>=3` (i.e. non-stdio) file descriptors after spawning the child process. (#12, #14) * Container-based socket activation support with runc sets `LISTEN_PID=1` when forwarding socket-activation-related file descriptors, but with `catatonit` this doesn't work because `catatonit` is pid1 not the actual container process. As such, `catatonit` will now rewrite the `LISTEN_PIDS` environment variable to equal the pid2 pid if `LISTEN_PIDS` is equal to the pid of `catatonit`. (#13, #15) ## [0.1.5] - 2020-03-03 ### Fixed ### * Some cases where catatonit could hang if pid1 died and the death signal was coalesced are now correctly handled. (#4) ## [0.1.4] - 2019-01-29 ### Added ### * We now support the `-g` option (from `tini`) for signals to be sent to the process group. This is necessary for Rook to switch to `catatonit`. ## [0.1.3] - 2018-04-18 ### Fixed ## * Improve Docker compatibility by reporting ourselves as `tini` when providing version information from `catatonit -V`. ## [0.1.2] - 2018-03-29 ### Changed ### * Minor cosmetic changes, as we are now an openSUSE project. ## [0.1.1] - 2018-03-27 ### Fixed ### * Add a small fix for the libtool requirements to allow building catatonit on older distributions. ## 0.1.0 - 2018-03-27 This is the first release of catatonit. At this point it works fully (to the best of my ability) and is incredibly simple to use and maintain. [Unreleased]: https://github.com/openSUSE/catatonit/compare/v0.2.1...HEAD [0.2.1]: https://github.com/openSUSE/catatonit/compare/v0.2.0...v0.2.1 [0.2.0]: https://github.com/openSUSE/catatonit/compare/v0.1.7...v0.2.0 [0.1.7]: https://github.com/openSUSE/catatonit/compare/v0.1.6...v0.1.7 [0.1.6]: https://github.com/openSUSE/catatonit/compare/v0.1.5...v0.1.6 [0.1.5]: https://github.com/openSUSE/catatonit/compare/v0.1.4...v0.1.5 [0.1.4]: https://github.com/openSUSE/catatonit/compare/v0.1.3...v0.1.4 [0.1.3]: https://github.com/openSUSE/catatonit/compare/v0.1.2...v0.1.3 [0.1.2]: https://github.com/openSUSE/catatonit/compare/v0.1.1...v0.1.2 [0.1.1]: https://github.com/openSUSE/catatonit/compare/v0.1.0...v0.1.1 catatonit-0.2.1/COPYING000066400000000000000000000432541472724544100145550ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. catatonit-0.2.1/MAINTAINERS000066400000000000000000000000531472724544100152050ustar00rootroot00000000000000Aleksa Sarai (@cyphar) catatonit-0.2.1/Makefile.am000066400000000000000000000015551472724544100155540ustar00rootroot00000000000000# SPDX-License-Identifier: GPL-2.0-or-later # # catatonit: a container init so simple it's effectively brain-dead # Copyright (C) 2018-2023 SUSE LLC # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . bin_PROGRAMS = catatonit catatonit_LDFLAGS = -all-static catatonit_SOURCES = catatonit.c catatonit-0.2.1/README.md000066400000000000000000000101261472724544100147710ustar00rootroot00000000000000## catatonit ## [![Build Status](https://github.com/openSUSE/catatonit/actions/workflows/ci.yml/badge.svg)](https://github.com/openSUSE/catatonit/actions/workflows/ci.yml) A container init that is so simple it's effectively brain-dead. This is a rewrite of [initrs][initrs] in C, because we found that it is not possible to statically compile Rust binaries without using musl. That was, in turn, a reimplementation of other container inits like `tini` and `dumb-init`. The reason for re-implementing `docker-init` is because it appears as though all of the other implementations do not handle signals as correctly as they should. In particular, they all appear to make use of `sigwait(2)` (`tini` does a `sigtimedwait(2)` for an interval and then will do a `waitpid(2)` even if it didn't detect a `SIGCHLD`). `catatonit` uses `signalfd(2)`, which [has its own warts][signalfd-broken], but the improvements over `sigwait(2)` are significant in terms of stability. Ideally we would just write a patch for the other projects to use `signalfd(2)` rather than creating a new project, but after some time spent looking at `tini` and `dumb-init` we felt that such patches would be closer to full rewrites. In addition, the purpose of `catatonit` is to only support the key usage by `docker-init` which is `/dev/init -- `. With few exceptions, no other features will be added. [initrs]: https://github.com/cyphar/initrs [signalfd-broken]: https://ldpreload.com/blog/signalfd-is-useless ### Usage ### catatonit has identical usage to other basic `docker-init`'s -- you give it the command and list of arguments to that command. If you install `catatonit` to `/usr/bin/docker-init`, `docker run --init` will use `catatonit` as its container pid1. Alternatively, you can configure the Docker daemon to use `catatonit` without deleting any previously installed `/usr/bin/docker-init` by using `--init-path` (or adding an `init-path` setting in `/etc/docker/daemon.json`). Podman has similar options. Catatonit supports a very limit subset of features, in order to keep the code as simple as possible: * If catatonit is not pid1 (in other words, you are not in a PID namespace), it will try to use the sub-reaper support in the kernel to act as a "pseudo-init" for the process you requested. * You can pass `-g` if you want signals to be forwarded to the entire process group of your spawned process (otherwise it's just forwarded to the process spawned). * If you wish to use catatonit as a convenient pause container (do not spawn a child process nor do any signal handling), you can pass `-P`. If you want to include `catatonit` in your images, you can conveniently add it to your Dockerfile as an entrypoint: ```dockerfile # Runs "catatonit -- /my/amazing/script --with --args" ENTRYPOINT ["catatonit", "--"] # or if you use --rewrite or other cli flags # ENTRYPOINT ["catatonit", "--rewrite", "2:3", "--"] CMD ["/my/amazing/script", "--with", "--args"] ``` ### Installation ### catatonit uses autotools for building, so building is a fairly standard: ``` % ./autogen.sh % ./configure % make % sudo make install ``` Note that this install the `catatonit` binary to `/usr/bin/catatonit`. If you want to use `docker run --init` you may need to symlink `/usr/bin/docker-init` to `catatonit` or configure Docker to use `catatonit`. ### License ### catatonit is licensed under the GNU General Public License version 2 or later. ``` catatonit: a container init so simple it's effectively brain-dead Copyright (C) 2018-2023 SUSE LLC This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . ``` catatonit-0.2.1/autogen.sh000077500000000000000000000000401472724544100155050ustar00rootroot00000000000000#!/bin/sh exec autoreconf -fiv catatonit-0.2.1/catatonit.c000066400000000000000000000376601472724544100156600ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-2.0-or-later /* * catatonit: a container init so simple it's effectively brain-dead * Copyright (C) 2018-2023 SUSE LLC * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #define _GNU_SOURCE #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef HAVE_LINUX_CLOSE_RANGE_H # include #else # include #endif #include "config.h" static enum loglevel_t { LOG_FATAL = 0, LOG_ERROR = 1, LOG_WARN = 2, LOG_INFO = 3, LOG_DEBUG = 4, } global_log_level = LOG_ERROR; static void _log(enum loglevel_t level, char *fmt, ...) { va_list ap; int old_errno = errno; char *level_str = "*"; if (global_log_level < level) return; switch (level) { case LOG_FATAL: level_str = "FATAL"; break; case LOG_ERROR: default: level_str = "ERROR"; break; case LOG_WARN: level_str = "WARN"; break; case LOG_INFO: level_str = "INFO"; break; case LOG_DEBUG: level_str = "DEBUG"; break; } fprintf(stderr, "%s (%s:%d): ", level_str, PROGRAM_NAME, getpid()); va_start(ap, fmt); errno = old_errno; vfprintf(stderr, fmt, ap); va_end(ap); fprintf(stderr, "\n"); errno = old_errno; } static void usage(void) { fprintf(stderr, "usage: %s [-ghLPV] [--] [...]\n", PROGRAM_NAME); } static void help(void) { usage(); fprintf(stderr, "\n"); fprintf(stderr, "options:\n"); fprintf(stderr, " -g Forward signals to pid1's process group.\n"); fprintf(stderr, " -h Print this help page.\n"); fprintf(stderr, " -L Print license information.\n"); fprintf(stderr, " -P Run in pause mode (no program is run and quit on SIGINT).\n"); fprintf(stderr, " -V, --version Print version information.\n"); fprintf(stderr, "\n"); fprintf(stderr, "The source code can be found at <%s>.\n", PROGRAM_URL); fprintf(stderr, "For bug reporting instructions, please see: <%s>.\n", PROGRAM_BUGURL); } static void version(void) { // The name is intentional to make `docker-info` happy: docker is hard-coded // against `tini`. This is an (unfortunate) hack to make it work nicely with // catatonit. fprintf(stdout, "tini version %s_%s\n", PROGRAM_VERSION, PROGRAM_NAME); } static void license(void) { fprintf(stdout, "%s", PROGRAM_LICENSE); } #define LOG(level, ...) \ do { _log(level, __VA_ARGS__); } while (0) #define fatal(...) LOG(LOG_FATAL, __VA_ARGS__) #define error(...) LOG(LOG_ERROR, __VA_ARGS__) #define warn(...) LOG(LOG_WARN, __VA_ARGS__) #define info(...) LOG(LOG_INFO, __VA_ARGS__) #define debug(...) LOG(LOG_DEBUG, __VA_ARGS__) #define bail(...) \ do { error(__VA_ARGS__); exit(1); } while (0) #define bail_usage(...) \ do { error(__VA_ARGS__); usage(); exit(1); } while (0) /* * Set of signals that the kernel sends us if *we* screwed something up. We * don't want to forward these to the child, as it will just confuse them. If * we get one of these, we let ourselves die rather than just carrying on. */ int kernel_signals[] = {SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGABRT, SIGTRAP, SIGSYS}; #define ARRAY_LEN(arr) (sizeof(arr) / sizeof(*arr)) #ifndef HAVE_CLOSE_RANGE static int close_range(unsigned int fd, unsigned int max_fd, unsigned int flags) { # ifdef __NR_close_range return (int) syscall(__NR_close_range, fd, max_fd, flags); # else errno = ENOSYS; return -1; # endif } #endif /* * Close every fd >= n that is different from exclude_fd using close_range. */ static int close_range_fds_ge_than(int n, int exclude_fd) { int r, saved_errno = 0; /* exclude_fd is not in the [n, UINT_MAX] range. */ if (exclude_fd < n) return close_range(n, UINT_MAX, 0); /* exclude_fd is the first fd in the [n, UINT_MAX] range. */ if (exclude_fd == n) return close_range(n + 1, UINT_MAX, 0); /* exclude_fd is between n and UINT_MAX. */ errno = 0; r = close_range(n, exclude_fd - 1, 0); /* * attempt to close as many FDs as possible but return an error * if the close_range() failed. */ if (exclude_fd < UINT_MAX) { saved_errno = errno; r = close_range(exclude_fd + 1, UINT_MAX, 0); /* If the previous call failed, restore errno. */ if (saved_errno != 0) { r = -1; errno = saved_errno; } } return r; } /* * Close every fd >= n that is different from exclude_fd. */ static int close_fds_ge_than(int n, int exclude_fd) { struct dirent *next; int failures = 0; DIR *dir; int fd; int r; if (close_range_fds_ge_than(n, exclude_fd) == 0) return 0; /* Fallback when close_range fails. */ debug("close_range() failed, fallback to close() each open FD: %m"); dir = opendir("/proc/self/fd"); if (dir == NULL) { debug("cannot opendir /proc/self/fd: %m"); return -1; } fd = dirfd(dir); for (next = readdir(dir); next; next = readdir(dir)) { const char *name = next->d_name; long long val; if (name[0] == '.') continue; val = strtoll(name, NULL, 10); if (val < n || val == fd || val == exclude_fd) continue; r = close(val); if (r < 0) { debug("cannot close %d: %m", val); failures++; } } r = closedir(dir); if (r < 0) { debug("cannot close %d: %m", fd); failures++; } return -failures; } /* * Makes the current process a "foreground" process, by making it the leader of * a process group and session leader. It also updates the sigmask to include * signals that should be blocked. */ static int make_foreground(sigset_t *sigmask) { /* Create a new process group. */ if (setpgid(0, 0) < 0) bail("failed to create process group"); pid_t pgrp = getpgrp(); if (pgrp < 0) bail("failed to get new process group id"); /* * We open /dev/tty directly here. The reason for this (rather than just * using STDIN_FILENO) is the the file descriptor could be duped over, but * we still should become the controlling process. */ int ttyfd = open("/dev/tty", O_RDWR|O_CLOEXEC); if (ttyfd < 0) { info("using stdin as tty fd: could not open /dev/tty: %m"); ttyfd = STDIN_FILENO; } /* * Add TTY signals to ignored mask for pid1. This isn't strictly necessary, * but we do it anyway to avoid pid1 being stopped inadvertently. */ if (sigaddset(sigmask, SIGTSTP) < 0) bail("failed to add SIGTSTP to pid1 mask"); if (sigaddset(sigmask, SIGTTOU) < 0) bail("failed to add SIGTTOU to pid1 mask"); if (sigaddset(sigmask, SIGTTIN) < 0) bail("failed to add SIGTTIN to pid1 mask"); /* Try to set ourselves as the owner of the terminal. */ if (tcsetpgrp(ttyfd, pgrp) < 0) { switch (errno) { /* The fd wasn't a tty. This isn't a problem. */ case ENOTTY: case EBADF: debug("setting foreground process failed: no tty present: %m"); break; /* Can happen on lx-branded zones. Not a problem. */ case ENXIO: debug("setting foreground process failed: no such device"); break; /* Other errors are a problem. */ default: bail("setting foreground process failed: %m"); break; } } if (ttyfd != STDIN_FILENO) close(ttyfd); return 0; } /* * If the LISTEN_PID environment variable is set to the parent pid, rewrite it to * point to the current pid. */ static void rewrite_listen_pid_env() { char *listen_pid = getenv("LISTEN_PID"); long long val; if (listen_pid == NULL) return; errno = 0; val = strtoll(listen_pid, NULL, 10); if (errno == ERANGE) { warn("LISTEN_PID has an invalid value"); return; } if (val == getppid()) { char pid_str[32]; int r; snprintf(pid_str, sizeof(pid_str), "%d", getpid()); r = setenv("LISTEN_PID", pid_str, 1); if (r < 0) warn("could not overwrite env variable LISTEN_PID: %m"); } } /* * Spawn a child process with the given arguments and signal map and make it a * faux-pid1 by placing it in the foreground. This is the main process which * catatonit is going to be managing throughout its life. */ static int spawn_pid1(char *file, char **argv, sigset_t *sigmask) { pid_t child = fork(); if (child != 0) { if (child < 0) error("failed to fork child: %m"); return child; } rewrite_listen_pid_env(); /* * We are now in the child. Set up our sigmask, put ourselves in the * foreground, and then finally exec (with the environment inherited). */ if (make_foreground(sigmask) < 0) bail("failed to become foreground: %m"); if (sigprocmask(SIG_SETMASK, sigmask, NULL) < 0) bail("failed to reset sigmask: %m"); execvpe(file, argv, environ); bail("failed to exec pid1: %m"); } /* * Handles any queued zombies which need to be reaped using waitpid(2). We * continually wait for child process deaths until none are reported (or we * have no children left). */ static int reap_zombies(pid_t pid1, int *pid1_exitcode) { for (;;) { int wstatus = 0; pid_t child = waitpid(-1, &wstatus, WNOHANG); if (child <= 0) { if (errno == ECHILD) { debug("got ECHILD: no children left to monitor"); child = 0; } return child; } /* * There is a special-case for our pid1. If the process exits we * inherit its exit code, otherwise we assume an exit code of 127. * This will cause us to exit immediately, since pid1 is now dead. */ if (child == pid1) { /* Did it die from an exit(2)? */ if (WIFEXITED(wstatus)) *pid1_exitcode = WEXITSTATUS(wstatus); /* What about from a signal? */ else if (WIFSIGNALED(wstatus)) *pid1_exitcode = 128 + WTERMSIG(wstatus); /* Is the child actually dead? */ else if (kill(pid1, 0) < 0) *pid1_exitcode = 127; /* It hasn't died... */ else warn("received SIGCHLD from pid1 (%d) but it's still alive", pid1); continue; } if (WIFEXITED(wstatus)) debug("child process %d exited with code %d", child, WEXITSTATUS(wstatus)); else if (WIFSIGNALED(wstatus)) debug("child process %d exited due to signal %d", child, WTERMSIG(wstatus)); else warn("observed unexpected status for process %d: %#x", child, wstatus); } } int main(int argc, char **argv) { /* If CATATONIT_DEBUG is defined we change the global log level. */ char *logstring = secure_getenv("CATATONIT_DEBUG"); if (logstring != NULL) global_log_level = LOG_DEBUG; /* CATATONIT_LOG is reserved for future use. */ if (secure_getenv("CATATONIT_LOG")) bail("CATATONIT_LOG is reserved for future use"); /* * Set up signal handling before *anything else*. We block *all* signals * (except for signals that the kernel generates to try to kill us) since * they will be read from the signalfd we set up. We also keep a copy of * the original sigmask so we can re-set it on our faux-pid1. */ sigset_t init_sigmask, pid1_sigmask; if (sigfillset(&init_sigmask) < 0) bail("failed to fill init_sigmask: %m"); int i; for (i = 0; i < ARRAY_LEN(kernel_signals); i++) { if (sigdelset(&init_sigmask, kernel_signals[i]) < 0) bail("failed to clear signal %d from init_sigmask: %m", kernel_signals[i]); } if (sigprocmask(SIG_SETMASK, &init_sigmask, &pid1_sigmask) < 0) bail("failed to block all signals: %m"); int sfd = signalfd(-1, &init_sigmask, SFD_CLOEXEC); if (sfd < 0) bail("failed to create signalfd: %m"); /* * We need to support "--" as well as provide license information and so * on. Aside from that we also need to update argv so it points at the * first *pid1* argv argument rather than our own. */ int opt; bool kill_pgid = false; bool run_as_pause = false; const struct option longopts[] = { {name: "version", has_arg: no_argument, flag: NULL, val: 'V'}, {}, }; while ((opt = getopt_long(argc, argv, "ghLPV", longopts, NULL)) != -1) { switch (opt) { case 'g': kill_pgid = true; break; case 'P': run_as_pause = true; break; case 'h': help(); exit(0); case 'L': license(); exit(0); case 'V': version(); exit(0); default: usage(); exit(1); } } argv += optind; argc -= optind; if (argc < 1 && !run_as_pause) bail_usage("missing program name"); /* * If we aren't pid1, we have to set subreaper or bail. Otherwise zombies * will collect on the host and that's just not a good idea. We don't just * bail in all cases because users can run us in a container, but with the * pid namespace shared with the host (though the benefit of using a * container init is effectively zero in that instance). */ if (getpid() != 1) { #if defined(PR_SET_CHILD_SUBREAPER) if (prctl(PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0) < 0) bail("failed to set child-reaper as non-pid1: %m"); #else bail("cannot run as non-pid1 without child-reaper support in kernel"); #endif } /* Spawn the faux-pid1. */ pid_t pid1 = 0; if (!run_as_pause) { pid1 = spawn_pid1(argv[0], argv, &pid1_sigmask); if (pid1 <= 0) bail("failed to spawn pid1: %m"); /* One final check to make sure that it actually spawned. */ if (kill(pid1, 0) < 0) bail("self-check that pid1 (%d) was spawned failed: %m", pid1); debug("pid1 (%d) spawned: %s", pid1, argv[0]); } /* * Switch to / explicitly, to work around a known podman issue where podman * runs "catatonit -P" in a subdirectory which causes umount to fail * because the directory is pinned by catatonit. Ignore errors since we * don't care about the cwd anyway. */ (void) chdir("/"); if (close_fds_ge_than(3, sfd) < 0) warn("failed to close some file descriptor in range >=3"); /* * The "pid" we send signals to. With -g we send signals to the entire * process group which pid1 is in, which is represented by a -ve pid. */ pid_t pid1_target = run_as_pause ? 0 : (kill_pgid ? -pid1 : pid1); /* * Wait for signals and process them as necessary. At this point we are no * longer allowed to bail(), because if anything breaks it's ultimately our * fault since a pid1 death will kill the container. */ int pid1_exitcode = -1; while (pid1_exitcode < 0) { /* * Wait for a signal. read(2) will block here and we don't care about * anything else, so no need for select(2) or epoll(2) or anything * equivalently clever. */ struct signalfd_siginfo ssi = {0}; int n = read(sfd, &ssi, sizeof(ssi)); if (n != sizeof(ssi)) { if (n < 0) warn("signalfd read failed: %m"); else warn("signalfd had %d-byte partial-read: %m", n); continue; } switch (ssi.ssi_signo) { /* * Signals that we get sent if we are a background job in the current * terminal (if it has TOSTOP set), which is possible since we make * pid1 the foreground process. We just ignore them. */ case SIGTSTP: case SIGTTOU: case SIGTTIN: debug("ignoring kernel attempting to stop us: tty has TOSTOP set"); break; /* A child has died or a zombie has been re-parented to us. */ /* * TODO: We really should check ssi_pid, to see whether the sender was * inside our pid namespace. This would help avoid cases where someone * (foolishly) wants us to forward SIGCHLD to our pid1. Not sure why * you'd ever want that, but no reason to not support it. */ case SIGCHLD: if (reap_zombies(pid1, &pid1_exitcode) < 0) warn("problem occurred while reaping zombies: %m"); break; /* A signal sent to us by a user which we must forward to pid1. */ default: /* We just forward the signal to pid1. */ if (run_as_pause) { if (ssi.ssi_signo == SIGTERM || ssi.ssi_signo == SIGINT) return 0; } else if (kill(pid1_target, ssi.ssi_signo) < 0) { warn("forwarding of signal %d to pid1 (%d) failed: %m", ssi.ssi_signo, pid1_target); } break; } } return pid1_exitcode; } catatonit-0.2.1/config.h.in000066400000000000000000000035551472724544100155450ustar00rootroot00000000000000// SPDX-License-Identifier: GPL-3.0-or-later /* * catatonit: a container init so simple it's effectively brain-dead * Copyright (C) 2018-2023 SUSE LLC * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #if !defined(CONFIG_H) #define CONFIG_H #define PROGRAM_NAME "@PACKAGE_NAME@" #define PROGRAM_VERSION "@PACKAGE_VERSION@" #define PROGRAM_BUGURL "@PACKAGE_BUGREPORT@" #define PROGRAM_URL "@PACKAGE_URL@" #define PROGRAM_LICENSE \ PROGRAM_NAME ": a container init so simple it's effectively brain-dead\n" \ "Copyright (C) 2018-2023 SUSE LLC\n" \ "\n" \ "This program is free software; you can redistribute it and/or modify\n" \ "it under the terms of the GNU General Public License as published by\n" \ "the Free Software Foundation, either version 2 of the License, or\n" \ "(at your option) any later version.\n" \ "\n" \ "This program is distributed in the hope that it will be useful,\n" \ "but WITHOUT ANY WARRANTY; without even the implied warranty of\n" \ "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" \ "GNU General Public License for more details.\n" \ "\n" \ "You should have received a copy of the GNU General Public License\n" \ "along with this program. If not, see .\n" \ #endif /* !defined(CONFIG_H) */ catatonit-0.2.1/configure.ac000066400000000000000000000024001472724544100157740ustar00rootroot00000000000000# SPDX-License-Identifier: GPL-2.0-or-later # # catatonit: a container init so simple it's effectively brain-dead # Copyright (C) 2018-2023 SUSE LLC # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . AC_PREREQ([2.69]) AC_INIT([catatonit], [0.2.1], [https://bugs.opensuse.org/], [], [https://github.com/openSUSE/catatonit/]) AM_INIT_AUTOMAKE([-Wall foreign]) LT_PREREQ([2.4.2]) LT_INIT([disable-shared]) AC_CHECK_HEADERS([errno.h fcntl.h signal.h stdarg.h stdio.h stdlib.h unistd.h]) AC_CHECK_HEADERS([linux/close_range.h sys/prctl.h sys/signalfd.h sys/stat.h sys/types.h sys/wait.h]) AC_CHECK_FUNCS([close_range]) AC_TYPE_PID_T AC_FUNC_FORK AC_CONFIG_FILES([Makefile config.h]) AC_OUTPUT catatonit-0.2.1/hack/000077500000000000000000000000001472724544100144205ustar00rootroot00000000000000catatonit-0.2.1/hack/release.sh000077500000000000000000000076471472724544100164150ustar00rootroot00000000000000#!/bin/bash # release.sh: configurable signed-artefact release script # Copyright (C) 2016-2019 SUSE LLC. # # This Source Code Form is subject to the terms of the Mozilla Public # License, v2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. set -Eeuo pipefail ## ---> # Project-specific options and functions. In *theory* you shouldn't need to # touch anything else in this script in order to use this elsewhere. project="catatonit" root="$(readlink -f "$(dirname "${BASH_SOURCE}")/..")" # Make pushd and popd silent. function pushd() { command pushd "$@" &>/dev/null ; } function popd() { command popd "$@" &>/dev/null ; } # These functions allow you to configure how the defaults are computed. function get_arch() { uname -m ; } function get_version() { echo '@PACKAGE_VERSION@' | "$root/config.status" --file - ; } # Any pre-configuration steps should be done here -- for instance ./configure. function setup_project() { pushd "$root" ./autogen.sh ./configure LDFLAGS="-static" --prefix=/ --bindir=/bin popd } # This function takes an output path as an argument, where the built # (preferably static) binary should be placed. function build_project() { tmprootfs="$(mktemp -d --tmpdir "$project-build.XXXXXX")" make -C "$root" clean all install DESTDIR="$tmprootfs" mv "$tmprootfs/bin/$project" "$1" rm -rf "$tmprootfs" } # End of the easy-to-configure portion. ## <--- # Print usage information. function usage() { echo "usage: release.sh [-h] [-v ] [-c ] [-o ]" >&2 echo " [-H ] [-S ]" >&2 } # Log something to stderr. function log() { echo "[*]" "$@" >&2 } # Log something to stderr and then exit with 0. function quit() { log "$@" exit 0 } # Conduct a sanity-check to make sure that GPG provided with the given # arguments can sign something. Inability to sign things is not a fatal error. function gpg_cansign() { gpg "$@" --clear-sign /dev/null } # When creating releases we need to build (ideally static) binaries, an archive # of the current commit, and generate detached signatures for both. keyid="" version="" arch="" commit="HEAD" hashcmd="sha256sum" while getopts ":h:v:c:o:S:H:" opt; do case "$opt" in S) keyid="$OPTARG" ;; c) commit="$OPTARG" ;; o) outputdir="$OPTARG" ;; v) version="$OPTARG" ;; H) hashcmd="$OPTARG" ;; h) usage ; exit 0 ;; \:) echo "Missing argument: -$OPTARG" >&2 usage ; exit 1 ;; \?) echo "Invalid option: -$OPTARG" >&2 usage ; exit 1 ;; esac done # Run project setup first... ( set -x ; setup_project ) # Generate the defaults for version and so on *after* argument parsing and # setup_project, to avoid calling get_version() needlessly. version="${version:-$(get_version)}" arch="${arch:-$(get_arch)}" outputdir="${outputdir:-release/$version}" log "[[ $project ]]" log "version: $version" log "commit: $commit" log "output_dir: $outputdir" log "key: ${keyid:-(default)}" log "hash_cmd: $hashcmd" # Make explicit what we're doing. set -x # Make the release directory. rm -rf "$outputdir" && mkdir -p "$outputdir" # Build project. build_project "$outputdir/$project.$arch" # Generate new archive. git archive --format=tar --prefix="$project-$version/" "$commit" | xz > "$outputdir/$project.tar.xz" # Generate sha256 checksums for both. ( cd "$outputdir" ; "$hashcmd" "$project".{"$arch",tar.xz} > "$project.$hashcmd" ; ) # Set up the gpgflags. gpgflags=() [[ -z "$keyid" ]] || gpgflags+=("--default-key=$keyid") gpg_cansign "${gpgflags[@]}" || quit "Could not find suitable GPG key, skipping signing step." # Sign everything. gpg "${gpgflags[@]}" --detach-sign --armor "$outputdir/$project.$arch" gpg "${gpgflags[@]}" --detach-sign --armor "$outputdir/$project.tar.xz" gpg "${gpgflags[@]}" --clear-sign --armor \ --output "$outputdir/$project.$hashcmd"{.tmp,} && \ mv "$outputdir/$project.$hashcmd"{.tmp,}