pax_global_header00006660000000000000000000000064130364437000014512gustar00rootroot0000000000000052 comment=4446b359725341079c7842e72df79c48be0a082b detachtty-11.0.0/000077500000000000000000000000001303644370000135625ustar00rootroot00000000000000detachtty-11.0.0/.gitignore000066400000000000000000000000301303644370000155430ustar00rootroot00000000000000attachtty detachtty *.o detachtty-11.0.0/COPYING000066400000000000000000000440751303644370000146270ustar00rootroot00000000000000This is detachtty, currently maintained by Massimiliano Ghilardi several improvements by Marco Baringer bugfixes by huetsch written by Daniel Barlow on Thu, 31 May 2001 22:10:29 +0100. The latest source can be found at: https://github.com/cosmos72/detachtty Copyright (C) 2016-2017 Massimiliano Ghilardi Copyright (C) 2001-2005 Daniel Barlow ---------------------------------------- GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. detachtty-11.0.0/ChangeLog000066400000000000000000000103631303644370000153370ustar00rootroot00000000000000detachtty (11.0.0) * Added COPYING with GPLv2 license, updated README and INSTALL * Added explicit copyright statement to all sources and headers * Added detachtty command-line option "--version" * removed debian/ folder, and moved ChangeLog from debian/ to top folder * Documented attachtty behaviour on SIGTSTP and CTRL+Z in man page -- Massimiliano Ghilardi Sat, 14 Jan 1017 16:40:20 +0100 detachtty (10.5.0) * several improvements to attachtty: * propagate window size changes to process running inside detachtty * fixed tty initialization to correctly forward ^C ^Q ^R and ^S * added support for CTRL+Z * added support for timeout also on remote (ssh) connections * added clean exit upon end-of-file while reading from socket or standard input * when command is specified, terminate it with '\r' instead of '\n' * fixed signal handlers to set volatile flags, instead of calling fprintf() directly * simplified ssh remote connection logic, no longer requires ssh-askpass * and to detachtty: * updated man page detachtty.1 * fixed several compile warnings and missing return values * improved logging messages * improved robustness of forking in background * do not pass pts_name[] to forkpty, as minimum buffer length cannot be determined -- Massimiliano Ghilardi Sun, Apr 26 2015 19:52:16 +0200 detachtty (10) unstable; urgency=low * Minor manual page bugfix (Closes: #298877) * MacOS 10.3 doesn't need fink any more: note to that effect in the Makefile * More robust when the client goes away unexpectedly (ignore SIGPIPE, test for EPIPE) * Attempts to distinguish dead socket from earlier run and socket in use by simultaneous run -- Daniel Barlow Thu, 31 Mar 2005 10:28:22 +0100 detachtty (9) unstable; urgency=low * Minor bug fix/incompatible change: reset the umask in the child process from 077 to whatever it had been in the parent environment * Bump debian standards version -- Daniel Barlow Sun, 14 Dec 2003 12:57:35 +0000 detachtty (8) unstable; urgency=low * Patch from Paul Lathrop to build on MacOS X with the libpoll fink package -- Daniel Barlow Mon, 4 Aug 2003 10:10:38 +0100 detachtty (7) unstable; urgency=low * Patch from Ng Pheng Siong to set VERASE2 to something harmless -- Daniel Barlow Thu, 23 Jan 2003 09:56:54 +0000 detachtty (6) unstable; urgency=low * Solaris port and assorted fixes (thanks to Matthias Koeppe and Utz-Uwe Haus) * Better error messages for bad command line arguments (Closes: #151156) * Manpage improvements * Probably survives a SIGHUP better if using relative log/dribble filenames -- Daniel Barlow Tue, 17 Sep 2002 22:06:05 +0100 detachtty (5) unstable; urgency=low * FreeBSD portability fixes * Includes text from strerror when reporting OS errors * Upload sponsored by Matthew Danish -- Daniel Barlow Wed, 17 Oct 2001 10:59:03 +0100 detachtty (4) unstable; urgency=low * Dribble files now work correctly * Server process was dying in some circumstances when client went away * Upload sponsored by Matthew Danish * More documentation -- Daniel Barlow Tue, 16 Oct 2001 19:54:51 +0100 detachtty (3) unstable; urgency=low * Man page fixes * Upload sponsored by Matthew Danish * Closes: #110712 (ITP) * Re-upload due to initial rejection - ssh could not be Recommended if this package was to go into main. - Moved ssh to Suggests instead. -- Daniel Barlow Wed, 5 Sep 2001 13:32:53 -0400 detachtty (2) unstable; urgency=low * Fix various packaging infelicities * Removed #include reference to unused * Correct section number in manual page * Give intelligible error messages when invoked without args * Upload sponsored by Matthew Danish * Closes: #110712 (ITP) -- Daniel Barlow Sat, 1 Sep 2001 00:51:21 +0100 detachtty (1) unstable; urgency=low * Initial Release. -- Daniel Barlow Thu, 31 May 2001 22:10:29 +0100 Local variables: mode: debian-changelog End: detachtty-11.0.0/INSTALL000066400000000000000000000024061303644370000146150ustar00rootroot00000000000000 INSTALLATION The Makefile apparently requires GNU Make; if you have some other Make program, you'll need to edit it by hand - or install GNU Make, of course. vi Makefile make make install Or, if your distribution already contains detachtty: - on Debian, Ubuntu and other GNU/Linux systems that use ".deb" packages, "apt-get install detachtty" will download and install it - on RedHat, Fedora, CentOS and other GNU/Linux systems that use ".rpm" packages, "yum install detachtty" will download and install it PORTING detachtty is tested primarily on GNU/Linux boxes. It should work on - anything with a forkpty() call - anything with an openpty() call that the code in forkpty.c will run on but you may need to tune things (1) Look at the Makefile. Alter OS_CFLAGS, OS_LOADLIBES, OS_OBJECTS as necessary. (2) If that's insufficient (e.g. you need more header files), add the necessary stanzas to config.h and return to step 1 (3) If that's still insufficent, do something else reasonably tasteful (Note from original author Daniel Barlow: NB: auto* is _not_ reasonably tasteful) (4) Send your patch (or as last resort, your problem) to the maintainer. The preferred channel is to open a github issue at https://github.com/cosmos72/detachtty/issues detachtty-11.0.0/Makefile000066400000000000000000000025301303644370000152220ustar00rootroot00000000000000 # OS_* variables vary according to your operating system. See INSTALL # for details # Linux 2.4 OS_CFLAGS=-DNEED_PTY_H -fno-strict-aliasing # FreeBSD, version unknown #OS_CFLAGS=-DNEED_LIBUTIL_H # Solaris, some version of #OS_CFLAGS=-DNEED_STRINGS_H -DNEED_LOCAL_FORKPTY_H # MacOS X needs the local forkpty, and < 10.3 needs libpoll from fink # OS_CFLAGS=-DNEED_LOCAL_FORKPTY_H -I/sw/include # -lutil has forkpty() in it in Linux 2.4, and apparently at least # doesn't break anything in FreeBSD. OS_LDLIBS=-lutil # Solaris users need this instead #OS_LDLIBS=-lnsl -lsocket # MacOS X <10.3 needs libpoll from fink, later versions don't # OS_LDLIBS=-L/sw/lib -lpoll OS_OBJECTS= # no forkpty in Solaris or MacOS X # OS_OBJECTS=forkpty.o INSTALL_DIR=/usr/local/bin # You probably don't need to edit anything below this line ADD_CFLAGS= ADD_LDLIBS= CFLAGS=$(OS_CFLAGS) $(ADD_CFLAGS) LDLIBS=$(OS_LDLIBS) $(ADD_LDLIBS) all: detachtty attachtty clean: rm -f *.o *~ attachtty detachtty install: all install detachtty attachtty $(DESTDIR)$(INSTALL_DIR) deb: rm -rf /usr/local/src/Packages/detachtty/ CVSROOT=`cat CVS/Root` cvs-buildpackage -W/usr/local/src/Packages -F -uc -us -rfakeroot lintian /usr/local/src/Packages/detachtty*.changes detachtty: detachtty.o copy-stream.o errors.o $(OS_OBJECTS) attachtty: attachtty.o copy-stream.o errors.o $(OS_OBJECTS) detachtty-11.0.0/README000066400000000000000000000122351303644370000144450ustar00rootroot00000000000000-*- Text -*- is good. detachtty detachtty lets you run interactive programs non-interactively, and connect to them over the network when you do need to interact with them. If you've used screen, it's a similar concept. Compared to screen, detachtty has * no capability to swap between different screens (it doesn't co-opt C-a) * no tty emulation (you can sanely use it in emacs comint modes) * no features (less to go wrong) * no configuration file * ability to spawn ssh to securely connect across the network * What it's for - a likely usage scenario I have a persistent server implemented in Lisp. Usually it sits there serving things, but sometimes (for example when a new version is available and it needs to be upgraded) I need to connect to it and type Lisp at it. Why don't I use screen? I could - I used to do exactly that - but then I have to talk directly to the CMUCL repl, which means no command line editing. I want to use ILISP, but (1) screen's terminal handling is likely to confuse Emacs, (2) screen isn't network-enabled and the server machine doesn't have Emacs installed anyway. * How it works: detachtty has two parts: ** detachtty - the server opens a pseudoterminal and starts your program on the slave end. It then copies between that tty and a unix-domain socket whose location you specify when you start it detachtty has options to fork into the background, to specify the socket location, and to govern the placement of its log file and of the dribble file from the application underneath it ** attachtty - the client When you want to connect to the process, attachtty attaches to the unix-domain socket and copies input/output to and from you. If you have ssh installed and set up, you can also use attachtty across the network. This requires - that you also have attachtty installed on the machine that you are running detachtty on, and that it's somewhere on the path It's often nice to be able to interrupt a process, especially when it's stuck in some kind of loop. attachtty catches SIGINT and sends the character \003 into the pty master, which causes the controlled process to get a SIGINT of its own. This works at least for using with ILISP and CMUCL. To terminate attachtty, sending it SIGQUIT (usually from the keyboard with CONTROL+\): it will detach from the unix-domain socket, leaving the server process running. Sometimes you need to press it twice. You can also suspend and resume attachtty as a regular Unix process (usually from the keyboard with CONTROL+Z). The server process will keep running while attachtty is suspended. * Using it - an example server$ detachtty --help detachtty: unrecognized option `--help' usage: detachtty [--no-detach] [--dribble-file name] [--log-file name] \ [--pid-file name] socket-path command [arg] [arg] [arg] ... server$ detachtty --dribble-file /var/log/cliki-dribble --log-file \ /var/log/detachtty.log --pid-file /var/run/cliki.pid \ /var/run/cliki-socket /usr/bin/lisp -eval '(load-system :telentweb)' \ -eval '(progn (telentweb::init) (telentweb::start))' \ client$ attachtty dan@server:/var/run/cliki-socket ** Signals and log files When detachtty receives a SIGHUP, it closes and reopens its log and dribble files, so it should play nice with whatever log rotation tools you already use. Note that the dribble file especially can grow large quite quickly The SIGHUP should be sent to detachtty, not to the child. What the child does with signals depends entirely on what the child is ... * Security considerations - detachtty performs no authentication of who's attached. You choose where the socket is created in the filesystem, so choose somewhere that other people can't get to. (detachtty creates its socket with mode 0700. Some Unix systems - Linux among them - honour file permissions on sockets, so only the original user or root will be able to connect to it. However, "many BSD derived systems [...] ignore permissions for Unix sockets" so you need to check if this will help you or not.) - communication across the net is done using ssh. If there is a program on your computer called "ssh", then whatever level of security it provides is available here - no serious effort has been made to examine the attachtty and detachtty code for buffer overruns etc. If you are planning on using these setuid or in some other untrusted-user situation, now is the time to think of an alternative plan. * Where to get it detachtty development is hosted at Also, your distribution may (or may not) already contain it. If it does, you will find that: - on Debian, Ubuntu and other GNU/Linux systems that use ".deb" packages, "apt-get install detachtty" will download and install it - on RedHat, Fedora, CentOS and other GNU/Linux systems that use ".rpm" packages, "yum install detachtty" will download and install it Users of platforms that do not contain detachtty can download it from and compile and install it manually - see the INSTALL file inside the downloaded package. * Feedback, feature requests, patches Use github issues at detachtty-11.0.0/attachtty.c000066400000000000000000000227121303644370000157370ustar00rootroot00000000000000/* * detachtty - run long-lived processes non interactively in the background, * and reattach them to a terminal at later time * * Copyright (C) 2016-2017 Massimiliano Ghilardi * Copyright (C) 2001-2005 Daniel Barlow * * 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. */ #include #include #include "config.h" extern FILE *log_fp; void connect_direct(char * path, char *text, int timeout) ; void connect_ssh(char *host, char *path, char *text, char *timeout) ; int init_tty(void); int cleanup_tty(void); static void init_signal_handlers(void); static void cleanup_signal_handler(int signal); #ifndef UNIX_PATH_MAX # define UNIX_PATH_MAX 108 #endif static char * const MY_NAME = "attachtty"; /* attachtty /path/to/socket [text-to-send [timeout]] or attachtty user@hostname:/path/to/socket [text-to-send [timeout]] In the latter case, we open an ssh connection to user@hostname then run attachtty on the remote machine with the remainder of the arguments */ volatile int was_interrupted=0, was_suspended=0, was_resized=0, time_to_die=0; void tears_in_the_rain(int signal) { time_to_die=signal; cleanup_signal_handler(signal); } void control_c_pressed(int signal) { was_interrupted=1; } void control_z_pressed(int signal) { was_suspended=1; } void window_resized(int signal) { was_resized=1; } void init_ctrl_z_handler(void) { struct sigaction act; act.sa_handler = control_z_pressed; sigemptyset(&(act.sa_mask)); act.sa_flags = SA_RESETHAND; sigaction(SIGTSTP,&act,0); } void cleanup_ctrl_z_handler(void) { cleanup_signal_handler(SIGTSTP); } void suspend_myself(void) { /* restore tty and SIGTSTP settings before suspending myself */ cleanup_tty(); cleanup_ctrl_z_handler(); kill(getpid(), SIGTSTP); /* received SIGCONT: perform again initial setup */ init_ctrl_z_handler(); init_tty(); } static void init_signal_handlers(void) { struct sigaction act; int i, fatal_sig[] = { SIGHUP, SIGQUIT, SIGILL, SIGABRT, SIGBUS, SIGFPE, SIGSEGV, SIGPIPE, SIGTERM, SIGSTKFLT, SIGCHLD, SIGXCPU, SIGXFSZ, }; /* catch SIGINT and send character \003 over the link */ act.sa_handler=control_c_pressed; sigemptyset(&(act.sa_mask)); act.sa_flags=0; sigaction(SIGINT,&act,0); /* catch SIGWINCH and send window size over the link */ act.sa_handler=window_resized; sigemptyset(&(act.sa_mask)); act.sa_flags=0; sigaction(SIGWINCH,&act,0); /* catch SIGSTOP and cleanup tty before suspending */ init_ctrl_z_handler(); /* catch SIGCHLD, SIGQUIT, SIGTERM, SIGILL, SIGFPE... and exit */ act.sa_handler = tears_in_the_rain; sigemptyset(&(act.sa_mask)); act.sa_flags=SA_RESETHAND; for (i = 0; i < sizeof(fatal_sig)/sizeof(fatal_sig[0]); i++) { sigaction(fatal_sig[i],&act,0); } } static void cleanup_signal_handler(int sig) { struct sigaction act; act.sa_handler = SIG_DFL; sigemptyset(&(act.sa_mask)); act.sa_flags = 0; sigaction(sig, &act, 0); } struct termios saved_tty; #ifndef _POSIX_VDISABLE # define _POSIX_VDISABLE 0 #endif #ifndef ONOCR # define ONOCR 0 #endif int init_tty(void) { struct termios tty; int err = tcgetattr(0, &saved_tty); if (err == 0) { tty = saved_tty; tty.c_iflag &= ~(INLCR|ICRNL|IGNCR|IXON|IXOFF); tty.c_oflag &= ~(OCRNL|ONOCR|ONLRET); #ifdef ONLCR tty.c_oflag |= ONLCR; /* avoid staircase effect */ #endif tty.c_oflag &= ~(ONLCR|OCRNL|ONOCR|ONLRET); tty.c_lflag &= ~(ECHO|ICANON|IEXTEN); tty.c_cc[VSTART] = tty.c_cc[VSTOP] = _POSIX_VDISABLE; err = tcsetattr(0, TCSADRAIN, &tty); } return err; } int cleanup_tty(void) { return tcsetattr(0, TCSADRAIN, &saved_tty); } int main(int argc,char *argv[], char *envp[]) { char *host=NULL; /* "hostname" or "user@hostname" */ char *path; /* path to socket */ char *p; char *text=NULL; char *timeout_str=NULL; int timeout = 1; if (argc<2 || argc>4) { fprintf(stderr, "%s: unrecognized arguments\n" "usage: %s /path/to/socket [text] [timeout]\n" " %s remote_user@remote_host:/path/to/socket [text] [timeout]\n", argv[0], argv[0], argv[0]); exit(1); } p=strdup(argv[1]); log_fp=stderr; if((path=strchr(p,':')) != NULL) { host=p; *path='\0'; path++; } else { path=p; } if (argc >= 3) text = argv[2]; if (argc == 4) { timeout_str = argv[3]; int read_timeout = atoi(timeout_str); if (read_timeout > 0) timeout = read_timeout; } init_signal_handlers(); setlinebuf(stdout); setlinebuf(stderr); if (host) { logprintf(MY_NAME,"connecting through ssh to %s on %s",path,host); connect_ssh(host,path,text,timeout_str); } else { logprintf(MY_NAME,"connecting directly to %s",path); init_tty(); connect_direct(path,text,timeout); cleanup_tty(); } if (time_to_die != 0) { logprintf(MY_NAME,"got signal %d, exiting",time_to_die); } return 0; } int send_window_size(int fd) { struct winsize my_winsize; if (fd >= 0 && ioctl(0,TIOCGWINSZ,&my_winsize) == 0 && ioctl(fd,TIOCSWINSZ,&my_winsize) == 0) return 0; return -1; } /* copy between stdin,stdout and unix-domain socket */ void connect_direct(char * path, char *text, int timeout) { int sock=-1, pty_master=-1, ufds_n = 0; int *recv_fd = &pty_master; int text_len = text ? strlen(text) : 0; struct pollfd ufds[3]; struct sockaddr_un s_a; s_a.sun_family=AF_UNIX; strncpy(s_a.sun_path,path,UNIX_PATH_MAX); s_a.sun_path[UNIX_PATH_MAX-1]='\0'; sock=socket(PF_UNIX,SOCK_STREAM,0); if(sock==-1) bail(MY_NAME,"socket"); if(connect(sock,(const struct sockaddr *) &s_a,sizeof s_a)!=0) bail(MY_NAME,"connect"); int time_end = time(NULL) + timeout; int msec_left = -1; if (text) { ufds[0].fd=sock; ufds[0].events=POLLIN|POLLOUT; ufds_n=1; } else { ufds[0].fd=sock; ufds[0].events=POLLIN; ufds[1].fd=0; ufds[1].events=POLLIN|POLLHUP; ufds_n=2; } while (!time_to_die) { if (was_interrupted) { was_interrupted=0; write(sock,"\003",1); } if (was_suspended) { was_suspended=0; suspend_myself(); } if (was_resized && pty_master >= 0) { was_resized=0; send_window_size(pty_master); } if (text) msec_left = (time_end - time(NULL)) * 1000; else msec_left = -1; if (poll(ufds, ufds_n, msec_left) == -1) { if (errno == EINTR) continue; else bail(MY_NAME, "poll"); } if (ufds[0].revents & POLLIN) { if (copy_a_bit_recvfd_with_log(sock,1,-1,recv_fd, MY_NAME, "copying from socket, exiting") == 0) break; /* send window size as soon as we retrieve pty_master through the link. later, we will send window size again each time we receive a SIGWINCH */ if (recv_fd != NULL && pty_master >= 0) { send_window_size(pty_master); recv_fd = NULL; } } if (text) { if (ufds[0].revents & POLLOUT) { int written = write(sock,text,text_len); if (written > 0) { text += written; text_len -= written; if (text_len <= 0) { ufds[0].events = POLLIN; /* no longer need to output */ write(sock,"\r",1); } } } if (time(NULL) >= time_end) { close(sock); sock=-1; time_to_die = 1; } } else { if (ufds[1].revents & POLLIN) { if (copy_a_bit_with_log(0,sock,-1,MY_NAME, "copying to socket, exiting") == 0) break; } if (ufds[1].revents & POLLHUP) { logprintf(MY_NAME, "closed connection due to hangup, exiting"); break; } } } } void connect_ssh(char *host, char *path, char *text, char *timeout_str) { /* * ssh option -t forces tty allocation on remote side. * Needed to properly setup local and remote tty, * including -icanon -iecho flags and forwarding of CTRL+C */ execlp("ssh", "ssh", "-t", host, "attachtty", path, text, timeout_str, (char *)NULL); bail(MY_NAME, "exec ssh failed"); } /* * Local Variables: * c-basic-offset: 4 * End: */ detachtty-11.0.0/config.h000066400000000000000000000043651303644370000152100ustar00rootroot00000000000000/* * detachtty - run long-lived processes non interactively in the background, * and reattach them to a terminal at later time * * Copyright (C) 2016-2017 Massimiliano Ghilardi * Copyright (C) 2001-2005 Daniel Barlow * * 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. */ #ifndef DETACHTTY_CONFIG_H #define DETACHTTY_CONFIG_H #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef NEED_PTY_H #include #endif #ifdef NEED_LIBUTIL_H #include #endif #ifdef NEED_STRINGS_H #include #endif #ifdef NEED_LOCAL_FORKPTY_H #include "forkpty.h" #endif #define DETACHTTY_VERSION_STR "11.0.0" int copy_a_bit(int in_fd, int out_fd, int dribble_fd, char *message); int copy_a_bit_with_log(int in_fd, int out_fd, int dribble_fd, char * program, char *message); int copy_a_bit_sendfd(int in_fd, int out_fd, int dribble_fd, int send_fd, char *message); int copy_a_bit_recvfd_with_log(int in_fd, int out_fd, int dribble_fd, int * recv_fd, char * program, char *message); int output_buffer(int out_fd); int output_buffer_sendfd(int out_fd, int send_fd); extern FILE *log_fp; int logprintf(char *progname, char *format, ...); void bail(char *progname, char *format, ...); #endif /* DETACHTTY_CONFIG_H */ detachtty-11.0.0/copy-stream.c000066400000000000000000000155761303644370000162070ustar00rootroot00000000000000/* * detachtty - run long-lived processes non interactively in the background, * and reattach them to a terminal at later time * * Copyright (C) 2016-2017 Massimiliano Ghilardi * Copyright (C) 2001-2005 Daniel Barlow * * 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. */ #include #include #include #include "config.h" #if defined(SCM_RIGHTS) && defined(CMSG_FIRSTHDR) && defined(CMSG_LEN) && defined(CMSG_DATA) && defined(CMSG_NXTHDR) # define DETACHTTY_SENDFD_RECVFD #else # warning compiling without SENDFD/RECVD support #endif enum { buf_capacity = 4096 }; static int bytes_in_buf = 0; static char buf[buf_capacity + 1]; #ifdef DETACHTTY_SENDFD_RECVFD int send_bytes_and_fd(int out_fd, const char * bytes, int bytes_to_write, int send_fd) { char control[sizeof(struct cmsghdr)+sizeof(int)]; struct msghdr msg; struct cmsghdr *cmsg; struct iovec iov; if (send_fd < 0) return -1; /* Response data */ iov.iov_base = (char *)bytes; iov.iov_len = bytes_to_write; /* compose the message */ memset(&msg, 0, sizeof(msg)); memset(control, 0, sizeof(control)); msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = control; msg.msg_controllen = sizeof(control); /* attach open in_fd */ cmsg = CMSG_FIRSTHDR(&msg); cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_type = SCM_RIGHTS; cmsg->cmsg_len = CMSG_LEN(sizeof(int)); *(int *)CMSG_DATA(cmsg) = send_fd; msg.msg_controllen = cmsg->cmsg_len; return sendmsg(out_fd, &msg, 0); } int recv_bytes_and_fd(int in_fd, char * bytes, int bytes_to_read, int * recv_fd) { char control[sizeof(struct cmsghdr)+sizeof(int)+100]; struct msghdr msg; struct cmsghdr *cmsg; struct iovec iov; if (recv_fd == NULL) return -1; memset(&msg, 0, sizeof(msg)); memset(control, 0, sizeof(control)); iov.iov_base = bytes; iov.iov_len = bytes_to_read; msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = control; msg.msg_controllen = sizeof(control); bytes_to_read = recvmsg(in_fd, &msg, 0); if (bytes_to_read < 0) return bytes_to_read; /* Loop over all control messages */ cmsg = CMSG_FIRSTHDR(&msg); while (cmsg != NULL) { if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) { * recv_fd = *(int *) CMSG_DATA(cmsg); break; } cmsg = CMSG_NXTHDR(&msg, cmsg); } return bytes_to_read < iov.iov_len ? bytes_to_read : iov.iov_len; } #endif /* DETACHTTY_SENDFD_RECVFD */ int full_write_bytes_and_sendfd(int out_fd, const char * bytes, int bytes_to_write, int send_fd) { int bytes_written = 0, bytes_written_total = 0; if (out_fd < 0 || bytes_to_write <= 0) return 0; #ifdef DETACHTTY_SENDFD_RECVFD if (send_fd >= 0 && send_bytes_and_fd(out_fd, bytes, 1, send_fd) >= 0) { bytes++; bytes_written_total++; bytes_to_write--; } #endif while (bytes_to_write > 0) { bytes_written = write(out_fd, bytes, bytes_to_write); if (bytes_written < 0) return bytes_written; bytes_to_write -= bytes_written; bytes += bytes_written; bytes_written_total += bytes_written; } return bytes_written_total; } int output_buffer(int out_fd) { return full_write_bytes_and_sendfd(out_fd, buf, bytes_in_buf, -1); } int output_buffer_sendfd(int out_fd, int send_fd) { return full_write_bytes_and_sendfd(out_fd, buf, bytes_in_buf, send_fd); } int input_buffer_recvfd(int in_fd, int dribble_fd, int * recv_fd) { int bytes_read = 0; #ifdef DETACHTTY_SENDFD_RECVFD if (recv_fd != NULL) bytes_read = recv_bytes_and_fd(in_fd, buf, buf_capacity, recv_fd); else #endif bytes_read = read(in_fd, buf, buf_capacity); if (bytes_read > 0) { /* overwrite global variable bytes_in_buf only if we received something: we preserve last read buffer for whoever will attach next */ bytes_in_buf = bytes_read; output_buffer(dribble_fd); } return bytes_read; } int input_buffer(int in_fd, int dribble_fd) { return input_buffer_recvfd(in_fd, dribble_fd, NULL); } int copy_a_bit_sendfd_recvfd(int in_fd, int out_fd, int dribble_fd, int send_fd, int * recv_fd, char *message) { /* copy whatever's available (max 4k) from in_fd to out_fd (and dribble_fd if !=-1) Return number of bytes copied. Bail if error happens. Note: not re-entrant */ if (input_buffer_recvfd(in_fd, dribble_fd, recv_fd) <= 0) return 0; if (output_buffer_sendfd(out_fd, send_fd) < 0) { if (errno != EPIPE) { perror(message); exit(1); } } return bytes_in_buf; } int copy_a_bit_sendfd_recvfd_with_log(int in_fd, int out_fd, int dribble_fd, int send_fd, int * recv_fd, char * program, char *message) { int n = copy_a_bit_sendfd_recvfd(in_fd, out_fd, dribble_fd, send_fd, recv_fd, message); if (n==0) logprintf(program, "%s %s", "end-of-file while", message); return n; } int copy_a_bit(int in_fd, int out_fd, int dribble_fd, char *message) { return copy_a_bit_sendfd_recvfd(in_fd, out_fd, dribble_fd, -1, NULL, message); } int copy_a_bit_with_log(int in_fd, int out_fd, int dribble_fd, char * program, char *message) { return copy_a_bit_sendfd_recvfd_with_log(in_fd, out_fd, dribble_fd, -1, NULL, program, message); } int copy_a_bit_sendfd(int in_fd, int out_fd, int dribble_fd, int send_fd, char *message) { return copy_a_bit_sendfd_recvfd(in_fd, out_fd, dribble_fd, send_fd, NULL, message); } int copy_a_bit_recvfd_with_log(int in_fd, int out_fd, int dribble_fd, int * recv_fd, char * program, char *message) { return copy_a_bit_sendfd_recvfd_with_log(in_fd, out_fd, dribble_fd, -1, recv_fd, program, message); } /* * Local Variables: * c-basic-offset: 4 * End: */ detachtty-11.0.0/detachtty.1000066400000000000000000000125701303644370000156420ustar00rootroot00000000000000.\" Hey, EMACS: -*- nroff -*- .\" First parameter, NAME, should be all caps .\" Second parameter, SECTION, should be 1-8, maybe w/ subsection .\" other parameters are allowed: see man(7), man(1) .TH DETACHTTY 1 "Mar 18, 2006" .\" Please adjust this date whenever revising the manpage. .\" .\" Some roff macros, for reference: .\" .nh disable hyphenation .\" .hy enable hyphenation .\" .ad l left justify .\" .ad b justify to both left and right margins .\" .nf disable filling .\" .fi enable filling .\" .br insert line break .\" .sp insert n+1 empty lines .\" for manpage-specific macros, see man(7) .SH NAME detachtty, attachtty \- run an interactive program with io to a unix-domain socket .SH SYNOPSIS .B detachtty .RI [ --no-detach ] .RI [ --dribble-file \ \ dribblename ] .RI [ --log-file \ \ name ] .RI [ --pid-file \ \ pidname ] .I socket-path command .RI [ arguments-to-command ] ... .br .B attachtty .I socket-path .RI [ command ] .RI [ timeout ] .br .B attachtty .I username@host:socket-path .RI [ command ] .SH DESCRIPTION .B detachtty lets you run interactive programs non-interactively, and connect to them (optionally over the network) when you do need to interact with them. \fIcommand\fR is run on a pseudo-terminal, and data is copied between it and a unix(7)-domain socket named \fIsocket-path\fR. \fIcommand\fR runs with the current user's permissions and environment variables. .PP .B attachtty is used to connect to a process running under detachtty. It copies between \fIsocket-path\fR and stdin/out. It also catches SIGINT and arranges for it to be forwarded to the \fIcommand\fR, so the user may use Control-C in the usual fashion. .P If you've used screen, it's a similar concept. Compared to screen, detachtty has .PP * no capability to swap between different screens (it doesn't co-opt C-a) .PP * no tty emulation (you can sanely use it in emacs comint modes) .PP * no features (less to go wrong) .PP * no configuration file .PP * ability to spawn ssh to securely connect across the network .SH OPTIONS These programs approximately follow the usual GNU command line syntax, using long options that start with two dashes (`--'). .PP For \fBdetachtty\fR, the options are: .TP .B \-\-no\-detach Don't fork into the background. Useful if you wish to start the program from .BR inittab (5). .TP .BI \-\-dribble\-file \ \ dribblename All input from and to the program being run is copied into .I dribblename (if unspecified, it is discarded). .TP .BI \-\-log\-file \ \ name Status messages (client connects, disconnects, errors) are sent to .I name (if unspecified, they go to standard error). .TP .BI \-\-pid\-file \ \ pidname The process ID of detachtty is written to .I pidname. See \fBSIGNALS\fR. .TP .I socket-path The unix-domain socket. If access to \fIcommand\fR should be in any way restricted, so should this socket - i.e. it is recommended that you put it in a mode 700 directory. .TP .I command arguments The command to run (which is searched for in the normal way). All remaining command line parameters are passed to it as arguments. .PP For \fBattachtty\fR, the options are instead: .TP .I socket-path This is either the path to \fIsocket-path\fR, or a "remote path" of the form .IR username @ host : socket-path where .IR username @ host is passed to ssh. The latter form is currently an alias for \fIssh -t\fR .IR username @ host \fIattachtty socket-path [text]\fR and lets ssh manage the authentication, i.e. whether to ask for a password or not. .TP .I text The text to write into the socket. It will be processed by the command executed from detachtty. For local sockets, the same effect can be obtained with \fI(echo -e text\'\\r\'; sleep timeout) | attachtty socket-path\fR .TP .I timeout The maximum timeout in seconds (defaults to 1) to wait for the written text to be processed. This is available only for local connections. .PP To detach from the tty without exiting from the server process, send attachtty any signal that it doesn't catch. See the SIGNALS section. .P .SH NOTES .P detachtty does not search the user's PATH environment variable for the program to execute, so a full pathname must be provided. .P If you get an immediate "Child terminated, exiting" message from detachtty, this usually means that the program you specified was not found or could not be executed (on Linux 2.4, .BR execve (1) succeeds even if it didn't, so to speak). .P You will probably go insane a lot more slowly if you use absolute pathnames for all filename arguments. .P .SH SIGNALS .P Sending \fBSIGHUP\fR to the process identified by \fIpidname\fR will cause detachtty to close and reopen its log files. .P Sending \fBSIGTSTP\fR to an \fIattachtty\fR process (usually from the keyboard with ^Z) will cause it to stop itelf, leaving the server process running. It can be resumed normally with the shell builtin command "fg". .P Sending \fBSIGQUIT\fR to an \fIattachtty\fR process (usually from the keyboard with ^\\) will cause it to detach from the tty and quit, leaving the server process running. Sometimes you need to press it twice. .SH SEE ALSO .BR screen (1), .BR ssh (1), .BR sbcl (1). .br .SH AUTHOR Written by Daniel Barlow , and a cast of units. Modified by Luca Capello . Modified by Mark Huetsch . Modified by Massimiliano Ghilardi . detachtty-11.0.0/detachtty.c000066400000000000000000000334441303644370000157270ustar00rootroot00000000000000/* * detachtty - run long-lived processes non interactively in the background, * and reattach them to a terminal at later time * * Copyright (C) 2016-2017 Massimiliano Ghilardi * Copyright (C) 2001-2005 Daniel Barlow * * 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. */ #include "config.h" #include #include #include #include #ifndef UNIX_PATH_MAX # define UNIX_PATH_MAX 108 #endif static char * const MY_NAME = "detachtty"; /* Create child process and establish the slave pseudo terminal as the child's controlling terminal. extern int forkpty __P ((int *__amaster, char *__name, struct termios *__termp, struct winsize *__winp)); __amaster=fd of master pty __name = name of master pty, must be long enough. how do we know? In the child, also dups the slave device to fds 0,1,2 and calls setsid() (which causes the right process group stuff to happen too) */ static int parse_args(int argc, char *argv[], int * next_arg_ptr); static void set_noecho(int fd); static int bind_socket_or_bail(char * socket_path); static void usage(char *name,char *offending_option); static void version(void); static void init_signal_handlers(void); static void process_accumulated_signals(void); static void tidy_up_nicely(int signal); /* 1) fork and open pty pairs. start child process on the slave end 2) open network socket, listen to it - backlog 0 (should be unix-domain socket) 3) accept a single connection */ static char *socket_path=NULL; static char *dribble_path=NULL; static char *log_file_path=NULL; static char *pid_file_path=NULL; static int dribble_fd=-1; static volatile int was_signaled = 0, was_sighupped = 0; static void reopen_files(int signal) { if (log_file_path) { if (log_fp) fclose(log_fp); log_fp = fopen(log_file_path,"a"); if (log_fp==NULL) perror("fopen log file"); setvbuf(log_fp, NULL, _IONBF, 0); /* don't buffer */ if (signal > 0) logprintf(MY_NAME, "Got signal %d, reopened log file \"%s\"", signal, log_file_path); } else { log_fp = stderr; } if (dribble_path) { if (dribble_fd >= 0) close(dribble_fd); dribble_fd = open(dribble_path, O_WRONLY|O_CREAT|O_APPEND,0600); if (dribble_fd < 0) logprintf(MY_NAME,"Cannot open dribble file %s", dribble_path); } } static void usage(char *name,char *offending_option) { if(offending_option) fprintf(stderr, "%s: unrecognized option `%s'\n", name,offending_option); else fprintf(stderr, "%s: unrecognized arguments\n", name); fprintf(stderr,"usage:\n" " %s [--version] [--no-detach] [--dribble-file name] [--log-file name] \\\n" " [--pid-file name] socket-path /path/to/command [arg] [arg] [arg] ...\n", name); } static void version(void) { fprintf(stdout,"detachtty version %s\n%s", DETACHTTY_VERSION_STR, "Copyright (C) 2016-2017 Massimiliano Ghilardi\n" "Copyright (C) 2001-2005 Daniel Barlow\n" "License GPLv2+: GNU GPL version 2 or later .\n" "\n" "This is free software: you are free to change and redistribute it.\n" "There is NO WARRANTY, to the extent permitted by law.\n"); } #define CLIENT_CONNECTED (sock>=0) int main(int argc,char *argv[], char *envp[]) { struct pollfd ufds[3]; struct termios my_termios; struct winsize my_winsize; int pty_master = -1, master_socket = -1, sock = -1, send_fd = -1; int next_arg = 0, pid = -1, detach_p = 1; mode_t old_umask; log_fp = stderr; /* may be changed by parse_args */ detach_p = parse_args(argc, argv, &next_arg); /* this assumes we're started from a shell. would be smart to default 80x24 or something if we can't do this */ tcgetattr(0, &my_termios); ioctl(0, TIOCGWINSZ, &my_winsize); old_umask = umask(077); master_socket = bind_socket_or_bail(socket_path); umask(old_umask); if (listen(master_socket, 1) != 0) bail(MY_NAME,"listen"); if (detach_p) { int dev_null; if (daemon(1, 1)) bail(MY_NAME, "daemon"); /* we leave stderr open - if the user really wanted his tty back, he'd have specified --log-file */ close(0); close(1); dev_null = open("/dev/null",O_RDWR); dup2(dev_null, 0); dup2(dev_null, 1); } if (pid_file_path) { FILE *fp = fopen(pid_file_path, "w"); if (fp != NULL) { fprintf(fp, "%d\n", (int)getpid()); fclose(fp); } } reopen_files(0); setlinebuf(stdout); setlinebuf(stderr); pid = forkpty(&pty_master,NULL,&my_termios,&my_winsize); if (pid < 0) { /* error */ perror("detach: Can't fork"); exit(1); } else if (pid==0) { /* child */ set_noecho(0); execve(argv[next_arg],&argv[next_arg],envp); bail(MY_NAME,"detach: exec failed"); } else { /* parent */ init_signal_handlers(); logprintf(MY_NAME, "Successfully started"); for (;;) { ufds[0].fd=pty_master; ufds[0].events=POLLIN|POLLHUP; ufds[1].fd=master_socket; ufds[1].events=POLLIN; ufds[2].fd=sock; ufds[2].events=POLLIN|POLLHUP; process_accumulated_signals(); if (poll(ufds, CLIENT_CONNECTED ? 3 : 2, -1) == -1) { int err = errno; if (err != EINTR && err != EAGAIN) logprintf(MY_NAME, "poll failed: %s", strerror(errno)); continue; } process_accumulated_signals(); if (ufds[0].revents & POLLIN) { if (copy_a_bit_sendfd(pty_master,sock,dribble_fd,send_fd,"copying from child") > 0) send_fd = -1; } if (ufds[0].revents & POLLHUP) { logprintf(MY_NAME, "child terminated, exiting"); if (sock>=0) { close(sock); sock=-1; } tidy_up_nicely(0); } if (ufds[1].revents & POLLIN) { struct sockaddr_un their_addr; #ifdef __linux__ socklen_t spare_integer = sizeof(their_addr); #else int spare_integer = sizeof(their_addr); #endif int new_sock = accept(master_socket, (struct sockaddr *) &their_addr, &spare_integer); if (new_sock >= 0) { logprintf(MY_NAME,"accepted connection%s", (CLIENT_CONNECTED ? " (and closing previous one)" : "")); if (CLIENT_CONNECTED) close(sock); sock = new_sock; send_fd = pty_master; /* give them a copy of anything we read recently */ if (output_buffer_sendfd(sock, send_fd) > 0) send_fd = -1; continue; } } if (CLIENT_CONNECTED && (ufds[2].revents & POLLIN)) { if (copy_a_bit_with_log(sock, pty_master, dribble_fd, MY_NAME, "copying from socket, closing connection") == 0) { /* end-of-file on socket */ if (sock >= 0) { close(sock); sock=-1; } } } if (CLIENT_CONNECTED && (ufds[2].revents & POLLHUP)) { logprintf(MY_NAME, "closed connection due to hangup"); close(sock); sock=-1; } } } return 0; } static int parse_args(int argc, char *argv[], int * next_arg_ptr) { int next_arg, detach_p = 1; for (next_arg = 1; next_arg < argc; next_arg++) { if (!strcmp("--no-detach", argv[next_arg])) { detach_p = 0; } else if (!strcmp("--dribble-file", argv[next_arg])) { dribble_path = argv[++next_arg]; } else if (!strcmp("--log-file", argv[next_arg])) { log_file_path = argv[++next_arg]; } else if (!strcmp("--pid-file", argv[next_arg])) { pid_file_path = argv[++next_arg]; } else if (!strcmp("--version", argv[next_arg])) { version(); exit(0); } else if (!strncmp("--", argv[next_arg], 2)) { usage(argv[0], argv[next_arg]); exit(1); } else { break; } } if (next_arg >= argc - 1) { usage(argv[0], NULL); exit(1); } socket_path=argv[next_arg++]; if (argv[next_arg][0] != '/') { logprintf(MY_NAME,"\"%s\" is not an absolute path", argv[next_arg]); bail(MY_NAME, "argument parsing"); } *next_arg_ptr = next_arg; return detach_p; } static int bind_socket_or_bail(char * socket_path) { char pidbuf[80]; struct sockaddr_un addr; FILE * fp = NULL; int master_socket, oldpid = -1; master_socket = socket(PF_UNIX, SOCK_STREAM, 0); if (master_socket < 0) { bail(MY_NAME, "socket"); } addr.sun_family=AF_UNIX; strncpy(addr.sun_path, socket_path, UNIX_PATH_MAX); addr.sun_path[UNIX_PATH_MAX-1] = '\0'; if (bind(master_socket, (const struct sockaddr *) &addr, sizeof(addr)) == 0) { return master_socket; } if (!pid_file_path) { goto no_pid; } fp = fopen(pid_file_path,"r"); if (fp) { if (fgets(pidbuf, sizeof(pidbuf), fp)) { oldpid = atoi(pidbuf); } fclose(fp); } if (oldpid <= 0) { goto no_pid; } if (kill(oldpid,0) == 0 || errno != ESRCH) { logprintf(MY_NAME, "process %d for pid file \"%s\" is still running", oldpid, pid_file_path); goto bind_failed; } /* remove socket_path and try again */ if (unlink(pid_file_path) != 0) { goto bind_failed; } logprintf(MY_NAME, "found and removed stale socket \"%s\" from a previous run", socket_path); if (bind(master_socket, (const struct sockaddr *) &addr, sizeof(addr)) == 0) { return master_socket; } else { goto bind_failed; } no_pid: logprintf(MY_NAME, "Cannot create \"%s\": does it already exist from a previous run?", socket_path); bind_failed: if (master_socket >= 0) close(master_socket); bail(MY_NAME, "bind"); return -1; } /* borrowed from APUE example code found at http://www.yendor.com/programming/unix/apue/pty/main.c */ /* turn off echo (for slave pty) */ static void set_noecho(int fd) { #ifdef NEED_SET_NOECHO struct termios stermios; if (tcgetattr(fd, &stermios) < 0) bail("detach child","tcgetattr error"); stermios.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL); stermios.c_lflag|=ICANON; /* stermios.c_oflag &= ~(ONLCR); */ /* would also turn off NL to CR/NL mapping on output */ stermios.c_cc[VERASE]=0177; #ifdef VERASE2 stermios.c_cc[VERASE2]=0177; #endif if (tcsetattr(fd, TCSANOW, &stermios) < 0) bail("detach child","tcsetattr error"); #endif /* NEED_SET_NOECHO */ } static void cleanup_signal_handler(int sig) { struct sigaction act; act.sa_handler = SIG_DFL; sigemptyset(&(act.sa_mask)); act.sa_flags = 0; sigaction(sig, &act, 0); } static void fatal_signal_handler(int sig) { was_signaled = sig; cleanup_signal_handler(sig); } static void sighup_signal_handler(int sig) { was_sighupped = sig; } static void init_signal_handlers(void) { struct sigaction act; int i, fatal_sig[] = { SIGHUP, SIGQUIT, SIGILL, SIGABRT, SIGBUS, SIGFPE, SIGSEGV, /*SIGPIPE,*/ SIGTERM, SIGSTKFLT, SIGCHLD, SIGXCPU, SIGXFSZ, }; /* catch SIGCHLD, SIGQUIT, SIGTERM, SIGILL, SIGFPE... and exit */ act.sa_handler = fatal_signal_handler; sigemptyset(&(act.sa_mask)); act.sa_flags = SA_RESETHAND; for (i = 0; i < sizeof(fatal_sig)/sizeof(fatal_sig[0]); i++) { sigaction(fatal_sig[i],&act,0); } /* we can be HUPped */ act.sa_handler = sighup_signal_handler; sigemptyset(&(act.sa_mask)); act.sa_flags = 0; sigaction(SIGHUP, &act,0); /* ignore SIGPIPE */ act.sa_handler = SIG_IGN; sigemptyset(&(act.sa_mask)); act.sa_flags = 0; sigaction(SIGPIPE, &act,0); } static void process_accumulated_signals(void) { if (was_signaled) { tidy_up_nicely(was_signaled); was_signaled = 0; } if (was_sighupped) { reopen_files(was_sighupped); was_sighupped = 0; } } static void tidy_up_nicely(int signal) { if (signal) logprintf(MY_NAME, "got unexpected signal %d, exiting", signal); else logprintf(MY_NAME, "exiting", signal); if (unlink(socket_path)) logprintf(MY_NAME, "error unlinking \"%s\": %s", socket_path, strerror(errno)); if (pid_file_path && unlink(pid_file_path) != 0) logprintf(MY_NAME, "error unlinking \"%s\": %s", pid_file_path, strerror(errno)); exit(signal); } /* * Local Variables: * c-basic-offset: 4 * End: */ detachtty-11.0.0/errors.c000066400000000000000000000034621303644370000152470ustar00rootroot00000000000000/* * detachtty - run long-lived processes non interactively in the background, * and reattach them to a terminal at later time * * Copyright (C) 2016-2017 Massimiliano Ghilardi * Copyright (C) 2001-2005 Daniel Barlow * * 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. */ #include #include #include #include #include #include #include #include FILE *log_fp = NULL; int logprintf(char *progname, char *format,...) { va_list ap; int n; va_start(ap, format); fprintf(log_fp, ";;; %s: %ld: ", progname, time(NULL)); n=vfprintf(log_fp, format, ap); va_end(ap); fputs("\r\n",log_fp); return n; } void bail(char *progname,char *format,...) { va_list ap; int err = errno; va_start(ap, format); fprintf(log_fp,";;; %s: %ld: FATAL ", progname, time(NULL)); vfprintf(log_fp, format, ap); va_end(ap); /* use \r\n to avoid staircase effect */ if (err > 0) fprintf(log_fp, " (%s)\r\n", strerror(err)); else fputs("\r\n",log_fp); kill(getpid(), SIGTERM); } detachtty-11.0.0/forkpty.c000066400000000000000000000051631303644370000154310ustar00rootroot00000000000000/* * detachtty - run long-lived processes non interactively in the background, * and reattach them to a terminal at later time * * Copyright (C) 2016-2017 Massimiliano Ghilardi * Copyright (C) 2001-2005 Daniel Barlow * * 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. */ #include #include #include #include #include #include #include int forkpty (int *amaster, char *name, struct termios *termp, struct winsize *winp) { int fdm, fds; char *slavename; pid_t pid; fdm = open("/dev/ptmx", O_RDWR); /* open master */ grantpt(fdm); /* change permission of slave */ unlockpt(fdm); /* unlock slave */ slavename = ptsname(fdm); /* get name of slave */ if (name) strcpy(name, slavename); *amaster = fdm; if ((pid = fork()) < 0) { return pid; /* error */ } else if (pid != 0) { /* parent */ return pid; } else { /* child */ pid_t pgid; /* create a new session */ pgid = setsid(); if (pgid == -1) { perror("setsid failed"); return -1; } fds = open(slavename, O_RDWR); /* open slave */ ioctl(fds, I_PUSH, "ptem"); /* push ptem */ ioctl(fds, I_PUSH, "ldterm"); /* push ldterm */ dup2(fds, 0); dup2(fds, 1); dup2(fds, 2); ioctl(fds, TIOCSPGRP, &pgid); /* magic */ if (termp) ioctl(fds, TCSETS, termp); if (winp) ioctl(fds, TIOCSWINSZ, winp); if (fds > 2) close(fds); return pid; } } int daemon(int nochdir, int noclose) { int fd; switch (fork()) { case -1: return (-1); case 0: break; default: exit(0); } if (setsid() == -1) return (-1); if (!nochdir) chdir("/"); if (!noclose && (fd = open("/dev/null", O_RDWR, 0)) != -1) { dup2(fd, 0); dup2(fd, 1); dup2(fd, 2); if (fd > 2) close (fd); } return (0); } detachtty-11.0.0/forkpty.h000066400000000000000000000023441303644370000154340ustar00rootroot00000000000000/* * detachtty - run long-lived processes non interactively in the background, * and reattach them to a terminal at later time * * Copyright (C) 2016-2017 Massimiliano Ghilardi * Copyright (C) 2001-2005 Daniel Barlow * * 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. */ #ifndef DETACHTTY_FORKPTY_H #define DETACHTTY_FORKPTY_H #include int forkpty (int *amaster, char *name, struct termios *termp, struct winsize *winp); int daemon(int nochdir, int noclose); #endif /* DETACHTTY_FORKPTY_H */