cpopen-1.4/0000775000175000017500000000000012606230076014326 5ustar ybronheiybronhei00000000000000cpopen-1.4/debian/0000775000175000017500000000000012606230076015550 5ustar ybronheiybronhei00000000000000cpopen-1.4/debian/control0000664000175000017500000000077612577515575017206 0ustar ybronheiybronhei00000000000000Source: cpopen Maintainer: Simone Tiraboschi Section: python Priority: optional Build-Depends: python-all-dev (>= 2.6.6-3), debhelper (>= 9), dh-python Standards-Version: 3.9.6 Package: python-cpopen Architecture: any Depends: ${misc:Depends}, ${python:Depends}, ${shlibs:Depends} Description: Creates a subprocess in simpler safer manner A C reimplementation of the tricky bits of Python's Popen. It is currently implemented in a very specific way and might break under general use. cpopen-1.4/debian/python-cpopen.postinst.debhelper0000664000175000017500000000021712577515575024132 0ustar ybronheiybronhei00000000000000# Automatically added by dh_python2: if which pycompile >/dev/null 2>&1; then pycompile -p python-cpopen fi # End automatically added section cpopen-1.4/debian/files0000664000175000017500000000006012577515575016612 0ustar ybronheiybronhei00000000000000python-cpopen_1.3.2-0_amd64.deb python optional cpopen-1.4/debian/copyright0000664000175000017500000000201712577515575017524 0ustar ybronheiybronhei00000000000000Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ Upstream-Name: cpopen Source: http://gerrit.ovirt.org/gitweb?p=cpopen.git Files: * Copyright: 2012-2015 Red Hat, Inc. 2015 Packaged by Simone Tiraboschi License: GPL-2+ This package 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 package 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 . On Debian systems, the complete text of the GNU General Public License version 2 can be found in "/usr/share/common-licenses/GPL-2". cpopen-1.4/debian/source/0000775000175000017500000000000012606230076017050 5ustar ybronheiybronhei00000000000000cpopen-1.4/debian/source/format0000664000175000017500000000001412577515575020277 0ustar ybronheiybronhei000000000000003.0 (quilt) cpopen-1.4/debian/changelog0000664000175000017500000000023412577515575017442 0ustar ybronheiybronhei00000000000000cpopen (1.3.2-0) unstable; urgency=low * Initial release. (Closes: 777672) -- Simone Tiraboschi Wed, 11 Feb 2015 11:35:13 +0100 cpopen-1.4/debian/python-cpopen.prerm.debhelper0000664000175000017500000000036112577515575023374 0ustar ybronheiybronhei00000000000000# Automatically added by dh_python2: if which pyclean >/dev/null 2>&1; then pyclean -p python-cpopen else dpkg -L python-cpopen | grep \.py$ | while read file do rm -f "${file}"[co] >/dev/null done fi # End automatically added section cpopen-1.4/debian/rules0000775000175000017500000000027312577515575016653 0ustar ybronheiybronhei00000000000000#!/usr/bin/make -f # This file was automatically generated by stdeb 0.8.2 at # Wed, 11 Feb 2015 11:35:13 +0100 export PYBUILD_NAME=cpopen %: dh $@ --with python2 --buildsystem=pybuild cpopen-1.4/debian/compat0000664000175000017500000000000212577515575016767 0ustar ybronheiybronhei000000000000009 cpopen-1.4/debian/python-cpopen.substvars0000664000175000017500000000025412577515575022353 0ustar ybronheiybronhei00000000000000python:Versions=2.7 python:Provides=python2.7-cpopen python:Depends=python (>= 2.7), python (<< 2.8), python:any (>= 2.6.6-7~) shlibs:Depends=libc6 (>= 2.11) misc:Depends= cpopen-1.4/README0000664000175000017500000000074412600764760015221 0ustar ybronheiybronhei00000000000000# CPopen A C reimplementation of the tricky bits of Python's Popen. It is currently implemented in a very specific way and might break under general use. # TODO * Support string invocation - Currently only support array invocation * Support after fork func * Support all stream modes - Currently everything has to be PIPE # Usage ```{.python} import cpopen proc = cpopen.CPopen(["echo", "3"]) proc.communicate() ``` # Running the tests ```{.bash} nosetests tests/tests.py ``` cpopen-1.4/MANIFEST0000664000175000017500000000061312606230076015457 0ustar ybronheiybronhei00000000000000# file GENERATED by distutils, do NOT edit AUTHORS COPYING MANIFEST MANIFEST.in Makefile README python-cpopen.spec.in setup.py cpopen/__init__.py cpopen/cpopen.c debian/changelog debian/compat debian/control debian/copyright debian/files debian/python-cpopen.postinst.debhelper debian/python-cpopen.prerm.debhelper debian/python-cpopen.substvars debian/rules debian/source/format tests/tests.py cpopen-1.4/setup.py0000664000175000017500000000077512600771012016043 0ustar ybronheiybronhei00000000000000from distutils.core import setup, Extension ext_modules = [Extension('cpopen.cpopen', sources=['cpopen/cpopen.c'], extra_link_args=['-fPIE', '-Wl,-z,relro,-z,now'])] setup(name='cpopen', version='1.4', description='Creates a subprocess in simpler safer manner', license="GNU GPLv2+", author='Yaniv Bronhaim', author_email='ybronhei@redhat.com', url='redhat.com', packages=['cpopen'], ext_modules=ext_modules) cpopen-1.4/cpopen/0000775000175000017500000000000012606230076015612 5ustar ybronheiybronhei00000000000000cpopen-1.4/cpopen/__init__.py0000664000175000017500000001074012600767570017735 0ustar ybronheiybronhei00000000000000# # Copyright 2012 Red Hat, Inc. # # 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 # # Refer to the README and COPYING files for full details of the license # """ Python's implementation of Popen forks back to python before execing. Forking a python proc is a very complex and volatile process. This is a simpler method of execing that doesn't go back to python after forking. This allows for faster safer exec. """ import inspect import os import sys from subprocess import Popen, PIPE from cpopen import createProcess SUPPORTS_RESTORE_SIGPIPE = ( 'restore_sigpipe' in inspect.getargspec(Popen.__init__).args ) class CPopen(Popen): def __init__(self, args, close_fds=False, cwd=None, env=None, deathSignal=0, childUmask=None, stdin=PIPE, stdout=PIPE, stderr=PIPE, restore_sigpipe=False): if not isinstance(args, list): args = list(args) self._childUmask = childUmask self._deathSignal = int(deathSignal) if SUPPORTS_RESTORE_SIGPIPE: kw = {'restore_sigpipe': restore_sigpipe} else: kw = {} Popen.__init__(self, args, close_fds=close_fds, cwd=cwd, env=env, stdin=stdin, stdout=stdout, stderr=stderr, **kw) def _execute_child_v276( self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, to_close, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, restore_sigpipe=False ): return self._execute_child_v275( args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, restore_sigpipe=restore_sigpipe ) def _execute_child_v275( self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, restore_sigpipe=False ): if env is not None and not isinstance(env, list): env = list(("=".join(item) for item in env.iteritems())) try: pid, stdin, stdout, stderr = createProcess( args, close_fds, p2cread or -1, p2cwrite or -1, c2pread or -1, c2pwrite or -1, errread or -1, errwrite or -1, cwd, env, self._deathSignal, self._childUmask, restore_sigpipe ) self.pid = pid except: # Keep the original exception and reraise it after all fds are # closed, ignoring error during close. This is needed only for # Python 2.6, as Python 2.7 already does this when _execute_child # raises. t, v, tb = sys.exc_info() for fd in ( p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, ): try: if fd: os.close(fd) except OSError: pass raise t, v, tb # If child was started, close the unused fds on the parent side. Note # that we don't want to hide exceptions here. for fd in ( p2cread, errwrite, c2pwrite ): if fd: os.close(fd) if 'to_close' in inspect.getargspec(Popen._execute_child).args: _execute_child = _execute_child_v276 else: _execute_child = _execute_child_v275 cpopen-1.4/cpopen/cpopen.c0000664000175000017500000002251512600767570017257 0ustar ybronheiybronhei00000000000000/* * Copyright 2012-2014 Red Hat, Inc. * * 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 * * Refer to the README and COPYING files for full details of the license */ #include #include #include #include #include #include #include #include static PyObject *createProcess(PyObject *self, PyObject *args); static PyMethodDef CreateProcessMethods[]; static void closeFDs(int errnofd); static int restoreSIGPIPEDefaultHandler(void); /* Python boilerplate */ static PyMethodDef CreateProcessMethods[] = { {"createProcess", createProcess, METH_VARARGS, "Execute a command."}, {NULL, NULL, 0, NULL} /* Sentinel */ }; PyMODINIT_FUNC initcpopen(void) { PyObject *m; m = Py_InitModule("cpopen", CreateProcessMethods); /* In the future put other init code after this condition. */ if (m == NULL) return; } /* Just like close() but retries on interrupt */ static int safeClose(int fd) { int rv; do { rv = close(fd); } while ((rv < 0) && (errno == EINTR)); return rv; } /* Closes all open FDs except for stdin, stdout and stderr */ static void closeFDs(int errnofd) { DIR *dp; int dfd; struct dirent *ep; int fdNum = -1; dfd = open("/proc/self/fd/", O_RDONLY); dp = fdopendir(dfd); while ((ep = readdir(dp))) { if(sscanf(ep->d_name, "%d", &fdNum) < 1) { continue; } if (fdNum < 3) { continue; } if (fdNum == dfd) { continue; } if (fdNum == errnofd) { continue; } safeClose(fdNum); } /* Closes dp and the underlying dfd */ closedir(dp); } static int restoreSIGPIPEDefaultHandler(void) { struct sigaction sa; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sa.sa_handler = SIG_DFL; return sigaction(SIGPIPE, &sa, NULL); } static void freeStringArray(char** arr) { char** item; for (item = arr; *item != NULL; item++) { PyMem_Free(*item); } free(arr); } /* Copies the strings from a python list to a null terminated array. * The strings are shallow copied and are owned by python. * Don't keep this array after the call. * * Returns a NULL terminated array of null strings. On error returns NULL and * sets the python error accordingly */ static char** pyListToArray(PyObject* list, int checkIfEmpty) { int argn; int i; char** argv; if (!PyList_Check(list)) { PyErr_SetString(PyExc_TypeError, "Argument must be a python list"); return NULL; } argn = PyList_Size(list); if ((checkIfEmpty) && (argn < 1)) { PyErr_SetString(PyExc_ValueError, "List must not be empty"); return NULL; } argv = calloc(argn + 1, sizeof(char*)); if (!argv) { PyErr_SetFromErrno(PyExc_OSError); return NULL; } for (i = 0; i < argn; i++) { if (!PyArg_Parse(PyList_GetItem(list, i), "et;", Py_FileSystemDefaultEncoding, &argv[i])) { PyErr_SetString(PyExc_TypeError, "createProcess() arg 2 must contain only strings"); goto fail; } } return argv; fail: freeStringArray(argv); return NULL; } static long pyTryIntToLong(PyObject *intNum, int *gotIt) { long value = 0; if (PyInt_Check(intNum)) { value = PyInt_AsLong(intNum); if (value == -1 && PyErr_Occurred()) { *gotIt = 0; } else { *gotIt = 1; } } return value; } /* Python's implementation of Popen forks back to python before execing. * Forking a python proc is a very complex and volatile process. * * This is a simpler method of execing that doesn't go back to python after * forking. This allows for faster safer exec. * * return NULL on error and sets the python error accordingly. */ static PyObject * createProcess(PyObject *self, PyObject *args) { int cpid; int deathSignal = 0; int rv; int outfd[2] = {-1, -1}; int in1fd[2] = {-1, -1}; int in2fd[2] = {-1, -1}; int errnofd[2] = {-1, -1}; int childErrno = 0; PyObject* pyArgList; PyObject* pyEnvList; const char* cwd; int close_fds = 0; char** argv = NULL; char** envp = NULL; PyObject *childUmask; int hasUmask = 0; int mask; int restore_sigpipe = 0; if (!PyArg_ParseTuple(args, "O!iiiiiiizOiOi:createProcess;", &PyList_Type, &pyArgList, &close_fds, &outfd[0], &outfd[1], &in1fd[0], &in1fd[1], &in2fd[0], &in2fd[1], &cwd, &pyEnvList, &deathSignal, &childUmask, &restore_sigpipe)) { return NULL; } argv = pyListToArray(pyArgList, 1); if (!argv) { goto fail; } if (PyList_Check(pyEnvList)) { envp = pyListToArray(pyEnvList, 0); if (!envp) { goto fail; } } /* failure is not critical, we just leave umask as it is. */ mask = pyTryIntToLong(childUmask, &hasUmask); if (mask < 0) { hasUmask = 0; } if(pipe2(errnofd, O_CLOEXEC) < 0) { PyErr_SetFromErrno(PyExc_OSError); goto fail; } try_fork: cpid = fork(); if (cpid < 0) { if (errno == EAGAIN || errno == EINTR ) { goto try_fork; } PyErr_SetFromErrno(PyExc_OSError); goto fail; } if (!cpid) { safeClose(0); safeClose(1); safeClose(2); dup2(outfd[0], 0); dup2(in1fd[1], 1); dup2(in2fd[1], 2); safeClose(outfd[0]); safeClose(outfd[1]); safeClose(in1fd[0]); safeClose(in1fd[1]); safeClose(in2fd[0]); safeClose(in2fd[1]); safeClose(errnofd[0]); if (deathSignal) { childErrno = prctl(PR_SET_PDEATHSIG, deathSignal); if (childErrno < 0) { childErrno = errno; } /* Check that parent did not already die between fork and us * setting the death signal */ if (write(errnofd[1], &childErrno, sizeof(int)) < sizeof(int)) { exit(-1); } if (childErrno != 0) { exit(-1); } } if (close_fds) { closeFDs(errnofd[1]); } if (cwd) { if (chdir(cwd) < 0) { goto sendErrno; } setenv("PWD", cwd, 1); } if (hasUmask) { umask(mask); } if (restore_sigpipe) { if (restoreSIGPIPEDefaultHandler() < 0) { goto sendErrno; } } exec: if (envp) { execvpe(argv[0], argv, envp); } else { execvp(argv[0], argv); } if (errno == EINTR || errno == EAGAIN ) { goto exec; } sendErrno: if (write(errnofd[1], &errno, sizeof(int)) < 0) { exit(errno); } exit(-1); } safeClose(errnofd[1]); errnofd[1] = -1; if (deathSignal) { /* death signal sync point */ while (1) { rv = read(errnofd[0], &childErrno, sizeof(int)); if (rv < 0) { switch (errno) { case EINTR: case EAGAIN: break; default: PyErr_SetString(PyExc_OSError, strerror(errno)); goto fail; } } else if (rv < sizeof(int)) { /* Invalid response size from child */ PyErr_SetString(PyExc_OSError, strerror(EIO)); goto fail; } break; } if (childErrno != 0) { errno = childErrno; PyErr_SetFromErrno(PyExc_OSError); goto fail; } } /* error sync point */ if (read(errnofd[0], &childErrno, sizeof(int)) == sizeof(int)) { errno = childErrno; PyErr_SetFromErrno(PyExc_OSError); goto fail; } safeClose(errnofd[0]); errnofd[0] = -1; /* From this point errors shouldn't occur, if they do something is very * very very wrong */ freeStringArray(argv); if (envp) { freeStringArray(envp); } return Py_BuildValue("(iiii)", cpid, outfd[1], in1fd[0], in2fd[0]); fail: if (argv) { freeStringArray(argv); } if (envp) { freeStringArray(envp); } if (errnofd[0] >= 0) { safeClose(errnofd[0]); } if (errnofd[1] >= 0) { safeClose(errnofd[1]); } return NULL; } cpopen-1.4/COPYING0000664000175000017500000004312212540262576015372 0ustar ybronheiybronhei00000000000000 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 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 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 Library General Public License instead of this License. cpopen-1.4/tests/0000775000175000017500000000000012606230076015470 5ustar ybronheiybronhei00000000000000cpopen-1.4/tests/tests.py0000664000175000017500000002025312600767641017215 0ustar ybronheiybronhei00000000000000# # Copyright 2012-2014 Red Hat, Inc. # # 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 # # Refer to the README and COPYING files for full details of the license # import errno import os import sys import stat import subprocess from nose.plugins.skip import SkipTest import signal import threading import time import tempfile import shutil import signal import sysconfig from unittest import TestCase def distutils_dir_name(dname): """Returns the name of a distutils build directory""" f = "{dirname}.{platform}-{version[0]}.{version[1]}" return f.format(dirname=dname, platform=sysconfig.get_platform(), version=sys.version_info) TESTS_DIR = os.path.dirname(__file__) BUILD_DIR = os.path.join(TESTS_DIR, "..", "build", distutils_dir_name("lib")) sys.path = [BUILD_DIR] + sys.path import cpopen from cpopen import CPopen EXT_ECHO = "/bin/echo" class TestCPopen(TestCase): def testEcho(self): data = "Hello" p = CPopen([EXT_ECHO, "-n", data]) p.wait() self.assertTrue(p.returncode == 0, "Process failed: %s" % os.strerror(p.returncode)) self.assertEquals(p.stdout.read(), data) def testCat(self): path = "/etc/passwd" p = CPopen(["cat", path]) p.wait() self.assertTrue(p.returncode == 0, "Process failed: %s" % os.strerror(p.returncode)) with open(path, "r") as f: self.assertEquals(p.stdout.read(), f.read()) def testCloseFDs(self): with open("/dev/zero") as f: p = CPopen(["sleep", "1"], close_fds=True) try: child_fds = set(os.listdir("/proc/%s/fd" % p.pid)) finally: p.kill() p.wait() self.assertEqual(child_fds, set(["0", "1", "2"])) def testNoCloseFds(self): with open("/dev/zero") as f: p = CPopen(["sleep", "1"], close_fds=False) try: child_fds = set(os.listdir("/proc/%s/fd" % p.pid)) finally: p.kill() p.wait() # We cannot know which fds will be inherited in the child since the # test framework may open some fds. self.assertTrue(str(f.fileno()) in child_fds) def testEnv(self): p = CPopen(["printenv"], env={"key": "value"}) out, err = p.communicate() self.assertEqual(out, "key=value\n") def testEnvUnicodeKey(self): p = CPopen(["printenv"], env={u"\u05d0": "value"}) out, err = p.communicate() self.assertEqual(out, "\xd7\x90=value\n") def testEnvUnicodeValue(self): p = CPopen(["printenv"], env={"key": u"\u05d0"}) out, err = p.communicate() self.assertEqual(out, "key=\xd7\x90\n") def testCwd(self): cwd = "/proc" p = CPopen(["python", "-c", "import os; print os.getcwd()"], cwd=cwd) p.wait() self.assertTrue(p.returncode == 0, "Process failed: %s" % os.strerror(p.returncode)) self.assertEquals(p.stdout.read().strip(), cwd) def testRunNonExecutable(self): self.assertRaises(OSError, CPopen, ["/tmp"]) def testBadCwd(self): self.assertRaises(OSError, CPopen, ["echo", "hello"], cwd="/~~~~~dasdas~~~~") def testUnicodeArg(self): data = u'hello' cmd = [EXT_ECHO, "-n", data] p = CPopen(cmd) p.wait() p2 = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p2.wait() self.assertEquals(p.stdout.read(), p2.stdout.read()) def testNonASCIIUnicodeArg(self): data = u'\u05e9\u05dc\u05d5\u05dd' # If the default encoding is not utf-8 the test *should* fail as non # ascii conversion shouldn't work if sys.getfilesystemencoding() != "UTF-8": raise SkipTest("The default encoding isn't unicode") cmd = [EXT_ECHO, "-n", data] p = CPopen(cmd) p.wait() p2 = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p2.wait() self.assertEquals(p.stdout.read(), p2.stdout.read()) def testStdin(self): data = "Hello World" p = CPopen(["cat"]) p.stdin.write(data) p.stdin.flush() p.stdin.close() p.wait() self.assertTrue(p.returncode == 0, "Process failed: %s" % os.strerror(p.returncode)) self.assertEquals(p.stdout.read(), data) def testStdinEpoll(self): import select data = "Hello World" p = CPopen(["cat"]) ep = select.epoll() ep.register(p.stdin, select.EPOLLOUT) fd, ev = ep.poll(1)[0] ep.close() os.write(fd, data) p.stdin.close() p.wait() self.assertTrue(p.returncode == 0, "Process failed: %s" % os.strerror(p.returncode)) self.assertEquals(p.stdout.read(), data) def testDeathSignal(self): # This is done because assignment in python doesn't cross scopes procPtr = [None] def spawn(): procPtr[0] = CPopen(["sleep", "1"], deathSignal=signal.SIGKILL) t = threading.Thread(target=spawn) t.start() t.join() self.assertEqual(procPtr[0].wait(), -signal.SIGKILL) def testUmaskChange(self): p = CPopen(['umask'], childUmask=0o007) p.wait() out = p.stdout.readlines() self.assertEquals(out[0].strip(), '0007') def testUmaskTmpfile(self): tmp_dir = tempfile.mkdtemp() try: name = os.path.join(tmp_dir, "file.txt") p = CPopen(['touch', name], childUmask=0o007) p.wait() data = os.stat(name) self.assertTrue(data.st_mode & stat.S_IROTH == 0, "%s is world-readable" % name) self.assertTrue(data.st_mode & stat.S_IWOTH == 0, "%s is world-writeable" % name) self.assertTrue(data.st_mode & stat.S_IXOTH == 0, "%s is world-executable" % name) finally: shutil.rmtree(tmp_dir) def testNoEnt(self): try: CPopen(['there-is-no-executable-with-this/funny/name']) except OSError as ose: self.assertEquals(ose.errno, errno.ENOENT) else: self.fail('OSError not raised') def testNoStreams(self): p = CPopen(['true'], stdin=None, stdout=None, stderr=None) self.assertIsNone(p.stdin) self.assertIsNone(p.stdout) self.assertIsNone(p.stderr) p.wait() self.assertEquals(p.returncode, 0) # references about pipe/SIGPIPE tests: # https://bugzilla.redhat.com/show_bug.cgi?id=1117751#c4 # http://bugs.python.org/issue1652 def testBrokenPipe(self): p = CPopen(["sleep", "1"]) try: p.send_signal(signal.SIGPIPE) finally: p.kill() p.wait() self.assertEqual(p.returncode, -signal.SIGKILL) def testBrokenPipeSIGPIPERestored(self): if not cpopen.SUPPORTS_RESTORE_SIGPIPE: raise SkipTest("subprocess module does not support restore_sigpipe") p = CPopen(["sleep", "1"], restore_sigpipe=True) try: p.send_signal(signal.SIGPIPE) finally: p.kill() p.wait() self.assertEqual(p.returncode, -signal.SIGPIPE) cpopen-1.4/MANIFEST.in0000664000175000017500000000021612577515575016104 0ustar ybronheiybronhei00000000000000include AUTHORS COPYING readme.md PKG-INFO MANIFEST include *.in include Makefile include tests/*.py include debian/* include debian/source/* cpopen-1.4/python-cpopen.spec.in0000664000175000017500000000611412600767641020423 0ustar ybronheiybronhei00000000000000%{!?python_ver: %global python_ver %(%{__python} -c "import sys ; print sys.version[:3]")} %global __provides_exclude_from ^%{python_sitearch}/.*\\.so$ %global libname cpopen Name: python-%{libname} Version: @VERSION@ Release: @RELEASE@%{?dist} Summary: Creates a sub-process in simpler safer manner License: GPLv2+ Group: System Environment/Libraries URL: http://pypi.python.org/pypi/cpopen Source0: http://bronhaim.fedorapeople.org/cpopen-%{version}.tar.gz BuildRequires: python2-devel Provides: vdsm-python-cpopen = 4.13.2 Obsoletes: vdsm-python-cpopen <= 4.14 %description Python package for creating sub-process in simpler and safer manner by using C code. %prep %setup -q -n %{libname}-%{version} %build CPOPEN_VERSION=%{version} %{__python} setup.py build %install CPOPEN_VERSION=%{version} %{__python} setup.py install --root $RPM_BUILD_ROOT %files %doc AUTHORS COPYING README %{python_sitearch}/%{libname}/__init__.py* %{python_sitearch}/%{libname}-%{version}-py*.egg-info %attr(755, root, root) %{python_sitearch}/%{libname}/%{libname}.so* %changelog * Thu Sep 24 2015 Yaniv Bronhaim - 1.4 * Adding sigpipe handler - fix compatibility with python 2.7.5-33 * Sat Jun 13 2015 Yaniv Bronhaim - 1.3.2 - Fixing mishmash in versioning and rpm lint * Mon Oct 27 2014 Saggi Mizrahi - 1.3.1-5 - Add RELRO to LDFLAGS - New brew build with ppc * Wed Jul 30 2014 Yaniv Bronhaim - 1.3.1-4 - raising version to latest build - no changes in the code, just comparing to koji release number * Tue Jun 24 2014 Yaniv Bronhaim - 1.3.1 - fix compatibility with F20's python 2.7.5-12 * Sun Apr 6 2014 Yaniv Bronhaim - 1.3 - Tagging 1.3 * Thu Jan 2 2014 Yaniv Bronhaim - 1.2.3-7 - Changing Obsoletes and Provides of vdsm-python-cpopen package * Wed Dec 25 2013 Yaniv Bronhaim - 1.2.3-6 - Bumping version for RHEL build * Wed Dec 11 2013 Yaniv Bronhaim - 1.2.3-5 - Adding umask configuration to the child process * Mon Oct 28 2013 Yaniv Bronhaim - 1.2.3-4 - Wrong code were packed on previous release * Wed Oct 23 2013 Yaniv Bronhaim - 1.2.3-3 - Override old packages with same file names * Mon Aug 26 2013 Yaniv Bronhaim - 1.2.3-2 - Fixing import error in __init__.py * Sun Aug 25 2013 Yaniv Bronhaim - 1.2.3-1 - Moving files under cpopen folder * Wed Jun 12 2013 Yaniv Bronhaim - 1.2.2-1 - Merging vdsm-python-cpopen fixes - Renaming to cpopen.so * Tue Mar 19 2013 Yaniv Bronhaim 1.2.1-1 - Changing ownership and mod of cpopen-createprocess.so file * Wed Mar 13 2013 Yaniv Bronhaim 1.2-1 - Renaming createprocess to cpopen-createprocess * Tue Feb 05 2013 Yaniv Bronhaim 1.1-1 - Fix dependencies - Adding AUTHORS file * Sun Jan 20 2013 Yaniv Bronhaim 1.0-1 - Initial take cpopen-1.4/PKG-INFO0000664000175000017500000000036012606230076015422 0ustar ybronheiybronhei00000000000000Metadata-Version: 1.0 Name: cpopen Version: 1.4 Summary: Creates a subprocess in simpler safer manner Home-page: redhat.com Author: Yaniv Bronhaim Author-email: ybronhei@redhat.com License: GNU GPLv2+ Description: UNKNOWN Platform: UNKNOWN cpopen-1.4/AUTHORS0000664000175000017500000000042012540262576015401 0ustar ybronheiybronhei00000000000000The project current primary maintainers with commit access are: Saggi Mizrahi Yaniv Bronheim Patches have also been contributed by: Dan Kenigsberg [....send patches to get your name here....] cpopen-1.4/Makefile0000664000175000017500000000162112600767641015775 0ustar ybronheiybronhei00000000000000VERSION=1.4 RELEASE=0 NAME=cpopen FULL_NAME=${NAME}-${VERSION} TAR_FILE=${FULL_NAME}.tar.gz SPECFILE=python-cpopen.spec DIST=dist TAR_DIST_LOCATION=${DIST}/${TAR_FILE} all: build .PHONY: build rpm srpm ${TAR_DIST_LOCATION} check-local dist check ${SPECFILE}: ${SPECFILE}.in sed \ -e s/@VERSION@/${VERSION}/g \ -e s/@RELEASE@/${RELEASE}/g \ $< > $@ build: CPOPEN_VERSION=${VERSION} python setup.py build check: check-local check-local: build nosetests tests/tests.py dist: $(TAR_DIST_LOCATION) $(TAR_DIST_LOCATION): mkdir -p dist CPOPEN_VERSION=${VERSION} python setup.py sdist srpm: ${SPECFILE} $(TAR_DIST_LOCATION) dist rpmbuild --define "_sourcedir `pwd`/${DIST}" -bs python-cpopen.spec rpm: ${SPECFILE} ${TAR_DIST_LOCATION} dist rpmbuild --define "_sourcedir `pwd`/${DIST}" -ba python-cpopen.spec clean: CPOPEN_VERSION=${VERSION} python setup.py clean rm -rf $(DIST) rm -rf build