pax_global_header00006660000000000000000000000064146036126750014524gustar00rootroot0000000000000052 comment=e229ce3741cc6f1ed07b7e216a628a7c2f1f5d60 pglistener-5.1/000077500000000000000000000000001460361267500135455ustar00rootroot00000000000000pglistener-5.1/.gitignore000066400000000000000000000000121460361267500155260ustar00rootroot00000000000000 *~ *.pyc pglistener-5.1/AUTHORS000066400000000000000000000010761460361267500146210ustar00rootroot00000000000000Rob Bradford Robert McQueen Dafydd Harries Tollef Fog Heen , Maxime Buquet , Jordi Mallach , Vivek Das Mohapatra Paulo Henrique de Lima Santana Bruna Pinos de Oliveira Mark Kennedy Stelios Milidonis Theodotos Andreou Collabora SysAdmin Team pglistener-5.1/COPYING000066400000000000000000000431031460361267500146010ustar00rootroot00000000000000 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-5.1/README.md000066400000000000000000000012501460361267500150220ustar00rootroot00000000000000# Code repository # Package repository # Contact Collabora SysAdmin Team # Manual You can read the manual in manpage/pglistener-update.txt # 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 `nsswitch.conf`. * Create symlinks from `/var/lib/misc/*.db` to the generated files. pglistener-5.1/bin/000077500000000000000000000000001460361267500143155ustar00rootroot00000000000000pglistener-5.1/bin/pglistener000077500000000000000000000026241460361267500164230ustar00rootroot00000000000000#!/usr/bin/env python3 # 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 __future__ import print_function import sys from pglistener import config, daemon PIDFILE = '/run/pglistener/pglistener.pid' def main(argv): config_files = argv[1:] try: listeners = list(config.read_configs(config_files)) except RuntimeError: print("pglistener: couldn't read configuration file", file=sys.stderr) return 1 daemon.daemonize(PIDFILE) daemon.run(listeners) return 0 if __name__ == '__main__': sys.exit(main(sys.argv)) pglistener-5.1/bin/pglistener-update000077500000000000000000000006371460361267500177050ustar00rootroot00000000000000#!/usr/bin/env python3 import sys from pglistener import config def main(argv): configfile = argv[1] sections = argv[2:] listeners = {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-5.1/example.cfg000066400000000000000000000017441460361267500156670ustar00rootroot00000000000000[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-5.1/example.sql000066400000000000000000000066731460361267500157350ustar00rootroot00000000000000 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; pglistener-5.1/hooks/000077500000000000000000000000001460361267500146705ustar00rootroot00000000000000pglistener-5.1/hooks/copy-ssh-keys.sh000066400000000000000000000007651460361267500177520ustar00rootroot00000000000000#!/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-5.1/manpage/000077500000000000000000000000001460361267500151555ustar00rootroot00000000000000pglistener-5.1/manpage/genallman.sh000077500000000000000000000021041460361267500174470ustar00rootroot00000000000000#!/bin/bash # Generate several manpages at the same time. # Copyright (C) 2014-2015 Joao Eriberto Mota Filho # v0.3, available at https://github.com/eribertomota/genallman # # You can use this code in the same terms of the BSD-3-clause license or, # optionally, in the same terms of the license used in debian/ directory # when packaging for Debian or similar. # # This script uses txt2man. You need 2 files: program_name.txt and # program_name.header. # # The program_name.header must be use this structure: # # .TH "" "" " " "" # # Example: # # .TH mac-robber "1" "May 2013" "MAC-ROBBER 1.02" "collects data about allocated files in mounted filesystems" [ -f /usr/bin/txt2man ] || { echo "ERROR: txt2man not found."; exit; } for NAME in $(ls | grep header | cut -d'.' -f1) do LEVEL=$(cat $NAME.header | cut -d" " -f3 | tr -d '"') cat $NAME.header > $NAME.$LEVEL txt2man $NAME.txt | grep -v '^.TH ' >> $NAME.$LEVEL echo "Generated $NAME.$LEVEL." done pglistener-5.1/manpage/pglistener-update.1000066400000000000000000000044611460361267500207000ustar00rootroot00000000000000.TH pglistener-update "1" "Apr 2024" "PGLISTENER-UPDATE 5.1" "postgres listener" .\" Text automatically generated by txt2man .SH NAME \fBpglistener-update \fP- postgres listener. \fB .SH DESCRIPTION pglistener-update is a daemon that generates files from Postgres database. .PP It is a tool that listens for notifies from a Postgres database and then calls out to a number of hooks which do everything from updating the password database to updating accounts in RT. .SH USAGE Config and hooks live under: .PP .nf .fam C /var/lib/pglistener /var/lib/pglistener/hooks /etc/pglistener /etc/pglistener/conf.d .fam T .fi It is fine to restart postgres while pglistener is running. .PP If pglistener crashes for whatever reason, it can be restarted as a normal service. .PP Pglistener can in general be restarted at any time, it's quick to start and there are no interruptions to services or authentication. .SH SETTING UP Install a usable pglistener config in /etc/pglistener/pglistener.conf and should be mode 600, user pglistener. .PP Make symlinks for databases in /var/lib/misc: .PP .nf .fam C cd /var/lib/misc ln -s ../pglistener/group.db ln -s ../pglistener/passwd.db ln -s ../pglistener/shadow.db .fam T .fi If you have ssh keys for everybody on the host, add the following two lines to /etc/ssh/sshd_config: .PP .nf .fam C AuthorizedKeysFile /root/%u/.ssh/authorized_keys AuthorizedKeysFile2 /var/lib/misc/sshkeys/%u .fam T .fi Make sure pam_mkhomedir is set up, /etc/pam.d/common-session should contain: .PP .nf .fam C session required pam_mkhomedir.so .fam T .fi .SH AUTHOR The pglistener-update was written by Rob Bradford , Robert McQueen , Dafydd Harries , Tollef Fog Heen , Maxime Buquet , Jordi Mallach , Vivek Das Mohapatra Paulo Henrique de Lima Santana Bruna Pinos de Oliveira Mark Kennedy Stelios Milidonis .PP For a complete list of authors, please open AUTHORS file. .PP This manual page was written by Paulo Henrique de Lima Santana (phls) for the Debian project (but may be used by others). pglistener-5.1/manpage/pglistener-update.header000066400000000000000000000001211460361267500217550ustar00rootroot00000000000000.TH pglistener-update "1" "Apr 2024" "PGLISTENER-UPDATE 5.1" "postgres listener" pglistener-5.1/manpage/pglistener-update.txt000066400000000000000000000042161460361267500213550ustar00rootroot00000000000000NAME pglistener-update - postgres listener. DESCRIPTION pglistener-update is a daemon that generates files from Postgres database. It is a tool that listens for notifies from a Postgres database and then calls out to a number of hooks which do everything from updating the password database to updating accounts in RT. USAGE Config and hooks live under: /var/lib/pglistener /var/lib/pglistener/hooks /etc/pglistener /etc/pglistener/conf.d It is fine to restart postgres while pglistener is running. If pglistener crashes for whatever reason, it can be restarted as a normal service. Pglistener can in general be restarted at any time, it's quick to start and there are no interruptions to services or authentication. SETTING UP Install a usable pglistener config in /etc/pglistener/pglistener.conf and should be mode 600, user pglistener. Make symlinks for databases in /var/lib/misc: cd /var/lib/misc ln -s ../pglistener/group.db ln -s ../pglistener/passwd.db ln -s ../pglistener/shadow.db If you have ssh keys for everybody on the host, add the following two lines to /etc/ssh/sshd_config: AuthorizedKeysFile /root/%u/.ssh/authorized_keys AuthorizedKeysFile2 /var/lib/misc/sshkeys/%u Make sure pam_mkhomedir is set up, /etc/pam.d/common-session should contain: session required pam_mkhomedir.so AUTHOR The pglistener-update was written by Rob Bradford , Robert McQueen , Dafydd Harries , Tollef Fog Heen , Maxime Buquet , Jordi Mallach , Vivek Das Mohapatra Paulo Henrique de Lima Santana Bruna Pinos de Oliveira Mark Kennedy Stelios Milidonis Collabora SysAdmin Team For a complete list of authors, please open AUTHORS file. This manual page was written by Paulo Henrique de Lima Santana (phls) for the Debian project (but may be used by others). pglistener-5.1/manpage/pglistener.1000066400000000000000000000044161460361267500174200ustar00rootroot00000000000000.TH pglistener "1" "Apr 2024" "PGLISTENER 5.1" "postgres listener" .\" Text automatically generated by txt2man .SH NAME \fBpglistener \fP- postgres listener. \fB .SH DESCRIPTION pglistener is a daemon that generates files from Postgres database. .PP It is a tool that listens for notifies from a Postgres database and then calls out to a number of hooks which do everything from updating the password database to updating accounts in RT. .SH USAGE Config and hooks live under: .PP .nf .fam C /var/lib/pglistener /var/lib/pglistener/hooks /etc/pglistener /etc/pglistener/conf.d .fam T .fi It is fine to restart postgres while pglistener is running. .PP If pglistener crashes for whatever reason, it can be restarted as a normal service. .PP Pglistener can in general be restarted at any time, it's quick to start and there are no interruptions to services or authentication. .SH SETTING UP Install a usable pglistener config in /etc/pglistener/pglistener.conf and should be mode 600, user pglistener. .PP Make symlinks for databases in /var/lib/misc: .PP .nf .fam C cd /var/lib/misc ln -s ../pglistener/group.db ln -s ../pglistener/passwd.db ln -s ../pglistener/shadow.db .fam T .fi If you have ssh keys for everybody on the host, add the following two lines to /etc/ssh/sshd_config: .PP .nf .fam C AuthorizedKeysFile /root/%u/.ssh/authorized_keys AuthorizedKeysFile2 /var/lib/misc/sshkeys/%u .fam T .fi Make sure pam_mkhomedir is set up, /etc/pam.d/common-session should contain: .PP .nf .fam C session required pam_mkhomedir.so .fam T .fi .SH AUTHOR The pglistener was written by Rob Bradford , Robert McQueen , Dafydd Harries , Tollef Fog Heen , Maxime Buquet , Jordi Mallach , Vivek Das Mohapatra Paulo Henrique de Lima Santana Bruna Pinos de Oliveira Mark Kennedy Stelios Milidonis .PP For a complete list of authors, please open AUTHORS file. .PP This manual page was written by Paulo Henrique de Lima Santana (phls) for the Debian project (but may be used by others). pglistener-5.1/manpage/pglistener.header000066400000000000000000000001031460361267500204750ustar00rootroot00000000000000.TH pglistener "1" "Apr 2024" "PGLISTENER 5.1" "postgres listener" pglistener-5.1/manpage/pglistener.txt000066400000000000000000000041711460361267500200750ustar00rootroot00000000000000NAME pglistener - postgres listener. DESCRIPTION pglistener is a daemon that generates files from Postgres database. It is a tool that listens for notifies from a Postgres database and then calls out to a number of hooks which do everything from updating the password database to updating accounts in RT. USAGE Config and hooks live under: /var/lib/pglistener /var/lib/pglistener/hooks /etc/pglistener /etc/pglistener/conf.d It is fine to restart postgres while pglistener is running. If pglistener crashes for whatever reason, it can be restarted as a normal service. Pglistener can in general be restarted at any time, it's quick to start and there are no interruptions to services or authentication. SETTING UP Install a usable pglistener config in /etc/pglistener/pglistener.conf and should be mode 600, user pglistener. Make symlinks for databases in /var/lib/misc: cd /var/lib/misc ln -s ../pglistener/group.db ln -s ../pglistener/passwd.db ln -s ../pglistener/shadow.db If you have ssh keys for everybody on the host, add the following two lines to /etc/ssh/sshd_config: AuthorizedKeysFile /root/%u/.ssh/authorized_keys AuthorizedKeysFile2 /var/lib/misc/sshkeys/%u Make sure pam_mkhomedir is set up, /etc/pam.d/common-session should contain: session required pam_mkhomedir.so AUTHOR The pglistener was written by Rob Bradford , Robert McQueen , Dafydd Harries , Tollef Fog Heen , Maxime Buquet , Jordi Mallach , Vivek Das Mohapatra Paulo Henrique de Lima Santana Bruna Pinos de Oliveira Mark Kennedy Stelios Milidonis Collabora SysAdmin Team For a complete list of authors, please open AUTHORS file. This manual page was written by Paulo Henrique de Lima Santana (phls) for the Debian project (but may be used by others). pglistener-5.1/manpage/pua.1000066400000000000000000000032211460361267500160220ustar00rootroot00000000000000.TH pua "1" "Sep 2021" "PUA 5.10" "command line utility to manipulate users" .\" Text automatically generated by txt2man .SH NAME \fBpua \fP- command line utility to manipulate users. \fB .SH DESCRIPTION Command line interface (cli) used with pglistener and manipulate users. .SH USAGE Start using the tool by typing “pua” on console: .PP $ pua .PP To get help, type "?" in the prompt: .PP cmd >> ? .PP Options: .PP .nf .fam C 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 .fam T .fi .SH AUTHOR The pua was written by Rob Bradford , Robert McQueen and Dafydd Harries .PP For a complete list of authors, please open AUTHORS file. .PP This manual page was written by Paulo Henrique de Lima Santana (phls) for the Debian project (but may be used by others). pglistener-5.1/manpage/pua.header000066400000000000000000000001151460361267500171110ustar00rootroot00000000000000.TH pua "1" "Sep 2021" "PUA 5.10" "command line utility to manipulate users" pglistener-5.1/manpage/pua.txt000066400000000000000000000027571460361267500165160ustar00rootroot00000000000000NAME pua - command line utility to manipulate users. DESCRIPTION Command line interface (cli) used with pglistener and manipulate users. USAGE Start using the tool by typing “pua” on console: $ pua To get help, type "?" in the prompt: cmd >> ? Options: 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 AUTHOR The pua was written by Rob Bradford , Robert McQueen and Dafydd Harries For a complete list of authors, please open AUTHORS file. This manual page was written by Paulo Henrique de Lima Santana (phls) for the Debian project (but may be used by others). pglistener-5.1/pglistener/000077500000000000000000000000001460361267500157215ustar00rootroot00000000000000pglistener-5.1/pglistener/__init__.py000066400000000000000000000000001460361267500200200ustar00rootroot00000000000000pglistener-5.1/pglistener/apachevhost.py000066400000000000000000000021111460361267500205730ustar00rootroot00000000000000# 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-5.1/pglistener/config.py000066400000000000000000000017421460361267500175440ustar00rootroot00000000000000 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-5.1/pglistener/daemon.py000066400000000000000000000157201460361267500175430ustar00rootroot00000000000000 import errno import os import pwd import re import select import sys import syslog import time import socket import psycopg2 import psycopg2.extensions HAS_SDNOTIFY = True try: import sdnotify except ImportError: HAS_SDNOTIFY = False def close_stdio(): fh = open(os.devnull, 'r') os.dup2(fh.fileno(), 0) fh.close() fh = open(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, 0o644) 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 self.notifier = None if HAS_SDNOTIFY: self.notifier = sdnotify.SystemdNotifier() 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(self.sleeptime) if self.sleeptime < 128: self.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 as e: self.err("error: %s" % e) self.sleep() def query(self, listener): while True: s = -1 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) # cleanup duplicate socket used for sockopts if s != -1: s.close() return cursor.fetchall() except psycopg2.DatabaseError as 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 = list(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 as err: 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 as e: # Probably end of file due to losing the connection. # Reconnect. self.err(str(e)) for dsn, c in self.connections.items(): 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 watchdog(self): """Use sd_notify to update systemd's watchdog""" if self.notifier is None: return None self.notifier.notify("WATCHDOG=1") def do_iteration(self): self.watchdog() 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.items(): 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-5.1/pglistener/flatfile.py000066400000000000000000000026011460361267500200600ustar00rootroot00000000000000# 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 from .pglistener import PgListener class FlatFile(PgListener): def __init__(self, options): # if not options.has_key('delimiter'): if 'delimiter' not in options: options['delimiter'] = '\t' PgListener.__init__(self, options) def do_format(self, row): if 'format' in self.options: return self.options['format'].decode("string-escape").format(*row) return self.options['delimiter'].join(row) +"\n" pglistener-5.1/pglistener/gitolite.py000066400000000000000000000037021460361267500201150ustar00rootroot00000000000000# 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 functools import partial from sshkeys import SshKeys class Gitolite(SshKeys): def do_write(self, result, target): if not os.path.exists(target): os.mkdir(target) fnames = [] def write_helper(key_type, key_base64, comment, fh): fh.write(self.do_format([key_type, key_base64, comment])) 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), partial(write_helper, 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-5.1/pglistener/mailinglist.py000066400000000000000000000033721460361267500206140ustar00rootroot00000000000000# 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 l, emailaddress in result: if l not in lists: lists[l] = [] lists[l].append((emailaddress)) for l, values in lists.items(): PgListener.do_write( self, values, os.path.join(target, l), ) # 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-5.1/pglistener/nssdb.py000066400000000000000000000036031460361267500174060ustar00rootroot00000000000000# 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 from .pglistener import PgListener import bsddb3.db as bsddb import os class NssDb(PgListener): def do_write(self, result, target): i = 0 tmp = "%s.tmp.%d" % (target, i) while os.path.exists(tmp): i += 1 tmp = "%s.tmp.%d" % (target, i) db = bsddb.DB() db.open( tmp, None, bsddb.DB_BTREE, bsddb.DB_CREATE|bsddb.DB_TRUNCATE, mode=0o644, ) 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(bytes(db_keys[field] % row[field], encoding='utf-8'), entry) #db.put((db_keys[field] % row[field]).encode('utf-8'), entry) db.put(bytes("0%d" % index, encoding='utf-8'), entry) #db.put(b"0%d" % index, entry) db.sync() db.close() os.rename(tmp, target) pglistener-5.1/pglistener/nssgroupdb.py000066400000000000000000000021371460361267500204640ustar00rootroot00000000000000# 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-5.1/pglistener/nsspasswddb.py000066400000000000000000000021511460361267500206250ustar00rootroot00000000000000# 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-5.1/pglistener/nssshadowdb.py000066400000000000000000000021441460361267500206130ustar00rootroot00000000000000# 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-5.1/pglistener/pglistener.py000066400000000000000000000056201460361267500204520ustar00rootroot00000000000000# 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 as err: 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-5.1/pglistener/simpledbm.py000066400000000000000000000021671460361267500202550ustar00rootroot00000000000000# 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-5.1/pglistener/sshkeys.py000066400000000000000000000034271460361267500177720ustar00rootroot00000000000000# 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.items(): 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-5.1/setup.py000066400000000000000000000013401460361267500152550ustar00rootroot00000000000000#!/usr/bin/env python3 from setuptools import setup setup( name='pglistener', version='5.0', author='Collabora SysAdmin Team', author_email='sysadmin@collabora.com', license='GPLv2+', license_file='COPYING', packages=[ 'pglistener', ], scripts=[ 'useradm/bin/pua', 'bin/pglistener', 'bin/pglistener-update', ], install_requires=[ 'python3-psycopg2', ], extra_requires={ 'systemd': ['sdnotify'], }, classifiers=[ 'License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Utilities', ], ) pglistener-5.1/test.py000066400000000000000000000156721460361267500151110ustar00rootroot00000000000000 import bsddb3 import os import socket 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) dest_fd = open(destination) self.assertEqual('a:1\nb:2\n', dest_fd.read()) dest_fd.close() 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 = bsddb3.btopen(listener.destination, "r") self.assertEqual( b'amy:x:1000:1000:amy:/home/amy:/bin/bash\x00', db[b'.amy']) self.assertEqual( b'beth:x:1001:1001:beth:/home/beth:/bin/zsh\x00', db[b'=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) dest_fd = open(destination) self.assertEqual('1\tfoo\n2\tbar\n', dest_fd.read()) dest_fd.close() 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 = open(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.assertEqual('foo', foo.name) self.assertEqual('bar', bar.name) def tearDown(self): shutil.rmtree(self.tmpdir) class DaemonTest(unittest.TestCase): def runTest(self): class FakeCursor(object): def __init__(self, connection): self.connection = connection self.rfd, self.wfd = socket.socketpair() # send a notification self.wfd.send(b'\0') def execute(self, query): pass def fetchall(self): return "fake data" def isready(self): return True def fileno(self): return self.rfd.fileno() def __del__(self): self.wfd.close() self.rfd.close() class FakeConnection(object): notifies = [(0, 'fake notification')] def cursor(self): return FakeCursor(connection=self) 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.assertEqual( [('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-5.1/useradm/000077500000000000000000000000001460361267500152055ustar00rootroot00000000000000pglistener-5.1/useradm/bin/000077500000000000000000000000001460361267500157555ustar00rootroot00000000000000pglistener-5.1/useradm/bin/pua000077500000000000000000000221101460361267500164640ustar00rootroot00000000000000#! /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 STDIN, ":utf8"; 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 { utf8::decode($value); $user->update({$field => $value}); }; if ($@) { print $OUT $@; } } sub user_print_field { my ($OUT, $user, $field) = (@_); eval { my $val = $user->$field() // ''; utf8::encode($val); printf ($OUT "%-20s: %s\n", $field, $val); }; 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-5.1/useradm/etc/000077500000000000000000000000001460361267500157605ustar00rootroot00000000000000pglistener-5.1/useradm/etc/pglistener/000077500000000000000000000000001460361267500201345ustar00rootroot00000000000000pglistener-5.1/useradm/etc/pglistener/pglistener.cfg000066400000000000000000000006051460361267500227720ustar00rootroot00000000000000[DEFAULT] DSN = host=db_host dbname=db_name user=db_user password=db_password sslmode=verify-ca sslrootcert=/etc/ssl/certs/ca-certificates.crt [email_recipient_canonical] class = PgListener notifications = update query = select username from email_outgoing format = %s\n destination = /var/lib/pglistener/recipient_canonical posthooks = sudo /var/lib/pglistener/hooks/build-recipient-map pglistener-5.1/useradm/etc/pua.conf000066400000000000000000000001001460361267500174030ustar00rootroot00000000000000DBHOST=localhost DBNAME=accounts DBUSER=useradmin DBPASS=secret pglistener-5.1/useradm/lib/000077500000000000000000000000001460361267500157535ustar00rootroot00000000000000pglistener-5.1/useradm/lib/Pglistener/000077500000000000000000000000001460361267500200675ustar00rootroot00000000000000pglistener-5.1/useradm/lib/Pglistener/Schema.pm000066400000000000000000000001431460361267500216230ustar00rootroot00000000000000package Pglistener::Schema; use base qw/DBIx::Class::Schema/; __PACKAGE__->load_namespaces(); 1; pglistener-5.1/useradm/lib/Pglistener/Schema/000077500000000000000000000000001460361267500212675ustar00rootroot00000000000000pglistener-5.1/useradm/lib/Pglistener/Schema/Result/000077500000000000000000000000001460361267500225455ustar00rootroot00000000000000pglistener-5.1/useradm/lib/Pglistener/Schema/Result/Account.pm000066400000000000000000000010621460361267500244760ustar00rootroot00000000000000package 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-5.1/useradm/lib/Pglistener/Schema/Result/AccountGrp.pm000066400000000000000000000006111460361267500251460ustar00rootroot00000000000000package 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-5.1/useradm/lib/Pglistener/Schema/Result/Email.pm000066400000000000000000000005051460361267500241320ustar00rootroot00000000000000package 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-5.1/useradm/lib/Pglistener/Schema/Result/Group.pm000066400000000000000000000005301460361267500241750ustar00rootroot00000000000000package 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-5.1/useradm/lib/Pglistener/Schema/Result/SSHKey.pm000066400000000000000000000005101460361267500242050ustar00rootroot00000000000000package 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;