pglistener-4/0000755000000000000000000000000012504520537010264 5ustar pglistener-4/hooks/0000755000000000000000000000000011414314221011375 5ustar pglistener-4/hooks/copy-ssh-keys.sh0000644000000000000000000000076611414314221014460 0ustar #!/bin/sh # # Copy SSH keys from one directory to another, while changing the owner to # root and setting the mode to 600. src="/var/lib/pglistener/sshkeys/" dst="/var/lib/misc/sshkeys/" # copy files from $src to $dst (cd "$src"; find -maxdepth 1 -type f \ -exec install -m644 -oroot -groot '{}' "$dst" ';') # remove files from $dst which aren't in $src (cd "$dst"; find -maxdepth 1 -type f \ '(' -exec test ! -e "$src/{}" ';' \ -exec rm '{}' ';' \ ')') pglistener-4/starter.py0000755000000000000000000000256511414314221012323 0ustar #!/usr/bin/env python # Postgres Listener, writes out flatfiles when SQL NOTIFYs are triggered # Copyright (C) 2005 Rob Bradford # Copyright (C) 2007-8 Robert McQueen # # 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. import os import sys from pglistener import config, daemon pidfile = '/var/run/pglistener/pglistener.pid' def main(argv): config_files = argv[1:] try: listeners = list(config.read_configs(config_files)) except RuntimeError: print >>sys.stderr, "pglistener: couldn't read configuration file" return 1 daemon.daemonize(pidfile) daemon.run(listeners) return 0 if __name__ == '__main__': sys.exit(main(sys.argv)) pglistener-4/setup.py0000644000000000000000000000023112504520537011772 0ustar from distutils.core import setup setup(name='pglistener', version='4', py_modules=['pglistener'], scripts=['useradm/bin/pua'] ) pglistener-4/COPYING0000644000000000000000000004310311414314221011306 0ustar GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. pglistener-4/README0000644000000000000000000000063211414314221011133 0ustar == Installation Hints == === Hooks === * Allow the pglisten user to run any commands in /var/lib/pglisten/hooks as root using sudo. This is useful for changing ownership of files. === NSS === * Ensure that the DB backend for NSS is installed. * Enable the db backend for for the passwd/group/shadow entries in nssswitch.conf. * Create symlinks from /var/lib/misc/*.db to the generated files. pglistener-4/update.py0000755000000000000000000000065511414314221012117 0ustar #!/usr/bin/env python import sys from pglistener import config def main(argv): configfile = argv[1] sections = argv[2:] listeners = dict([(l.name, l) for l in config.read_configs(configfile)]) if not sections: sections = listeners.keys() for section in sections: listeners[section].connect() listeners[section].do_update() if __name__ == '__main__': main(sys.argv) pglistener-4/AUTHORS0000644000000000000000000000020211414314221011314 0ustar Rob Bradford Robert McQueen Dafydd Harries pglistener-4/pglistener/0000755000000000000000000000000012336457125012445 5ustar pglistener-4/pglistener/nssgroupdb.py0000644000000000000000000000211711414314221015167 0ustar # Postgres Listener, writes out flatfiles when SQL NOTIFYs are triggered # Copyright (C) 2005 Rob Bradford # Copyright (C) 2007-8 Robert McQueen # # 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. from nssdb import NssDb class NssGroupDb(NssDb): def __init__(self,options): options['format'] = "%s:%s:%d:%s" options['db-keys'] = { 0:".%s", 2:"=%d" } NssDb.__init__(self,options) pglistener-4/pglistener/__init__.py0000644000000000000000000000000011414314221014525 0ustar pglistener-4/pglistener/pglistener.py0000644000000000000000000000563411414314221015164 0ustar # Postgres Listener, writes out flatfiles when SQL NOTIFYs are triggered # Copyright (C) 2005 Rob Bradford # Copyright (C) 2007-8 Robert McQueen # Copyright (C) 2008 Collabora Ltd. # # 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. import errno import os import select import stat import syslog class PgListener: def __init__(self, options): """Creates object and make connection to server and setup a cursor for the connection.""" self.sleeptime = 0 self.options = options self.name = options['name'] self.dsn = options['dsn'] self.query = options['query'] self.notifications = options['notifications'] self.destination = options['destination'] self.conn = None def err(self, msg): syslog.syslog(syslog.LOG_ERR, "%s: %s" % (self.name, msg)) def info(self, msg): syslog.syslog(syslog.LOG_INFO, "%s: %s" % (self.name, msg)) def do_format(self, row): """Apply the format string against a row.""" return self.options['format'].replace('\\n', '\n') % row def write_file(self, path, f): tmp = path + "~" fh = open(tmp, "w+") try: f(fh) finally: fh.close() self.do_perms(path, tmp) os.rename(tmp, path) def do_write(self, result, target): """For each row in the result set apply the format and write it out to the target file.""" def write_results(fh): for row in result: fh.write(self.do_format(row)) self.write_file(target, write_results) def do_perms(self, source, target): """Apply the same file permissions from the original destination version of the file to the target.""" if os.path.exists(source): orig = os.stat(source) try: os.chmod(target, orig[stat.ST_MODE]) except select.error, (errno, strerror): self.err("failed to chmod new file: %s" % strerror) def do_posthooks(self): """Execute all the provided hooks.""" for hook in self.options.get('posthooks', '').strip().splitlines(): self.info("executing: %s" % hook) os.system(hook) pglistener-4/pglistener/sshkeys.py0000644000000000000000000000345211414314221014475 0ustar # Postgres Listener, writes out flatfiles when SQL NOTIFYs are triggered # Copyright (C) 2008 Collabora Ltd. # # 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. import os import syslog from pglistener import PgListener class SshKeys(PgListener): def do_format(self, row): return ' '.join(row) + '\n' def do_write(self, result, target): if not os.path.exists(target): os.mkdir(target) keys = {} for username, key_type, key_base64, comment in result: if username not in keys: keys[username] = [] keys[username].append((key_type, key_base64, comment)) for username, values in keys.iteritems(): PgListener.do_write(self, values, os.path.join(target, username)) # Remove old files. for name in os.listdir(target): if name in ('.', '..'): continue if name not in keys: path = os.path.join(target, name) try: os.unlink(path) except OSError: self.log(syslog.LOG_WARNING, "failed to unlink %s" % path) pglistener-4/pglistener/nssshadowdb.py0000644000000000000000000000212411414314221015316 0ustar # Postgres Listener, writes out flatfiles when SQL NOTIFYs are triggered # Copyright (C) 2005 Rob Bradford # Copyright (C) 2007-8 Robert McQueen # # 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. from nssdb import NssDb class NssShadowDb(NssDb): def __init__(self,options): options['format'] = "%s:%s:13045:0:99999:7:::" options['db-keys'] = { 0:".%s" } NssDb.__init__(self,options) pglistener-4/pglistener/mailinglist.py0000644000000000000000000000336011414314221015316 0ustar # Postgres Listener, writes out flatfiles when SQL NOTIFYs are triggered # Copyright (C) 2008 Collabora Ltd. # # 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. import os import syslog from pglistener import PgListener class MailingList(PgListener): def do_format(self, row): return row + '\n' def do_write(self, result, target): if not os.path.exists(target): os.mkdir(target) lists = {} for list, emailaddress in result: if list not in lists: lists[list] = [] lists[list].append((emailaddress)) for list, values in lists.iteritems(): PgListener.do_write(self, values, os.path.join(target, list)) # Remove old files. for name in os.listdir(target): if name in ('.', '..'): continue if name not in lists: path = os.path.join(target, name) try: os.unlink(path) except OSError: self.log(syslog.LOG_WARNING, "failed to unlink %s" % path) pglistener-4/pglistener/apachevhost.py0000644000000000000000000000207411414314221015310 0ustar # Postgres Listener, writes out flatfiles when SQL NOTIFYs are triggered # Copyright (C) 2005 Rob Bradford # Copyright (C) 2007-8 Robert McQueen # # 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. from pglistener import PgListener class ApacheVhost(PgListener): def __init__(self,options): options['format']="%s\t%s/webs/%s\n" PgListener.__init__(self,options) pglistener-4/pglistener/flatfile.py0000644000000000000000000000244612322427771014612 0ustar # Postgres Listener, writes out flatfiles when SQL NOTIFYs are triggered # Copyright (C) 2005 Rob Bradford # Copyright (C) 2007-8 Robert McQueen # # 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. from pglistener import PgListener class FlatFile(PgListener): def __init__(self,options): if(not options.has_key('delimiter')): options['delimiter']='\t' PgListener.__init__(self,options) def do_format(self,row): if self.options.has_key('format'): return self.options['format'].decode("string-escape").format(*row) else: return self.options['delimiter'].join(row) +"\n" pglistener-4/pglistener/gitolite.py0000644000000000000000000000360712322427771014644 0ustar # Postgres Listener, writes out flatfiles when SQL NOTIFYs are triggered # Copyright (C) 2008 Collabora Ltd. # Copyright (C) 2013 Varnish Software AS # # 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. import os import hashlib from sshkeys import SshKeys class Gitolite(SshKeys): def do_write(self, result, target): if not os.path.exists(target): os.mkdir(target) fnames = [] for username, key_type, key_base64, comment in result: fname = "{0}@{1}.pub".format(username, hashlib.md5(key_base64).hexdigest()) fnames.append(fname) self.write_file(os.path.join(target, fname), lambda fh: fh.write(self.do_format([key_type, key_base64, comment]))) # Remove old files. for name in os.listdir(target): if name in ('.', '..'): continue if name not in fnames: path = os.path.join(target, name) try: os.unlink(path) except OSError: self.err("failed to unlink %s" % path) pglistener-4/pglistener/daemon.py0000644000000000000000000001463512322427771014272 0ustar import errno import os import pwd import re import select import sys import syslog import time import socket import psycopg2 import psycopg2.extensions def close_stdio(): fh = file(os.devnull, 'r') os.dup2(fh.fileno(), 0) fh.close() fh = file(os.devnull, 'w') os.dup2(fh.fileno(), 1) os.dup2(fh.fileno(), 2) fh.close() class FakeStderr: def write(self, s): for line in s.rstrip().splitlines(): syslog.syslog(syslog.LOG_ERR, line) def daemonize(pidfile): # Open the PID file before we fork, so that our parent will see an error # if we fail. fd = os.open(pidfile, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0644) fh = os.fdopen(fd, 'w') pid = os.fork() if pid != 0: os._exit(0) os.setsid() pid = os.fork() if pid != 0: fh.write('%d\n' % pid) fh.close() os._exit(0) close_stdio() sys.stderr = FakeStderr() def format_dsn(dsn): matches = re.findall('([^\s=]+)=(\S+)', dsn) acc = [] for k, v in matches: if k != 'password': acc.append('%s=%s' % (k, v)) return ' '.join(acc) class Daemon: def __init__(self, listeners): self.connections = {} self.listeners = listeners self.sleeptime = 1 self.last_sleep = 0 def err(self, message): syslog.syslog(syslog.LOG_ERR, message) def info(self, message): syslog.syslog(syslog.LOG_INFO, message) def sleep(self): # Reset if stuff has been fine for five minutes if time.time() > self.last_sleep + 300: self.sleeptime = 1 time.sleep(sleeptime) if sleeptime < 128: sleeptime *= 2 self.last_sleep = time.time() def _make_connection(self, dsn): return psycopg2.connect(dsn) def make_connection(self, dsn): while True: self.info("connecting to: %s" % format_dsn(dsn)) try: return self._make_connection(dsn) except psycopg2.DatabaseError, e: self.err("error: %s" % e) self.sleep() def query(self, listener): while True: connection = self.connections[listener.dsn] cursor = connection.cursor() if hasattr(socket, 'SO_KEEPALIVE'): fd = None try: fd = cursor.fileno() except AttributeError: fd = cursor.connection.fileno() except AttributeError: pass else: s = socket.fromfd(fd, socket.AF_INET, socket.SOCK_STREAM) # avoid unix sockets if type(s.getsockname()) == type(()): s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) try: cursor.execute(listener.query) return cursor.fetchall() except psycopg2.DatabaseError, e: self.err("error: %s" % e) self.err("reconnecting and retrying") self.connections[listener.dsn] = \ self.make_connection(listener.dsn) self.sleep() def get_notifications(self, conn, cursor = None): # Newer psycopg needs poll, but older doesn't have it. try: conn.poll() except AttributeError: conn.cursor().isready() notifications = [name for pid, name in conn.notifies] conn.notifies[:] = [] return notifications def wait_for_notifications(self): connections = self.connections.values() # Backwards compatibility if not hasattr(connections[0], 'fileno'): connections = [x.cursor() for x in connections] try: readables, _, _ = select.select(connections, [], [], None) except select.error, (err, strerror): if err == errno.EINTR: return [] else: raise notifications = set() for obj in readables: conn = obj if hasattr(obj, 'connection'): # conn is a cursor, not a connection conn = conn.connection try: notifications.update( self.get_notifications(conn)) except psycopg2.DatabaseError, e: # Probably end of file due to losing the connection. # Reconnect. self.err(str(e)) for dsn, c in self.connections.iteritems(): if c is conn: self.connections[dsn] = self.make_connection(dsn) self.sleep() return notifications def update(self, listener): self.info("updating: %s (%s)" % (listener.name, listener.destination)) results = self.query(listener) listener.do_write(results, listener.destination) listener.do_posthooks() def do_iteration(self): notifications = self.wait_for_notifications() for notification in notifications: self.info("got notification: %s" % notification) for listener in self.listeners: if notifications & set(listener.notifications): self.update(listener) def loop(self): while True: self.do_iteration() def listen(self): for dsn, conn in self.connections.iteritems(): listens = [] cursor = conn.cursor() for listener in self.listeners: if listener.dsn == dsn: self.info("%s: listening for: %s" % (listener.name, ' '.join(listener.notifications))) listens.extend(listener.notifications) for listen in listens: cursor.execute('listen \"%s\"' % listen) def openlog(self): syslog.openlog('pglistener', syslog.LOG_PID, syslog.LOG_DAEMON) def run(self): self.info('starting up') for listener in self.listeners: if listener.dsn not in self.connections: conn = self.make_connection(listener.dsn) conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) self.connections[listener.dsn] = conn for listener in self.listeners: self.update(listener) self.listen() self.loop() def run(listeners): daemon = Daemon(listeners) daemon.run() pglistener-4/pglistener/nssdb.py0000644000000000000000000000267212336457125014137 0ustar # Postgres Listener, writes out flatfiles when SQL NOTIFYs are triggered # Copyright (C) 2005 Rob Bradford # Copyright (C) 2007-8 Robert McQueen # # 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. from pglistener import PgListener import bsddb.db as db import os class NssDb(PgListener): def do_write(self,result,target): tmp = "%s.tmp" % (target, ) _db = db.DB() _db.open(tmp, None, db.DB_BTREE, db.DB_CREATE|db.DB_TRUNCATE, mode=0644) db_keys = self.options['db-keys'] for index, row in enumerate(result): entry = self.do_format(row) + '\0' for field in db_keys.keys(): _db.put(db_keys[field] % row[field], entry) _db.put("0%d" % index, entry) _db.sync() _db.close() os.rename(tmp, target) pglistener-4/pglistener/simpledbm.py0000644000000000000000000000213711414314221014757 0ustar # Postgres Listener, writes out flatfiles when SQL NOTIFYs are triggered # Copyright (C) 2005 Rob Bradford # Copyright (C) 2007-8 Robert McQueen # # 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. import dbhash from pglistener import PgListener class SimpleDBM(PgListener): def do_write(self,result,target): db=dbhash.open(target,"n") for row in result: db[row[0]]=row[1] db.sync() pglistener-4/pglistener/nsspasswddb.py0000644000000000000000000000213111414314221015330 0ustar # Postgres Listener, writes out flatfiles when SQL NOTIFYs are triggered # Copyright (C) 2005 Rob Bradford # Copyright (C) 2007-8 Robert McQueen # # 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. from nssdb import NssDb class NssPasswdDb(NssDb): def __init__(self,options): options['format'] = "%s:%s:%d:%d:%s:%s:%s" options['db-keys'] = { 0:".%s", 2:"=%d" } NssDb.__init__(self,options) pglistener-4/pglistener/config.py0000644000000000000000000000174111414314221014250 0ustar import glob import os import sys from ConfigParser import RawConfigParser def expand_dirs(paths): file_paths = [] for path in paths: if os.path.isdir(path): file_paths.extend([ p for p in glob.glob('%s/*.cfg' % path) if os.path.isfile(p)]) else: file_paths.append(path) return file_paths def read_configs(paths): file_paths = expand_dirs(paths) cf = RawConfigParser() if cf.read(file_paths) != file_paths: raise RuntimeError("couldn't read config file") for section in cf.sections(): classname = cf.get(section, 'class') modname = 'pglistener.%s' % classname.lower() __import__(modname) cls = getattr(sys.modules[modname], classname) options = dict(cf.items(section)) options['name'] = section options['notifications'] = [ n.strip() for n in options['notifications'].split(',')] yield cls(options) pglistener-4/test.py0000644000000000000000000001510111414314221011601 0ustar import bsddb import os import sys import shutil import tempfile import unittest import coverage from pglistener import pglistener from pglistener.config import read_configs from pglistener.daemon import Daemon from pglistener.flatfile import FlatFile from pglistener.nsspasswddb import NssPasswdDb class TestListener(pglistener.PgListener): def __init__(self, options): pglistener.PgListener.__init__(self, options) def log(self, priority, message): pass class PgListenerTest(unittest.TestCase): def setUp(self): self.tmpdir = tempfile.mkdtemp() def runTest(self): destination = os.path.join(self.tmpdir, 'destination') listener = TestListener({ 'name': 'fake', 'dsn': 'fake', 'notifications': [], 'destination': destination, 'format': '%s:%s\\n', 'query': 'fake query' }) listener.do_write([('a', '1'), ('b', '2')], listener.destination) self.assertEquals('a:1\nb:2\n', file(destination).read()) def tearDown(self): shutil.rmtree(self.tmpdir) class NssPasswdDbTest(unittest.TestCase): def setUp(self): self.tmpdir = tempfile.mkdtemp() def runTest(self): destination = os.path.join(self.tmpdir, 'destination') listener = NssPasswdDb({ 'name': 'fake', 'dsn': 'fake', 'notifications': [], 'destination': destination, 'format': '%s:%s\\n', 'query': 'fake query' }) listener.do_write([ ('amy', 'x', 1000, 1000, 'amy', '/home/amy', '/bin/bash'), ('beth', 'x', 1001, 1001, 'beth', '/home/beth', '/bin/zsh')], listener.destination) db = bsddb.btopen(listener.destination, "r") self.assertEquals( 'amy:x:1000:1000:amy:/home/amy:/bin/bash\x00', db['.amy']) self.assertEquals( 'beth:x:1001:1001:beth:/home/beth:/bin/zsh\x00', db['=1001']) db.close() def tearDown(self): shutil.rmtree(self.tmpdir) class FlatFileTest(unittest.TestCase): def setUp(self): self.tmpdir = tempfile.mkdtemp() def runTest(self): destination = os.path.join(self.tmpdir, 'destination') listener = FlatFile({ 'name': 'fake', 'dsn': 'fake', 'notifications': [], 'destination': destination, 'query': 'fake query' }) listener.do_write([('1', 'foo'), ('2', 'bar')], listener.destination) self.assertEquals('1\tfoo\n2\tbar\n', file(listener.destination).read()) def tearDown(self): shutil.rmtree(self.tmpdir) class ConfigTest(unittest.TestCase): def setUp(self): self.tmpdir = tempfile.mkdtemp() def runTest(self): config_file = os.path.join(self.tmpdir, 'pglistener.cfg') config_dir = os.path.join(self.tmpdir, 'pglistener.d') os.mkdir(config_dir) def write_file(path, s): fh = file(path, 'w') fh.write(s) fh.close() config_str = ( '[%s]\n' + 'class = NssDb\n' + 'notifications = foo\n' + 'dsn = fake\n' + 'query = fake\n' + 'destination = fake\n') write_file(config_file, config_str % 'foo') write_file(os.path.join(config_dir, 'bar.cfg'), config_str % 'bar') (foo, bar) = list(read_configs([config_file, config_dir])) self.assertEquals('foo', foo.name) self.assertEquals('bar', bar.name) def tearDown(self): shutil.rmtree(self.tmpdir) class DaemonTest(unittest.TestCase): def runTest(self): class FakeCursor(object): def execute(self, query): pass def fetchall(self): return "fake data" def isready(self): return True def fileno(self): (rfd, wfd) = os.pipe() os.write(wfd, '\0') return rfd class FakeConnection(object): notifies = [(0, 'fake notification')] def cursor(self): return FakeCursor() def set_isolation_level(self, level): pass class Listener(object): def __init__(self): self.dsn = 'hostname=fake,password=foo' self.name = 'fake name' self.query = 'fake query' self.destination = 'fake destination' self.notifications = ['fake notification'] self.log = [] def log(self, *data): self.log.append(data) def do_write(self, data, destination): self.log.append(('do_write', data, destination)) def do_posthooks(self): self.log.append(('do_posthooks',)) class TestDaemon(Daemon): def _make_connection(self, dsn): return FakeConnection() def err(self, msg): #print 'err: %s' % msg pass def info(self, msg): #print 'info: %s' % msg pass def openlog(self): pass def loop(self): pass listener = Listener() daemon = TestDaemon([listener]) daemon.run() daemon.do_iteration() # Second iteration should do nothing since the connection's # notification list will have been emptied. daemon.do_iteration() self.assertEquals( [('do_write', 'fake data', 'fake destination'), ('do_posthooks',), ('do_write', 'fake data', 'fake destination'), ('do_posthooks',)], listener.log) def run_coverage(*args): os.spawnlp(os.P_WAIT, 'python', 'python', coverage.__file__, *args) def find_python_files(path): for dirpath, dirnames, filenames in os.walk(path): # Filter out non-packages. dirnames[:] = [d for d in dirnames if os.path.exists(os.path.join(dirpath, d, '__init__.py'))] for filename in filenames: if filename.endswith('.py'): yield os.path.join(dirpath, filename) def main(): for i in range(1, len(sys.argv)): if sys.argv[i] == '-c': del sys.argv[i] run_coverage('-e') run_coverage('-x', __file__, *sys.argv[1:]) files = list(find_python_files('.')) run_coverage('-r', *files) run_coverage('-a', *files) raise SystemExit(0) unittest.main() if __name__ == '__main__': main() pglistener-4/example.cfg0000644000000000000000000000174411414314221012374 0ustar [DEFAULT] DSN=dbname=bluelinux user=blvhost password=xxx [test1] class=PgListener notifications=['asdf','fsda'] query=select webdomainname,homedir from vhost_hosts format=%%s %%s\n destination=vhost.test posthooks=[] [test2] class=FlatFileListener DSN=dbname=bluelinux user=blvhost password=xxx notifications=['asdf','fsda'] query=select webdomainname,homedir from vhost_hosts destination=vhost.test posthooks=[] [passwd] class=NssPasswdDb DSN=dbname=bluelinux user=blnss password=xxx notifications=['customers'] query=select name,passwd,uid,gid,gecos,dir,shell from nss_passwd destination=nss/passwd.db posthooks=[] [group] class=NssGroupDb DSN=dbname=bluelinux user=blnss password=xxx notifications=['customers'] query=select name,passwd,gid,member from nss_group destination=nss/group.db posthooks=[] [shadow] class=NssShadowDb DSN=dbname=bluelinux user=blpam password=xxx notifications=['customers'] query=select name,passwd from nss_shadow destination=nss-shadow/shadow.db posthooks=[] pglistener-4/useradm/0000755000000000000000000000000011414314221011712 5ustar pglistener-4/useradm/etc/0000755000000000000000000000000011414314221012465 5ustar pglistener-4/useradm/etc/pua.conf0000644000000000000000000000010011414314221014110 0ustar DBHOST=localhost DBNAME=accounts DBUSER=useradmin DBPASS=secret pglistener-4/useradm/bin/0000755000000000000000000000000012502646745012504 5ustar pglistener-4/useradm/bin/pua0000755000000000000000000002175412502646745013230 0ustar #! /usr/bin/perl use strict; use warnings; use Config::File; use FindBin; use DBI; use lib "/usr/share/pglistener/perl"; use Sys::Syslog; use Term::ReadLine; use 5.010; use feature ":5.10"; use utf8; use Pglistener::Schema; use Data::Dumper; binmode STDOUT, ":utf8"; my $config = Config::File::read_config_file("/etc/pua.conf"); my $schema = Pglistener::Schema->connect("dbi:Pg:dbname=" . $config->{DBNAME} . ";host=" . $config->{DBHOST}, $config->{DBUSER}, $config->{DBPASS}, {pg_enable_utf8 => 1}) or die $DBI::errstr; my $currentuser = undef; my $default_groups = $config->{DEFAULT_GROUPS}; my @extra_fields_account = (); if ($config->{EXTRA_FIELDS_ACCOUNT}) { @extra_fields_account = split /\s+/, $config->{EXTRA_FIELDS_ACCOUNT}; my $rs = $schema->resultset('Account'); $rs->result_source->add_columns(@extra_fields_account); Pglistener::Schema::Result::Account->add_columns(@extra_fields_account); for my $col (@extra_fields_account) { Pglistener::Schema::Result::Account->register_column($col); } } sub help() { q[ Create new user: new $name [--groupname] Edit a particular user: enter (part of) the name When editing a user, the following commands are available: C-d/EOF to exit the current user SSH keys: ssh list ssh add [host $hostname], reads string, waits for C-d ssh delete $id Setting and getting fields: set name $name set shell $shell set password $md5sum set gpg_key $gpg_fingerprint show [$field] disable enable revoke [--community] Managing group membership group list group add $group group delete $group Managing email addresses email list email add $email [--customary] email delete $email ] } my $term = new Term::ReadLine 'Pglistener account management'; sub get_prompt { my $u = shift; return "cmd >> " unless defined $u; return sprintf "cmd [user=%s] >> ", $u->username; } sub create_new_user { my ($OUT, $schema, $username, $groups) = (@_); $groups ||= $default_groups; my $txn = sub { my $user = $schema->resultset('Account')->create({ username => $username, name => 'Not set yet' }); if ($groups) { for my $group (split /\s+/, $groups) { my $g = $schema->resultset('Group')->search( { name => $group }); $user->add_to_groups($g->first); } } return $user; }; my $user = $schema->txn_do($txn); return $user; } sub find_and_set_user { my ($OUT, $schema, $line) = (@_); my @accounts; @accounts = $schema->resultset('Account')->search( [ { username => $line } ]); if (scalar @accounts == 1) { return $accounts[0]; } @accounts = $schema->resultset('Account')->search( [ { name => { like => "%$line%" } }, { username => { like => "%$line%" } } ] ); if (scalar @accounts > 1) { print $OUT "Search '$line' matches more than one user\n"; for my $account (@accounts) { printf $OUT "%s (%s)\n", $account->name, $account->username; } } elsif (scalar @accounts == 1) { return $accounts[0]; } else { print $OUT help(); } return undef; } sub ssh_keys_list { my ($OUT, $user) = (@_); my $host = ""; for my $key ($user->sshkeys->search(undef, { order_by => "hostname" })) { if (not $key->hostname ~~ $host) { printf $OUT "Host: %s\n", $key->hostname // "All"; } printf $OUT "%d %s %s\n", $key->ssh_key_id, $key->key_base64, $key->comment; $host = $key->hostname; } } sub ssh_keys_add { my ($OUT, $IN, $user, $hostname) = (@_); my $string; print $OUT "Waiting for SSH key, end with '.' alone on a line\n"; { local $/ = "\n.\n"; $string = <$IN> }; my ($key, $comment) = ($string =~ m/(?:ssh-rsa\s+)?(\S+)\s+(\S+)/s); $user->sshkeys->create( { key_base64 => $key, comment => $comment, account_id => $user->account_id, hostname => $hostname }); } sub ssh_keys_delete { my ($OUT, $user, $keyid) = (@_); $user->sshkeys->search({ssh_key_id => $keyid})->delete; } sub user_set_field { my ($OUT, $user, $field, $value) = (@_); eval { $user->update({$field => $value}); }; if ($@) { print $OUT $@; } } sub user_print_field { my ($OUT, $user, $field) = (@_); eval { printf $OUT "%-20s: %s\n", $field, $user->$field // ''; }; if ($@ && $@ =~ "^Can't locate object method") { print $OUT "No such field $field\n"; } } sub user_revoke { my ($OUT, $user, $schema, $community) = (@_); my $txn = sub { $user->update({ password => undef, shell => '/bin/false', enabled => 'false'}); my $active_groups = $user->groups->search( { name => { 'NOT IN' => [ 'everyone', 'collabora', 'multimedia' ] }}); if ($active_groups->count > 0) { $user->remove_from_groups($user->groups->search( { name => { 'NOT IN' => [ 'everyone', 'collabora', 'multimedia' ] }})); } if ($user->groups->count > 0) { $user->remove_from_groups($user->groups->search); } if (defined $community and $community) { $user->sshkeys->update_all({ hostname => 'dhansak.collabora.co.uk' }); user_groups_add($OUT, $user, $schema, "community"); } else { $user->sshkeys->delete_all; } #$user->emails->delete_all; }; $schema->txn_do($txn); } sub user_groups_list { my ($OUT, $user) = (@_); for my $group ($user->groups->search(undef, { order_by => "name" })) { printf $OUT "%s\n", $group->name; } } sub user_groups_add { my ($OUT, $user, $schema, $group) = (@_); my $g = $schema->resultset('Group')->search( { name => $group }); $user->add_to_groups($g->first); } sub user_groups_delete { my ($OUT, $user, $group) = (@_); $user->remove_from_groups($user->groups->search({name => $group})); } sub email_list { my ($OUT, $user) = (@_); for my $email ($user->emails->search(undef, { order_by => ["domainpart","localpart"] })) { printf $OUT "%s %s@%s\n", $email->customary ? "*" : " ", $email->localpart, $email->domainpart; } } sub email_add { my ($OUT, $user, $email, $customary) = (@_); my ($localpart, $domainpart) = split "@", $email; if (not defined $customary) { if ($user->emails->count == 0) { $customary = 'true'; } } $user->emails->create( { localpart => $localpart, domainpart => $domainpart, customary => $customary }); } sub email_delete { my ($OUT, $user, $email) = (@_); my ($localpart, $domainpart) = split "@", $email; $user->emails->search({localpart => $localpart, domainpart => $domainpart})->delete; } my $attribs = $term->Attribs; $attribs->{completion_function} = sub { my ($text, $line, $start) = @_; return qw(a list of candidates to complete); }; my $OUT = $term->OUT || \*STDOUT; my $IN = $term->IN || \*STDIN; while (1) { my $line = $term->readline(get_prompt($currentuser)); last unless (defined $line or defined $currentuser); if (not defined $currentuser) { given ($line) { when (/^new (\S+)(?: -?-?(\S+))?$/) { $currentuser = create_new_user($OUT, $schema, $1, $2); } when (/^(\S+)$/) { $currentuser = find_and_set_user($OUT, $schema, $line); } default { print $OUT help(); } } } else { if (not defined $line) { undef $currentuser; next; } my $extra_set_group = join "|", @extra_fields_account; my $extra_set = qr/set ($extra_set_group) (.+)/; given ($line) { when (/^(?:cd\s*)?\.\./) { undef $currentuser; } when ("ssh list") { ssh_keys_list($OUT, $currentuser); } when (/ssh add(?: -?-?host[=\s](\S+))?/) { ssh_keys_add($OUT, $IN, $currentuser, $1); } when (/ssh delete (\d+)/) { ssh_keys_delete($OUT, $currentuser, $1); } when (/set name\s+(.+)/) { user_set_field($OUT, $currentuser, name => $1); } when (/set shell (\S+)/) { user_set_field($OUT, $currentuser, shell => $1); } when ($extra_set) { user_set_field($OUT, $currentuser, $1 => $2); } when (/set gpg_key (.+)/) { user_set_field($OUT, $currentuser, gpg_key => $1); } when (/show(?: (.+))?/) { if (defined $1) { user_print_field($OUT, $currentuser, $1); } else { for my $f (qw(account_id username name shell enabled gpg_key), @extra_fields_account) { user_print_field($OUT, $currentuser, $f); } } } when (/disable/) { user_set_field($OUT, $currentuser, enabled => 'false'); } when (/enable/) { user_set_field($OUT, $currentuser, enabled => 'true'); } when (/revoke(\s+-?-?community)?/) { user_revoke($OUT, $currentuser, $schema, $1); } when (/^groups?( list|$)/) { user_groups_list($OUT, $currentuser); } when (/group add (\S+)/) { user_groups_add($OUT, $currentuser, $schema, $1); } when (/group delete (\S+)/) { user_groups_delete($OUT, $currentuser, $1); } when (/emails? list/) { email_list($OUT, $currentuser); } when (/email add (\S+)( +-?-?customary)?/) { email_add($OUT, $currentuser, $1, (defined $2 ? 'true' : 'false')); } when (/email delete (\S+)/) { email_delete($OUT, $currentuser, $1); } default { print $OUT help(); } } } $term->addhistory($line) if ($line =~ /\S/ and not defined $term->Features->{autohistory}); } pglistener-4/useradm/lib/0000755000000000000000000000000012502641411012463 5ustar pglistener-4/useradm/lib/Pglistener/0000755000000000000000000000000012502641411014577 5ustar pglistener-4/useradm/lib/Pglistener/Schema.pm0000644000000000000000000000014312502640603016335 0ustar package Pglistener::Schema; use base qw/DBIx::Class::Schema/; __PACKAGE__->load_namespaces(); 1; pglistener-4/useradm/lib/Pglistener/Schema/0000755000000000000000000000000011414314221015774 5ustar pglistener-4/useradm/lib/Pglistener/Schema/Result/0000755000000000000000000000000012502646650017267 5ustar pglistener-4/useradm/lib/Pglistener/Schema/Result/Group.pm0000644000000000000000000000053011414314221020702 0ustar package Pglistener::Schema::Result::Group; use base qw/DBIx::Class::Core/; __PACKAGE__->table('grp'); __PACKAGE__->add_columns(qw/grp_id name/); __PACKAGE__->set_primary_key('grp_id'); __PACKAGE__->has_many(account_grp => 'Pglistener::Schema::Result::AccountGrp', "grp_id"); __PACKAGE__->many_to_many(members => 'account_grp', 'account'); 1; pglistener-4/useradm/lib/Pglistener/Schema/Result/SSHKey.pm0000644000000000000000000000051011414314221020712 0ustar package Pglistener::Schema::Result::SSHKey; use base qw/DBIx::Class::Core/; __PACKAGE__->table('ssh_key'); __PACKAGE__->add_columns(qw/ ssh_key_id account_id key_base64 comment hostname /); __PACKAGE__->set_primary_key('ssh_key_id'); __PACKAGE__->belongs_to(account => 'Pglistener::Schema::Result::Account', "account_id"); 1; pglistener-4/useradm/lib/Pglistener/Schema/Result/Account.pm0000644000000000000000000000106212502646650021220 0ustar package Pglistener::Schema::Result::Account; use base qw/DBIx::Class::Core/; __PACKAGE__->table('account'); __PACKAGE__->add_columns(qw/ account_id username name shell enabled gpg_key/); __PACKAGE__->set_primary_key('account_id'); __PACKAGE__->has_many(sshkeys => 'Pglistener::Schema::Result::SSHKey', "account_id" ); __PACKAGE__->has_many(account_grp => 'Pglistener::Schema::Result::AccountGrp', "account_id" ); __PACKAGE__->many_to_many(groups => 'account_grp', 'grp'); __PACKAGE__->has_many(emails => 'Pglistener::Schema::Result::Email', "account_id" ); 1; pglistener-4/useradm/lib/Pglistener/Schema/Result/AccountGrp.pm0000644000000000000000000000061111414314221021653 0ustar package Pglistener::Schema::Result::AccountGrp; use base qw/DBIx::Class::Core/; __PACKAGE__->table('account_grp'); __PACKAGE__->add_columns(qw/ account_id grp_id /); __PACKAGE__->set_primary_key('account_id', 'grp_id'); __PACKAGE__->belongs_to(account => 'Pglistener::Schema::Result::Account', "account_id"); __PACKAGE__->belongs_to(grp => 'Pglistener::Schema::Result::Group', "grp_id"); 1; pglistener-4/useradm/lib/Pglistener/Schema/Result/Email.pm0000644000000000000000000000050512502301026020635 0ustar package Pglistener::Schema::Result::Email; use base qw/DBIx::Class::Core/; __PACKAGE__->table('email'); __PACKAGE__->add_columns(qw/ localpart domainpart account_id customary email_id /); #__PACKAGE__->set_primary_key('email_id'); __PACKAGE__->belongs_to(account => 'Pglistener::Schema::Result::Account', "account_id"); 1; pglistener-4/debian/0000755000000000000000000000000012504525105011502 5ustar pglistener-4/debian/pglistener.dirs0000644000000000000000000000006311414314221014532 0ustar /etc/init.d /etc/pglistener /etc/pglistener/conf.d pglistener-4/debian/control0000644000000000000000000000072112504521330013101 0ustar Source: pglistener Section: misc Priority: optional Build-Depends: debhelper (>= 9), python Maintainer: Tollef Fog Heen X-Python-Versions: all Standards-Version: 3.9.6 Package: pglistener Depends: python, python-psycopg2, lsb-base (>= 3.0-6), adduser, ${misc:Depends} Recommends: libnss-db Suggests: libdbix-class-perl Architecture: all Description: Postgres listener Daemon that generates files from Postgres when Postgres data is modified. pglistener-4/debian/pglistener.docs0000644000000000000000000000000712504524612014527 0ustar README pglistener-4/debian/pglistener.examples0000644000000000000000000000003012504524263015413 0ustar example.cfg example.sql pglistener-4/debian/pglistener.lintian-overrides0000644000000000000000000000027712504520647017252 0ustar pglistener: init.d-script-missing-dependency-on-remote_fs etc/init.d/pglistener: required-start pglistener: init.d-script-missing-dependency-on-remote_fs etc/init.d/pglistener: required-stop pglistener-4/debian/compat0000644000000000000000000000000211414314221012672 0ustar 5 pglistener-4/debian/pglistener.postrm0000644000000000000000000000065611414314221015125 0ustar #! /bin/sh set -e case "$1" in remove|upgrade|failed-upgrade|abort-install|abort-upgrade|disappear) ;; purge) getent passwd pglisten >/dev/null && \ if [ -x /usr/sbin/deluser ]; then deluser --quiet --system pglisten fi rm -rf /var/lib/pglistener ;; *) echo "postrm called with unknown argument \`$1'" >&2 exit 1 esac #DEBHELPER# exit 0 pglistener-4/debian/copyright0000644000000000000000000000260112504521022013426 0ustar Downloaded from http://cgit.collabora.com/git/user/tfheen/pglistener.git/ Initially packaged by Dafydd Harries Now mainained by Tollef Fog Heen Copyright: Copyright (C) 2005 Rob Bradford Copyright (C) 2007-8 Robert McQueen Copyright (C) 2008 Collabora Ltd Copyright (C) 2013 Varnish Software AS Copyright (C) 2010-2015 Tollef Fog Heen Authors: Rob Bradford Robert McQueen Dafydd Harries Tollef Fog Heen Licence: 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. please see /usr/share/common-licenses/GPL-2 for the full text of the GPL version 2. pglistener-4/debian/pglistener.postinst0000644000000000000000000000130511414314221015454 0ustar #! /bin/sh set -e case "$1" in configure) if ! getent passwd pglisten >/dev/null; then echo "Creating pglistener user account..." adduser --home /var/lib/pglistener \ --gecos "pgListener system user" \ --system --quiet --group --disabled-password pglisten fi mkdir -p /var/lib/pglistener/hooks chown pglisten:pglisten /var/lib/pglistener/hooks chown pglisten:pglisten /etc/pglistener chmod 700 /etc/pglistener ;; abort-upgrade|abort-remove|abort-deconfigure) ;; *) echo "postinst called with unknown argument \`$1'" >&2 exit 1 ;; esac #DEBHELPER# exit 0 pglistener-4/debian/pglistener.init0000644000000000000000000000465011416614565014562 0ustar #! /bin/sh ### BEGIN INIT INFO # Provides: pglistener # Required-Start: # Required-Stop: # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: PGListener # Description: PostgreSQL listener ### END INIT INFO # Author: Dafydd Harries PATH=/sbin:/usr/sbin:/bin:/usr/bin DESC="PostgreSQL listener" NAME=pglistener STARTER=/usr/share/pglistener/starter.py DAEMON=/usr/bin/python CONFIG="/etc/pglistener/pglistener.cfg /etc/pglistener/conf.d" DAEMON_ARGS="$STARTER $CONFIG" PIDFILE=/var/run/$NAME/$NAME.pid SCRIPTNAME=/etc/init.d/$NAME # Exit if the package is not installed [ -e "$STARTER" ] || exit 0 # Read configuration variable file if it is present [ -r /etc/default/$NAME ] && . /etc/default/$NAME . /lib/init/vars.sh . /lib/lsb/init-functions do_start() { # Return # 0 if daemon has been started # 1 if daemon was already running # 2 if daemon could not be started mkdir -p /var/run/pglistener chown pglisten:pglisten /var/run/pglistener start-stop-daemon --start --quiet --pidfile $PIDFILE --chuid pglisten \ --exec $DAEMON --test > /dev/null \ || return 1 start-stop-daemon --start --quiet --pidfile $PIDFILE --chuid pglisten \ --exec $DAEMON -- $DAEMON_ARGS \ || return 2 } do_stop() { # Return # 0 if daemon has been stopped # 1 if daemon was already stopped # 2 if daemon could not be stopped # other if a failure occurred start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE RETVAL="$?" [ "$RETVAL" = 2 ] && return 2 # Many daemons don't delete their pidfiles when they exit. rm -f $PIDFILE return "$RETVAL" } case "$1" in start) [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME" do_start case "$?" in 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;; 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;; esac ;; stop) [ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME" do_stop case "$?" in 0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;; 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;; esac ;; restart|force-reload) log_daemon_msg "Restarting $DESC" "$NAME" do_stop case "$?" in 0|1) do_start case "$?" in 0) log_end_msg 0 ;; 1) log_end_msg 1 ;; # Old process is still running *) log_end_msg 1 ;; # Failed to start esac ;; *) # Failed to stop log_end_msg 1 ;; esac ;; *) echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2 exit 3 ;; esac : pglistener-4/debian/rules0000755000000000000000000000012312504520024012551 0ustar #!/usr/bin/make -f # -*- makefile -*- %: dh $@ --parallel --builddirectory=build pglistener-4/debian/changelog0000644000000000000000000000634312504525105013362 0ustar pglistener (4) unstable; urgency=medium * Add missing ${misc:Depends} to Depends. * Add lintian overrides. * Switch build system to dh, use setup.py. * Add libnss-db to Recommends. -- Tollef Fog Heen Wed, 18 Mar 2015 14:57:02 +0100 pglistener (3) unstable; urgency=low * Use @ instead of . as pubkey separator for gitolite. -- Tollef Fog Heen Mon, 18 Mar 2013 13:23:57 +0100 pglistener (2) unstable; urgency=low * Add format support to flatfile * Add gitolite handler * pua updates to handle email field -- Tollef Fog Heen Mon, 18 Mar 2013 13:15:39 +0100 pglistener (1) unstable; urgency=low * Switch versioning to just be an integer. * Fix race condition in nssdb.py where a database would be temporarily empty. * Freedesktop.org uses slightly different db, fix pua for them. * Move libdbix-class-perl to suggests, it's just needed for pua. * Make myself the maintainer. * Update debian/copyright to be useful. -- Tollef Fog Heen Mon, 25 Apr 2011 18:32:03 +0200 pglistener (0-11) lenny; urgency=low * Make sure to import psycopg2.extensions too, to make even newer versions of psycopg2 happy. -- Tollef Fog Heen Wed, 14 Jul 2010 12:10:18 +0200 pglistener (0-10) lenny; urgency=low * Get rid of postgresql from Required-Start and Required-Stop in the init script. -- Tollef Fog Heen Mon, 12 Jul 2010 15:33:37 +0200 pglistener (0-9) lenny; urgency=low * Make this compatible with newer versions of psycopg2. -- Tollef Fog Heen Mon, 12 Jul 2010 15:21:13 +0200 pglistener (0-8) lenny; urgency=low * Add user administration tool. -- Tollef Fog Heen Thu, 15 Apr 2010 09:00:22 +0200 pglistener (0-7) lenny; urgency=low * Fix typo -- Tollef Fog Heen Thu, 25 Feb 2010 08:48:37 +0100 pglistener (0-6) lenny; urgency=low * Turn on TCP keepalives if possible. This should make us better at detecting when the connection goes away. -- Tollef Fog Heen Tue, 16 Feb 2010 11:36:10 +0100 pglistener (0-5) lenny; urgency=low * Fix silly typo in starter.py and update.py where it would fail to start since config.read_config has now been renamed to config.read_configs. * Make starter.py only look at argv[1:] to avoid trying to parse itself as a config file. -- Tollef Fog Heen Tue, 08 Sep 2009 11:26:18 +0200 pglistener (0-4) lenny; urgency=low [ Dafydd Harries ] * Add support for config directories in addition to a single file. * Add more tests. [ Tollef Fog Heen ] * Add myself to uploaders. * Look for configs in /etc/pglistener/conf.d by default. -- Tollef Fog Heen Fri, 28 Aug 2009 23:30:19 +0200 pglistener (0-3) lenny; urgency=low * Make sure to include the sshkeys class -- Tollef Fog Heen Thu, 21 May 2009 18:56:22 +0200 pglistener (0-2) lenny; urgency=low * Add MailingList class -- Tollef Fog Heen Thu, 21 May 2009 11:10:15 +0200 pglistener (0-1) unstable; urgency=low * Initial package. -- Dafydd Harries Thu, 20 Nov 2008 13:18:22 +0000 pglistener-4/debian/pglistener.install0000644000000000000000000000041011414314221015233 0ustar pglistener/*.py /usr/share/pglistener/pglistener starter.py /usr/share/pglistener update.py /usr/share/pglistener hooks/copy-ssh-keys.sh /usr/share/doc/pglistener/examples useradm/bin/* /usr/bin useradm/etc/* /etc useradm/lib/Pglistener /usr/share/pglistener/perl pglistener-4/.gitignore0000644000000000000000000000004211414314221012236 0ustar .coverage .*.swp *.pyc *,cover *~ pglistener-4/example.sql0000644000000000000000000000667412322427771012461 0ustar CREATE OR REPLACE FUNCTION notify() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN EXECUTE 'NOTIFY ' || quote_ident(tg_relname); EXECUTE 'NOTIFY update'; DELETE FROM last_updated; INSERT INTO last_updated DEFAULT VALUES; RETURN NULL; END; $$; CREATE FUNCTION commas_sfunc(a text, b text) RETURNS text AS $$ begin if a = '' then return b; else return a || ',' || b; end if; end; $$ LANGUAGE plpgsql; CREATE AGGREGATE commas(text) ( SFUNC = commas_sfunc, STYPE = text, INITCOND = '' ); CREATE FUNCTION hostname(ip inet) RETURNS character varying LANGUAGE plperlu AS $_$ @_[0] =~ /(\d+)[.](\d+)[.](\d+)[.](\d+)/; my $ip = pack 'W4', $1, $2, $3, $4; my $name = gethostbyaddr($ip, 2); return $name; $_$; CREATE TABLE account ( account_id serial PRIMARY KEY, username varchar(20) NOT NULL, name varchar NOT NULL, shell varchar DEFAULT '/bin/bash'::varchar NOT NULL, password varchar, enabled boolean DEFAULT false NOT NULL, gpg_key varchar, email varchar, CONSTRAINT account_id_check CHECK ((account_id >= 1000)) ); CREATE TABLE phone ( account_id integer REFERENCES account(account_id), phone_no varchar(30), phone_type varchar(30) ); CREATE TABLE grp ( grp_id serial PRIMARY KEY, name varchar(20) NOT NULL, CONSTRAINT grp_id_check CHECK ((grp_id >= 100)) ); CREATE TABLE account_grp ( account_id integer REFERENCES account(account_id), grp_id integer REFERENCES grp(grp_id) ); CREATE VIEW apache AS SELECT account.username, account.password FROM account JOIN account_grp USING (account_id) JOIN grp USING (grp_id) WHERE (grp.name = 'varnish'::text) AND (account.password IS NOT NULL) AND (account.enabled = true); CREATE TABLE last_updated ( last_updated timestamp without time zone DEFAULT timezone('UTC'::text, now()) NOT NULL ); CREATE TABLE ssh_key ( ssh_key_id serial PRIMARY KEY, account_id integer NOT NULL, key_base64 text NOT NULL, comment text NOT NULL, hostname character varying ); CREATE VIEW ssh_authorized_keys AS SELECT account.username, 'ssh-rsa'::character varying AS keytype, ssh_key.key_base64, ssh_key.comment FROM (ssh_key JOIN account USING (account_id)) WHERE ((account.enabled = true) AND ((ssh_key.hostname IS NULL) OR ((ssh_key.hostname)::text = ((SELECT hostname(pg_stat_activity.client_addr) AS hostname FROM pg_stat_activity WHERE (pg_stat_activity.procpid = pg_backend_pid())))::text))); CREATE RULE notify_delete AS ON DELETE TO account DO NOTIFY update; CREATE RULE notify_delete AS ON DELETE TO phone DO NOTIFY update; CREATE RULE notify_delete AS ON DELETE TO account_grp DO NOTIFY update; CREATE RULE notify_delete AS ON DELETE TO grp DO NOTIFY update; CREATE RULE notify_delete AS ON DELETE TO ssh_key DO NOTIFY update; CREATE RULE notify_insert AS ON INSERT TO account DO NOTIFY update; CREATE RULE notify_insert AS ON INSERT TO phone DO NOTIFY update; CREATE RULE notify_insert AS ON INSERT TO account_grp DO NOTIFY update; CREATE RULE notify_insert AS ON INSERT TO grp DO NOTIFY update; CREATE RULE notify_insert AS ON INSERT TO ssh_key DO NOTIFY update; CREATE RULE notify_update AS ON UPDATE TO account DO NOTIFY update; CREATE RULE notify_update AS ON UPDATE TO phone DO NOTIFY update; CREATE RULE notify_update AS ON UPDATE TO account_grp DO NOTIFY update; CREATE RULE notify_update AS ON UPDATE TO grp DO NOTIFY update; CREATE RULE notify_update AS ON UPDATE TO ssh_key DO NOTIFY update;