tmpcma5cyg4/0000700000232200023220000000000014516675355013570 5ustar debalancedebalancetmpcma5cyg4/mod_http_redirect/0000755000232200023220000000000014516675355017301 5ustar debalancedebalancetmpcma5cyg4/mod_http_redirect/README.md0000644000232200023220000000166414516675355020567 0ustar debalancedebalancemod_http_redirect - Redirect HTTP path to another URI ============================================================ * Author: Badlop Description ----------- This simple module redirects the web browser to the configured URI. Configuration ------------- The configurable option is: - `location` (default: `[]`) The URI where requests will be redirected. This module should be added not only to the `modules` section, also to `request_handlers` inside the `listen` option. It is very important to set this request handler as the last one, otherwise it could produce infinite redirects. ```yaml listen: - port: 5280 module: ejabberd_http request_handlers: /admin: ejabberd_admin /register: mod_register_web /: mod_http_redirect modules: mod_http_redirect: location: http://example.com ``` With that configuration, a request for `http://localhost:5280/` will be redirected to `http://example.com` tmpcma5cyg4/mod_http_redirect/mod_http_redirect.spec0000644000232200023220000000034514516675355023656 0ustar debalancedebalanceauthor: "Badlop " category: "HTTP" summary: "Redirect HTTP path to another URI" home: "https://github.com/processone/ejabberd-contrib/tree/master/" url: "git@github.com:processone/ejabberd-contrib.git" tmpcma5cyg4/mod_http_redirect/conf/0000755000232200023220000000000014516675355020226 5ustar debalancedebalancetmpcma5cyg4/mod_http_redirect/conf/mod_http_redirect.yml0000644000232200023220000000027414516675355024453 0ustar debalancedebalance#listen: # - # port: 5286 # module: ejabberd_http # request_handlers: # /: mod_http_redirect # #modules: # mod_http_redirect: # location: http://example.com/some-path/ tmpcma5cyg4/mod_http_redirect/src/0000755000232200023220000000000014516675355020070 5ustar debalancedebalancetmpcma5cyg4/mod_http_redirect/src/mod_http_redirect.erl0000644000232200023220000000501014516675355024267 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% File : mod_http_redirect.erl %%% Author : Badlop %%% Purpose : Redirect HTTP path to another URI %%% Created : 15 May 2023 by Badlop %%% %%% %%% ejabberd, Copyright (C) 2002-2023 ProcessOne %%% %%% 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. %%% %%%---------------------------------------------------------------------- -module(mod_http_redirect). -author('badlop@process-one.net'). -behaviour(gen_mod). -export([start/2, stop/1, reload/3, process/2]). -export([mod_opt_type/1, mod_options/1, mod_doc/0, mod_status/0, depends/2]). -include("logger.hrl"). -include_lib("xmpp/include/xmpp.hrl"). -include("ejabberd_http.hrl"). -include("translate.hrl"). %%%---------------------------------------------------------------------- %%% gen_mod callbacks %%%---------------------------------------------------------------------- start(_Host, _Opts) -> ok. stop(_Host) -> ok. reload(_Host, _NewOpts, _OldOpts) -> ok. depends(_Host, _Opts) -> []. %%%---------------------------------------------------------------------- %%% HTTP handlers %%%---------------------------------------------------------------------- process(_Path, #request{host = Host}) -> try gen_mod:get_module_opt(Host, ?MODULE, location) of Location when is_binary(Location) -> {301, [{<<"Location">>, Location}], <<>>} catch error:{module_not_loaded, ?MODULE, Host} -> {404, [], <<"Not Found">>} end. %%%---------------------------------------------------------------------- %%% Options and documentation %%%---------------------------------------------------------------------- mod_opt_type(location) -> econf:binary(). mod_options(_) -> [{location, <<"">>}]. mod_doc() -> #{}. mod_status() -> "". tmpcma5cyg4/mod_http_redirect/COPYING0000644000232200023220000004346414516675355020347 0ustar debalancedebalanceAs a special exception, the authors give permission to link this program with the OpenSSL library and distribute the resulting binary. 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. tmpcma5cyg4/mod_ecaptcha/0000755000232200023220000000000014516675355016211 5ustar debalancedebalancetmpcma5cyg4/mod_ecaptcha/README.md0000644000232200023220000000735614516675355017503 0ustar debalancedebalancemod_ecaptcha - Generate CAPTCHAs using ecaptcha =============================================== Requires: - ejabberd 23.01 or higher - C compiler and makefile - write access to ejabberd's priv dir This small module uses the [ecaptcha](https://github.com/seriyps/ecaptcha) erlang library to generate CAPTCHA images suitable for ejabberd's [CAPTCHA](https://docs.ejabberd.im/admin/configuration/basic/#captcha) feature. Installing this module in a containerized ejabberd requires some additional steps, please read below. Basic Configuration ------------------- The minimal configuration required to get this module working is: ```yaml captcha_cmd: mod_ecaptcha captcha_url: http://localhost:5280/captcha listen: - port: 5280 module: ejabberd_http request_handlers: /captcha: ejabberd_captcha modules: mod_ecaptcha: {} ``` Options ------- The configurable options match mostly the ones from ecaptcha library: - `numchars` Number of characters to include in the CAPTCHA image. Default: `5` - `effects` List of effects to use to generate the CAPTCHA image. Check [ecaptcha usage](https://github.com/seriyps/ecaptcha#usage) for details. Default: `[line, blur, filter, dots, reverse_dots]` - `color` This option defines the image's color. Valid values: `black`, `red`, `orange`, `blue`, `pink` or `purple`. Default: `black` - `alphabet` String containing all the characters that can be printed on the image (duplicates are ok). The default value includes: numbers, latin characters lower and upper case. - `font` String of one of the supported fonts. Please notice that fonts are pre-rendered at NIF compile-time, see the `deps/ecaptcha/c_src/fonts.h` and `FONTS` parameter in `deps/ecaptcha/c_src/Makefile`. Default: `hplhs-oldstyle` Example Configuration --------------------- This example configuration setups CAPTCHA images that are simple to solve: just 3 characters, only the vocals in lower and upper case. It also setups `mod_register_web`, you can test the feature immediately visiting `http://localhost:5280/register/` ```yaml captcha_cmd: mod_ecaptcha captcha_url: http://localhost:5280/captcha listen: - port: 5280 module: ejabberd_http request_handlers: /captcha: ejabberd_captcha /register: mod_register_web modules: mod_ecaptcha: numchars: 3 effects: [line, dots] color: red alphabet: "aeiouAEIOU" font: "hplhs-oldstyle" ``` Install in Container -------------------- There are some additional steps to install this module in a containerized ejabberd. For example, if using the container image available at GitHub Container Registry: ``` docker run --name ejabberd -it -p 5222:5222 -p 5280:5280 -p 5288:5288 ghcr.io/processone/ejabberd:23.01 live ``` Install the dependencies required to compile C code: ``` docker exec --user root ejabberd apk add git make g++ freetype-dev erlang-dev ``` It's a good idea to update specs and modules source code: ``` docker exec ejabberd ejabberdctl modules_update_specs ``` Install the module so it gets the Erlang dependencies, then compile that dependency C code, and finally recompile it: ``` docker exec ejabberd ejabberdctl module_install mod_ecaptcha docker exec ejabberd make -C .ejabberd-modules/sources/ejabberd-contrib/mod_ecaptcha/deps/ecaptcha/c_src docker exec ejabberd ejabberdctl module_upgrade mod_ecaptcha ``` If using the Docker Hub Container, `ejabberdctl` is in a different path, please use those commands instead: ``` docker exec ejabberd bin/ejabberdctl modules_update_specs docker exec ejabberd bin/ejabberdctl module_install mod_ecaptcha docker exec ejabberd make -C .ejabberd-modules/sources/ejabberd-contrib/mod_ecaptcha/deps/ecaptcha/c_src docker exec ejabberd bin/ejabberdctl module_upgrade mod_ecaptcha ``` tmpcma5cyg4/mod_ecaptcha/rebar.config0000644000232200023220000000015714516675355020476 0ustar debalancedebalance{deps, [ {ecaptcha, ".*", {git, "https://github.com/seriyps/ecaptcha", {branch, "master"}}} ]}. tmpcma5cyg4/mod_ecaptcha/mod_ecaptcha.spec0000644000232200023220000000034714516675355021500 0ustar debalancedebalanceauthor: "Badlop " category: "captcha" summary: "Generate CAPTCHAs using ecaptcha" home: "https://github.com/processone/ejabberd-contrib/tree/master/" url: "git@github.com:processone/ejabberd-contrib.git" tmpcma5cyg4/mod_ecaptcha/conf/0000755000232200023220000000000014516675355017136 5ustar debalancedebalancetmpcma5cyg4/mod_ecaptcha/conf/mod_ecaptcha.yml0000644000232200023220000000032114516675355022264 0ustar debalancedebalancecaptcha_cmd: mod_ecaptcha captcha_url: http://localhost:5288/captcha/ listen: - port: 5288 module: ejabberd_http request_handlers: /captcha: ejabberd_captcha modules: mod_ecaptcha: {} tmpcma5cyg4/mod_ecaptcha/src/0000755000232200023220000000000014516675355017000 5ustar debalancedebalancetmpcma5cyg4/mod_ecaptcha/src/mod_ecaptcha.erl0000644000232200023220000000521314516675355022114 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : mod_ecaptcha.erl %%% Author : Badlop %%% Purpose : Generate CAPTCHAs using ecaptcha %%% Created : %%% %%% %%% ejabberd, Copyright (C) 2002-2022 ProcessOne %%% %%% 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. %%% %%%---------------------------------------------------------------------- -module(mod_ecaptcha). -author('badlop@process-one.net'). -behaviour(gen_mod). -export([start/2, stop/1, depends/2, mod_options/1, mod_opt_type/1, mod_doc/0]). -export([create_image/1]). %% --------------------- %% gen_mod %% --------------------- start(_Host, _Opts) -> ok. stop(_Host) -> ok. depends(_Host, _Opts) -> []. mod_opt_type(numchars) -> econf:int(1, 7); mod_opt_type(effects) -> econf:list(econf:enum([line, blur, filter, dots, reverse_dots])); mod_opt_type(color) -> econf:atom(); mod_opt_type(alphabet) -> econf:binary(); mod_opt_type(font) -> econf:binary(). mod_options(_Host) -> [{numchars, 5}, {effects, [line, blur, filter, dots, reverse_dots]}, {color, black}, {alphabet, <<"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ">>}, {font, <<"hplhs-oldstyle">>} ]. mod_doc() -> #{}. %% --------------------- %% CAPTCHA generation %% --------------------- create_image(_Key) -> Response = ecaptcha:png( get_opt(numchars), #{effects => get_opt(effects), color => get_opt(color), alphabet => get_opt(alphabet), font => get_opt(font)} ), case Response of {Phrase, PNGImage} when is_binary(Phrase) -> PNGBin = binary:list_to_bin([PNGImage]), {ok, <<"image/png">>, Phrase, PNGBin}; {error, Reason} -> {error, Reason} end. get_opt(OptionName) -> Host = hd(ejabberd_option:hosts()), gen_mod:get_module_opt(Host, ?MODULE, OptionName). tmpcma5cyg4/mod_ecaptcha/COPYING0000644000232200023220000004346414516675355017257 0ustar debalancedebalanceAs a special exception, the authors give permission to link this program with the OpenSSL library and distribute the resulting binary. 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. tmpcma5cyg4/README.md0000644000232200023220000000570614516675355015071 0ustar debalancedebalanceejabberd-contrib ================ This is a collaborative development area for ejabberd module developers and users. Those modules are not officially supported by ProcessOne. For users --------- To use an ejabberd module coming from this repository: - You need to have ejabberd installed. - If you have not already done it, run `ejabberdctl modules_update_specs` to retrieve the list of available modules. - Run `ejabberdctl module_install ` to get the source code and to compile and install the `beam` file into ejabberd's module search path. This path is either `~/.ejabberd-modules` or defined by the `CONTRIB_MODULES_PATH` setting in `ejabberdctl.cfg`. - Edit the configuration file provided in the `conf` directory of the installed module and update it to your needs. Or, if you prefer so, configure it in your main ejabberd configuration file. - Run `ejabberdctl module_uninstall ` to remove a module from ejabberd. For developers -------------- The following organization has been set up for the development: - Development and compilation of modules is done by ejabberd. You need ejabberd installed. Use `ejabberdctl module_check ` to ensure it compiles correctly before committing your work. The sources of your module must be located in `$CONTRIB_MODULES_PATH/sources/`. - Compilation can by done manually (if you know what you are doing) so you don't need ejabberd running: ``` cd /path/of/module mkdir ebin /path/of/ejabberd's/erlc \ -o ebin \ -I include -I /path/of/ejabberd/lib/ejabberd-XX.YY/include \ -DLAGER -DNO_EXT_LIB \ src/*erl ``` - The module directory structure is usually the following: * `README.txt`: Module description. * `COPYING`: License for the module. * `doc/`: Documentation directory. * `src/`: Erlang source directory. * `lib/`: Elixir source directory. * `priv/msgs/`: Directory with translation files (pot, po and msg). * `conf/.yml`: Configuration for your module. * `.spec`: Yaml description file for your module. - Module developers should note in the `README.txt` file whether the module has requirements or known incompatibilities with other modules. - If your module project contains several erlang modules, you should export a function pre_uninstall/0 in the main one listing the other ones. See mod_statsdx as an example. Broken modules -------------- This is the list of modules that are known to be broken with latest ejabberd master branch. If you feel they are worth it, your help to fix them is welcome: - atom_pubsub: "Provides access to all PEP nodes via an AtomPub interface." - ircd: "This is an IRC server frontend to ejabberd." - mod_archive: "Message Archiving (XEP-0136)." - mod_irc: "IRC transport." - mod_mam_mnesia: This feature got included in ejabberd 15.06 - mod_openid: "Transform the Jabber Server in an openid provider." - mod_profile: "User Profile (XEP-0154) in Mnesia table." tmpcma5cyg4/ejabberd_observer_cli/0000755000232200023220000000000014516675355020076 5ustar debalancedebalancetmpcma5cyg4/ejabberd_observer_cli/README.md0000644000232200023220000000222414516675355021355 0ustar debalancedebalanceejabberd observer_cli plugins ============================= [observer_cli][oc] is an erlang tool to visualize Erlang node statistics on the command line. This directory contains several plugins specifically written to view statistics of [ejabberd][ej]. To install this, just run: ```bash ejabberdctl module_install ejabberd_observer_cli ``` It will automatically download, compile and install the required dependencies: [observer_cli][oc], [recon][recon], and the additional plugin [os_stats][os]. Then, start an erlang shell attached to your ejabberd node, for example: ```bash ejabberdctl debug ``` in that erlang shell execute: ```erlang ejabberd_observer_cli:start(). ``` If using Elixir (for example when started with `ejabberdctl iexdebug`, run: ```elixir :ejabberd_observer_cli.start() ``` To sort columns or change between the different pages, type the corresponding letter and hit Enter. For example, to view MUC statistics, type: `M and then Enter`. There is no configuration required. [oc]: https://github.com/zhongwencool/observer_cli [os]: https://github.com/zhongwencool/os_stats [recon]: https://github.com/ferd/recon [ej]: https://www.ejabberd.im/ tmpcma5cyg4/ejabberd_observer_cli/rebar.config0000644000232200023220000000036414516675355022363 0ustar debalancedebalance{deps, [ {observer_cli, ".*", {git, "https://github.com/zhongwencool/observer_cli"}}, {os_stats, ".*", {git, "https://github.com/zhongwencool/os_stats"}}, {recon, ".*", {git, "https://github.com/ferd/recon"}} ]}. tmpcma5cyg4/ejabberd_observer_cli/src/0000755000232200023220000000000014516675355020665 5ustar debalancedebalancetmpcma5cyg4/ejabberd_observer_cli/src/ejabberd_observer_cli_userstophost.erl0000644000232200023220000000347114516675355030534 0ustar debalancedebalance-module(ejabberd_observer_cli_userstophost). %% observer_cli_plugin Callback API -export([attributes/1, sheet_header/0, sheet_body/1]). get_top_host() -> lists:foldl( fun(Host, {HostRelativeMax, CountRelativeMax}) -> case ejabberd_auth:count_users(Host) of Count when Count > CountRelativeMax -> {Host, Count}; _ -> {HostRelativeMax, CountRelativeMax} end end, {unknown, -1}, ejabberd_option:hosts() ). attributes(PrevState) -> {Host, _} = get_top_host(), RegisteredUsers = ejabberd_auth:count_users(Host), Sessions = length(ejabberd_sm:dirty_get_sessions_list()), SessionsThisNode = length(ejabberd_sm:dirty_get_my_sessions_list()), Attrs = [ [ #{content => "Virtual Host", width => 12}, #{content => Host, width => 14}, #{content => "Sessions Total", width => 18}, #{content => Sessions, width => 8} ], [ #{content => "Accounts Total", width => 12}, #{content => RegisteredUsers, width => 14}, #{content => "Sessions This Node", width => 18}, #{content => SessionsThisNode, width => 8} ] ], NewState = PrevState, {Attrs, NewState}. sheet_header() -> [ #{title => "Username", width => 25, shortcut => "u"}, #{title => "Resources", width => 15, shortcut => "r"} ]. sheet_body(PrevState) -> {Host, _} = get_top_host(), Body = [ begin [ Username, length(ejabberd_sm:get_user_resources(Username, Host)) ] end || {Username, _} <- lists:reverse(lists:sort(ejabberd_auth:get_users(Host))) ], NewState = PrevState, {Body, NewState}. tmpcma5cyg4/ejabberd_observer_cli/src/ejabberd_observer_cli_users.erl0000644000232200023220000000610314516675355027106 0ustar debalancedebalance-module(ejabberd_observer_cli_users). %% observer_cli_plugin Callback API -export([attributes/1, sheet_header/0, sheet_body/1]). attributes(PrevState) -> Hosts = length(ejabberd_option:hosts()), RegisteredUsers = lists:foldl( fun(Host, Sum) -> ejabberd_auth:count_users(Host) + Sum end, 0, ejabberd_option:hosts() ), Sessions = length(ejabberd_sm:dirty_get_sessions_list()), SessionsThisNode = length(ejabberd_sm:dirty_get_my_sessions_list()), Attrs = [ [ #{content => "Virtual Hosts", width => 18}, #{content => Hosts, width => 8}, #{content => "Sessions Total", width => 18}, #{content => Sessions, width => 8} ], [ #{content => "Accounts Total", width => 18}, #{content => RegisteredUsers, width => 8}, #{content => "Sessions This Node", width => 18}, #{content => SessionsThisNode, width => 8} ] ], NewState = PrevState, {Attrs, NewState}. sheet_header() -> [ #{title => "Username", width => 25, shortcut => "u"}, #{title => "Host", width => 25, shortcut => "h"}, #{title => "Sessions", width => 11, shortcut => "s"}, #{title => "Roster", width => 9, shortcut => "r"}, #{title => "Offline", width => 10, shortcut => "o"}, #{title => "Last Activity", width => 20, shortcut => "l"} ]. sheet_body(PrevState) -> Body = [ begin [ Username, Host, length(ejabberd_sm:get_user_resources(Username, Host)), length(mod_roster:get_roster(Username, Host)), mod_offline:count_offline_messages(Username, Host), get_last_activity(Username, Host) ] end || {Username, Host} <- lists:sort(ejabberd_auth:get_users()) ], NewState = PrevState, {Body, NewState}. %% Code copied from ejabberd_web_admin.erl get_last_activity(User, Server) -> case ejabberd_sm:get_user_resources(User, Server) of [] -> case get_last_info(User, Server) of not_found -> "Never"; {ok, Shift, _Status} -> TimeStamp = {Shift div 1000000, Shift rem 1000000, 0}, {{Year, Month, Day}, {Hour, Minute, Second}} = calendar:now_to_local_time(TimeStamp), (io_lib:format( "~w-~.2.0w-~.2.0w ~.2.0w:~.2.0w:~.2.0w", [ Year, Month, Day, Hour, Minute, Second ] )) end; _ -> "Online" end. get_last_info(User, Server) -> case gen_mod:is_loaded(Server, mod_last) of true -> mod_last:get_last_info(User, Server); false -> not_found end. tmpcma5cyg4/ejabberd_observer_cli/src/ejabberd_observer_cli.erl0000644000232200023220000000231514516675355025666 0ustar debalancedebalance-module(ejabberd_observer_cli). -export([start/0, stop/1, mod_status/0]). start() -> application:set_env(observer_cli, plugins, plugins(), [{persistent, true}]), observer_cli:start_plugin(). stop(_Host) -> ok. mod_status() -> "In an erlang shell run: ejabberd_observer_cli:start().". plugins() -> [ #{ module => ejabberd_observer_cli_vhosts, title => "VHosts", interval => 1600, shortcut => "V", sort_column => 2 }, #{ module => ejabberd_observer_cli_users, title => "Users", interval => 1600, shortcut => "U", sort_column => 2 }, %% #{module => ejabberd_observer_cli_userstophost, title => "Users Top Vhost", %% interval => 1600, shortcut => "T", sort_column => 2}, #{ module => ejabberd_observer_cli_muc, title => "MUC", interval => 1600, shortcut => "M", sort_column => 2 }, #{ module => os_stats_plug, title => "OS", interval => 2000, shortcut => "O", sort_column => 2 } ]. tmpcma5cyg4/ejabberd_observer_cli/src/ejabberd_observer_cli_muc.erl0000644000232200023220000000253114516675355026532 0ustar debalancedebalance-module(ejabberd_observer_cli_muc). %% observer_cli_plugin Callback API -export([attributes/1, sheet_header/0, sheet_body/1]). attributes(PrevState) -> OnlineRoomsNumber = lists:foldl( fun(Host, Acc) -> Acc + mod_muc:count_online_rooms(Host) end, 0, mod_muc_admin:find_hosts(global) ), Attrs = [ [ #{content => "MUC Rooms", width => 25}, #{content => OnlineRoomsNumber, width => 8} ] ], NewState = PrevState, {Attrs, NewState}. sheet_header() -> [ #{title => "Room Name", width => 20, shortcut => "n"}, #{title => "MUC Service", width => 30, shortcut => "s"}, #{title => "Occupants", width => 12, shortcut => "o"}, #{title => "Subscribers", width => 13, shortcut => "r"} ]. sheet_body(PrevState) -> Body = [ begin {Name, Service, _} = jid:split(jid:decode(RoomStr)), OccupantsNumber = mod_muc_admin:get_room_occupants_number(Name, Service), SubsNumber = length(mod_muc_admin:get_subscribers(Name, Service)), [ Name, Service, OccupantsNumber, SubsNumber ] end || RoomStr <- mod_muc_admin:muc_online_rooms(global) ], NewState = PrevState, {Body, NewState}. tmpcma5cyg4/ejabberd_observer_cli/src/ejabberd_observer_cli_vhosts.erl0000644000232200023220000000451614516675355027301 0ustar debalancedebalance-module(ejabberd_observer_cli_vhosts). %% observer_cli_plugin Callback API -export([attributes/1, sheet_header/0, sheet_body/1]). attributes(PrevState) -> Hosts = length(ejabberd_option:hosts()), RegisteredUsers = lists:foldl( fun(Host, Sum) -> ejabberd_auth:count_users(Host) + Sum end, 0, ejabberd_option:hosts() ), Sessions = length(ejabberd_sm:dirty_get_sessions_list()), SessionsThisNode = length(ejabberd_sm:dirty_get_my_sessions_list()), OnlineRoomsNumber = lists:foldl( fun(Host, Acc) -> Acc + mod_muc:count_online_rooms(Host) end, 0, mod_muc_admin:find_hosts(global) ), Attrs = [ [ #{content => "Virtual Hosts", width => 25}, #{content => Hosts, width => 8}, #{content => "Sessions Total", width => 25}, #{content => Sessions, width => 8} ], [ #{content => "Accounts Total", width => 25}, #{content => RegisteredUsers, width => 8}, #{content => "Sessions This Node", width => 25}, #{content => SessionsThisNode, width => 8} ], [ #{content => "MUC Rooms", width => 25}, #{content => OnlineRoomsNumber, width => 8} ] ], NewState = PrevState, {Attrs, NewState}. sheet_header() -> [ #{title => "Virtual Host", width => 38, shortcut => "v"}, #{title => "Accounts", width => 11, shortcut => "a"}, #{title => "Sessions", width => 11, shortcut => "s"}, #{title => "Rooms", width => 8, shortcut => "r"} ]. sheet_body(PrevState) -> Body = [ begin RegisteredUsers = ejabberd_auth:count_users(Host), Sessions = ejabberd_sm:get_vh_session_number(Host), OnlineRoomsNumber = lists:foldl( fun(Host1, Acc) -> Acc + mod_muc:count_online_rooms(Host1) end, 0, mod_muc_admin:find_hosts(Host) ), [ Host, RegisteredUsers, Sessions, OnlineRoomsNumber ] end || Host <- lists:reverse(lists:sort(ejabberd_option:hosts())) ], NewState = PrevState, {Body, NewState}. tmpcma5cyg4/ejabberd_observer_cli/COPYING0000644000232200023220000004346414516675355021144 0ustar debalancedebalanceAs a special exception, the authors give permission to link this program with the OpenSSL library and distribute the resulting binary. 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. tmpcma5cyg4/ejabberd_observer_cli/ejabberd_observer_cli.spec0000644000232200023220000000034614516675355025251 0ustar debalancedebalanceauthor: "Badlop " category: "stats" summary: "Observer CLI plugins for ejabberd" home: "https://github.com/processone/ejabberd-contrib/tree/master/" url: "git@github.com:processone/ejabberd-contrib.git" tmpcma5cyg4/mod_s2s_log/0000755000232200023220000000000014516675355016011 5ustar debalancedebalancetmpcma5cyg4/mod_s2s_log/README.md0000644000232200023220000000044014516675355017266 0ustar debalancedebalancemod_s2s_log - Log all s2s connections in a file =============================================== This module can be used to keep track of other XMPP servers your server has been connected with. Example configuration: ```yaml modules: mod_s2s_log: filename: "/path/to/s2s.log" ``` tmpcma5cyg4/mod_s2s_log/ChangeLog0000644000232200023220000000040214516675355017557 0ustar debalancedebalance2008-03-20 Badlop * README.txt: Explained requirement of ejabberd SVN 1135 trunk or 2.0.x branch * ChangeLog: Added file to track changes 2008-03-14 Mickael Remond * mod_s2s_log: Initial commit tmpcma5cyg4/mod_s2s_log/conf/0000755000232200023220000000000014516675355016736 5ustar debalancedebalancetmpcma5cyg4/mod_s2s_log/conf/mod_s2s_log.yml0000644000232200023220000000012614516675355021667 0ustar debalancedebalancemodules: mod_s2s_log: filename: auto # filename: "/var/log/ejabberd/s2s.log" tmpcma5cyg4/mod_s2s_log/src/0000755000232200023220000000000014516675355016600 5ustar debalancedebalancetmpcma5cyg4/mod_s2s_log/src/mod_s2s_log.erl0000644000232200023220000001066714516675355021525 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : mod_s2s_log.erl %%% Author : Mickael Remond %%% Purpose : Log all s2s connections in a file %%% Created : 14 Mar 2008 by Mickael Remond %%% %%% %%% ejabberd, Copyright (C) 2002-2020 ProcessOne %%% %%% 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. %%% %%%---------------------------------------------------------------------- -module(mod_s2s_log). -author('mremond@process-one.net'). -behaviour(gen_mod). %% API: -export([start/2, init/1, stop/1, depends/2, mod_doc/0, mod_opt_type/1, mod_status/0, mod_options/1]). %% Hooks: -export([reopen_log/0, s2s_out_auth/2, s2s_in_auth/3]). -include("logger.hrl"). -define(PROCNAME, ?MODULE). -define(FILE_OPTS, [append,raw]). -record(config, {filename, iodevice}). %% For now we only support one log file for all vhosts. start(Host, Opts) -> case whereis(?PROCNAME) of undefined -> FilenameStr = case gen_mod:get_opt(filename, Opts) of auto -> filename:join(filename:dirname(ejabberd_logger:get_log_path()), "s2s.log"); FN -> FN end, Filename = iolist_to_binary(FilenameStr), register(?PROCNAME, spawn(?MODULE, init, [#config{filename=Filename}])), ejabberd_hooks:add(reopen_log_hook, ?MODULE, reopen_log, 55), s2s_hooks(Host, add); _ -> s2s_hooks(Host, add) end. init(Config)-> {ok, IOD} = file:open(Config#config.filename, ?FILE_OPTS), loop(Config#config{iodevice=IOD}). loop(Config) -> receive {s2s_connect, MyServer, Server} -> log_s2s_connection(Config#config.iodevice, MyServer, Server), loop(Config); {reopen_log} -> file:close(Config#config.iodevice), {ok, IOD} = file:open(Config#config.filename, ?FILE_OPTS), loop(Config#config{iodevice = IOD}); {get_filename, Pid} -> Pid ! {filename, Config#config.filename}, loop(Config); stop -> file:close(Config#config.iodevice), exit(normal) end. stop(Host) -> s2s_hooks(Host, delete), case gen_mod:is_loaded_elsewhere(Host, ?MODULE) of true -> ok; false -> ejabberd_hooks:delete(reopen_log_hook, ?MODULE, reopen_log, 55), ?PROCNAME ! stop end. s2s_out_auth(#{remote_server := RServer, server := LServer} = Acc, true) -> ?PROCNAME ! {s2s_connect, LServer, RServer}, Acc; s2s_out_auth(Acc, _) -> Acc. s2s_in_auth(#{lserver := LServer} = Acc, true, RServer) -> ?PROCNAME ! {s2s_connect, RServer, LServer}, Acc; s2s_in_auth(Acc, _, _) -> Acc. reopen_log() -> ?PROCNAME ! {reopen_log}. depends(_, _) -> []. mod_opt_type(filename) -> econf:either(auto, econf:file(write)). mod_options(_Host) -> [{filename, auto}]. mod_doc() -> #{}. mod_status() -> ?PROCNAME ! {get_filename, self()}, Filename = receive {filename, F} -> F end, io_lib:format("Logging to: ~s", [binary_to_list(Filename)]). %% --- %% Internal functions log_s2s_connection(IODevice, MyServer, Server) -> {{Y, M, D}, {H, Min, S}} = calendar:local_time(), Date = io_lib:format(template(date), [Y, M, D, H, Min, S]), Record = [Date, "|", MyServer, "|", Server, "\n"], ok = file:write(IODevice, Record). template(date) -> "~p-~2.2.0w-~2.2.0w ~2.2.0w:~2.2.0w:~2.2.0w". -spec s2s_hooks(binary(), add | delete) -> ok. s2s_hooks(Host, add) -> ejabberd_hooks:add(s2s_out_auth_result, Host, ?MODULE, s2s_out_auth, 55), ejabberd_hooks:add(s2s_in_auth_result, Host, ?MODULE, s2s_in_auth, 55); s2s_hooks(Host, delete) -> ejabberd_hooks:delete(s2s_out_auth_result, Host, ?MODULE, s2s_out_auth, 55), ejabberd_hooks:delete(s2s_in_auth_result, Host, ?MODULE, s2s_in_auth, 55). tmpcma5cyg4/mod_s2s_log/mod_s2s_log.spec0000644000232200023220000000035514516675355021077 0ustar debalancedebalanceauthor: "Mickael Remond " category: "log" summary: "Log all s2s connections in a file" home: "https://github.com/processone/ejabberd-contrib/tree/master/" url: "git@github.com:processone/ejabberd-contrib.git" tmpcma5cyg4/mod_s2s_log/COPYING0000644000232200023220000004332414516675355017052 0ustar debalancedebalanceAs a special exception, the authors give permission to link this program with the OpenSSL library and distribute the resulting binary. GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. tmpcma5cyg4/mod_post_log/0000755000232200023220000000000014516675355016267 5ustar debalancedebalancetmpcma5cyg4/mod_post_log/README.md0000644000232200023220000000210014516675355017537 0ustar debalancedebalancemod_post_log - Logs messages to an HTTP API =========================================== * Author: Tim Stewart, Mojo Lingo LLC * Requirements: ejabberd 14.07 or later This module implements logging of all messages sent (chat and groupchat) via an HTTP API. Configuration ------------- - `url`: URL where the HTTP POSTs are to be sent. - `ts_header`: Default value: `"X-Message-Timestamp"` - `from_header`: Default value: `"X-Message-From"` - `to_header`: Default value: `"X-Message-To"` - `headers`: Default value: `[]` - `content_type`: Default value: `"text/xml"` - `http_options`: Default value: `[]` - `req_options`: Default value: `[]` Example Configuration --------------------- ```yaml modules: mod_post_log: url: "http://foo.bar.com/messages" ``` API Example ----------- ``` POST /messages HTTP/1.0 HTTP-X-MESSAGE-FROM: doo@dah.com HTTP_X_MESSAGE_TO: foo@bar.com Content-Type: application/xml Content-Length: 122 Hello there Foo! ``` tmpcma5cyg4/mod_post_log/mod_post_log.spec0000644000232200023220000000033214516675355021626 0ustar debalancedebalanceauthor: "Tim Stewart " category: "log" summary: "Logs messages to an HTTP API" home: "https://github.com/processone/ejabberd-contrib/tree/master/" url: "git@github.com:processone/ejabberd-contrib.git" tmpcma5cyg4/mod_post_log/conf/0000755000232200023220000000000014516675355017214 5ustar debalancedebalancetmpcma5cyg4/mod_post_log/conf/mod_post_log.yml0000644000232200023220000000010314516675355022416 0ustar debalancedebalance#modules: # mod_post_log: # url: "http://foo.bar.com/messages" tmpcma5cyg4/mod_post_log/src/0000755000232200023220000000000014516675355017056 5ustar debalancedebalancetmpcma5cyg4/mod_post_log/src/mod_post_log.erl0000644000232200023220000001123314516675355022247 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : mod_post_log.erl %%% Author : Tim Stewart %%% Purpose : POST user messages to server via HTTP %%% Created : 02 Aug 2014 by Tim Stewart %%% %%% Based on mod_service_log.erl %%%---------------------------------------------------------------------- -module(mod_post_log). -author('tim@stoo.org'). -behaviour(gen_mod). -export([start/2, stop/1, depends/2, mod_opt_type/1, mod_options/1, mod_doc/0, log_user_send/1, log_user_send/4, post_result/1]). -include_lib("xmpp/include/xmpp.hrl"). start(Host, _Opts) -> ok = case inets:start() of {error, {already_started, inets}} -> ok; ok -> ok end, ejabberd_hooks:add(user_send_packet, Host, ?MODULE, log_user_send, 50), ok. stop(Host) -> ejabberd_hooks:delete(user_send_packet, Host, ?MODULE, log_user_send, 50), ok. depends(_Host, _Opts) -> []. mod_opt_type(url) -> fun binary_to_list/1; mod_opt_type(ts_header) -> fun binary_to_list/1; mod_opt_type(from_header) -> fun binary_to_list/1; mod_opt_type(to_header) -> fun binary_to_list/1; mod_opt_type(headers) -> fun(L) when is_list(L) -> L end; mod_opt_type(content_type) -> fun binary_to_list/1; mod_opt_type(http_options) -> fun(L) when is_list(L) -> L end; mod_opt_type(req_options) -> fun(L) when is_list(L) -> L end. mod_options(_Host) -> [{url, undefined}, {ts_header, "X-Message-Timestamp"}, {from_header, "X-Message-From"}, {to_header, "X-Message-To"}, {headers, []}, {content_type, "text/xml"}, {http_options, []}, {req_options, []}]. mod_doc() -> #{}. %% TODO: remove log_user_send/4 after 17.02 is released log_user_send(Packet, C2SState, From, To) -> log_user_send({xmpp:set_from_to(Packet, From, To), C2SState}), Packet. log_user_send({#message{type = T} = Packet, _C2SState} = Acc) when T == chat; T == groupchat -> ok = log_message(Packet), Acc; log_user_send(Acc) -> Acc. log_message(#message{from = From, to = To, body = Body} = Msg) -> case xmpp:get_text(Body) of <<"">> -> ok; _ -> XML = binary_to_list(fxml:element_to_binary(xmpp:encode(Msg))), post_xml(From, To, XML) end. post_xml(#jid{lserver = LServer} = From, To, Xml) -> Ts = to_iso_8601_date(os:timestamp()), Body = Xml, Url = get_opt(LServer, url), TsHeader = get_opt(LServer, ts_header), FromHeader = get_opt(LServer, from_header), ToHeader = get_opt(LServer, to_header), Headers = [ {TsHeader, Ts}, {FromHeader, format_jid(From)}, {ToHeader, format_jid(To)} | get_opt(LServer, headers) ], ContentType = get_opt(LServer, content_type), HttpOptions = get_opt(LServer, http_options), ReqOptions = get_opt(LServer, req_options), {ok, _ReqId} = httpc:request(post, {Url, Headers, ContentType, Body}, HttpOptions, [ {sync, false}, {receiver, {?MODULE, post_result, []}} | ReqOptions ]), ok. post_result({_ReqId, {error, Reason}}) -> report_error([ {error, Reason } ]); post_result({_ReqId, Result}) -> {StatusLine, Headers, Body} = Result, {_HttpVersion, StatusCode, ReasonPhrase} = StatusLine, if StatusCode < 200; StatusCode > 299 -> ok = report_error([ {status_code, StatusCode}, {reason_phrase, ReasonPhrase}, {headers, Headers}, {body, Body} ]), ok; true -> ok end. get_opt(LServer, Opt) -> gen_mod:get_module_opt(LServer, ?MODULE, Opt). report_error(ReportArgs) -> ok = error_logger:error_report([ mod_post_log_cannot_post | ReportArgs ]). format_jid(JID) -> binary_to_list(jid:encode(JID)). %% Erlang now()-style timestamps are in UTC by definition, and we are %% assuming ISO 8601 dates should be printed in UTC as well, so no %% conversion necessary %% %% Example: %% {1385,388790,334905} %% -becomes- %% 2013-11-25 14:13:10.334905Z -spec to_iso_8601_date(erlang:timestamp()) -> string(). to_iso_8601_date(Timestamp) when is_tuple(Timestamp) -> {{Y, Mo, D}, {H, M, S}} = calendar:now_to_universal_time(Timestamp), {_, _, US} = Timestamp, lists:flatten(io_lib:format("~4.10.0B-~2.10.0B-~2.10.0B ~2.10.0B:~2.10.0B:~2.10.0B.~6.10.0BZ", [Y, Mo, D, H, M, S, US])). tmpcma5cyg4/mod_post_log/COPYING0000644000232200023220000000204214516675355017320 0ustar debalancedebalanceCopyright (C) 2014 Mojo Lingo LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. tmpcma5cyg4/mod_captcha_rust/0000755000232200023220000000000014516675355017121 5ustar debalancedebalancetmpcma5cyg4/mod_captcha_rust/README.md0000644000232200023220000000520414516675355020401 0ustar debalancedebalancemod_captcha_rust - Generate CAPTCHAs using Rust library ======================================================= Requires: - ejabberd 23.01 or higher compiled with Elixir - Erlang/OTP and Elixir to compile the `captcha_nif` Elixir library - Rust compiler (package `rustc` in some package managers) This small module generates CAPTCHA images suitable for ejabberd's [CAPTCHA](https://docs.ejabberd.im/admin/configuration/basic/#captcha) feature, thanks to the [captcha](https://github.com/feng19/captcha) Elixir library, which internally uses the [captcha](https://github.com/daniel-e/captcha) Rust library. See example CAPTCHA images in the [captcha Rust documentation](https://docs.rs/captcha/latest/captcha/). Get `captcha_nif` library ------------------------- This module depends on an Elixir library, and there are two ways to get it installed, depending on how you obtained ejabberd: ### A) ejabberd source code If you compile ejabberd from source code, go to the path with your ejabberd source code and apply this small patch: ```diff --- a/mix.exs +++ b/mix.exs @@ -99,6 +99,7 @@ defmodule Ejabberd.MixProject do defp deps do [{:base64url, "~> 1.0"}, + {:captcha, "~> 0.1", hex: :captcha_nif}, {:cache_tab, "~> 1.0"}, {:eimp, "~> 1.0"}, {:ex_doc, ">= 0.0.0", only: :dev}, ``` Then get the new dependencies, and compile as usual: ``` mix deps.get make ``` Install ejabberd as usual, restart it and now you can proceed to install `mod_captcha_rust`. ### B) ejabberd with binary installer If you installed ejabberd using some kind of binary installer, you can download, compile and install the required library manually: ``` git clone https://github.com/feng19/captcha.git cd captcha/ mix deps.get mix mix release ``` Copy all the directories from `_build/dev/rel/captcha/lib` to the path where you have ejabberd lib directories installed. Now you can restart ejabberd and proceed to install `mod_captcha_rust`. Basic Configuration ------------------- The minimal configuration required to get this module working is: ```yaml captcha_cmd: 'Elixir.ModCaptchaRust' captcha_url: http://localhost:5280/captcha listen: - port: 5280 module: ejabberd_http request_handlers: /captcha: ejabberd_captcha ``` Options ------- This module supports those configurable options: * `difficulty` Sets the CAPTCHA difficulty, it can be `easy`, `medium` or `hard`. Default value: `easy`. * `color` Sets the CAPTCHA color, as a list of RGB integers from 0 to 255. Default value: `[0, 0, 0]`. Example of module configuration: ```yaml modules: 'Elixir.ModCaptchaRust': difficulty: hard color: [255, 0, 0] ``` tmpcma5cyg4/mod_captcha_rust/mod_captcha_rust.spec0000644000232200023220000000035314516675355023315 0ustar debalancedebalanceauthor: "Badlop " category: "captcha" summary: "Generate CAPTCHAs using Rust library" home: "https://github.com/processone/ejabberd-contrib/tree/master/" url: "git@github.com:processone/ejabberd-contrib.git" tmpcma5cyg4/mod_captcha_rust/conf/0000755000232200023220000000000014516675355020046 5ustar debalancedebalancetmpcma5cyg4/mod_captcha_rust/conf/mod_captcha_rust.yml0000644000232200023220000000034714516675355024114 0ustar debalancedebalancecaptcha_cmd: 'Elixir.ModCaptchaRust' captcha_url: http://localhost:5288/captcha/ listen: - port: 5288 module: ejabberd_http request_handlers: /captcha: ejabberd_captcha modules: 'Elixir.ModCaptchaRust': {} tmpcma5cyg4/mod_captcha_rust/COPYING0000644000232200023220000004346414516675355020167 0ustar debalancedebalanceAs a special exception, the authors give permission to link this program with the OpenSSL library and distribute the resulting binary. 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. tmpcma5cyg4/mod_captcha_rust/lib/0000755000232200023220000000000014516675355017667 5ustar debalancedebalancetmpcma5cyg4/mod_captcha_rust/lib/mod_captcha_rust.ex0000644000232200023220000000255214516675355023550 0ustar debalancedebalancedefmodule ModCaptchaRust do use Ejabberd.Module require Record ##==================================================================== ## gen_mod callbacks ##==================================================================== def start(_host, _opts) do :ok end def stop(_host) do :ok end def depends(_host, _opts) do [] end def mod_opt_type(:color) do :econf.list(:econf.int(0, 255)) end def mod_opt_type(:difficulty) do :econf.enum([:easy, :medium, :hard]) end def mod_options(_host) do [ {:color, [0, 0, 0]}, {:difficulty, :easy}, ] end def mod_doc() do %{:desc => 'This is just a demonstration.'} end ##==================================================================== ## Captcha Rust ##==================================================================== def create_image(_key) do [r, g, b] = get_opt(:color) color = %{r: r, g: g, b: b} {captcha_text, captcha_image} = case get_opt(:difficulty) do :easy -> Captcha.easy(set_color: color) :medium -> Captcha.medium(set_color: color) :hard -> Captcha.hard(set_color: color) end {:ok, "image/png", captcha_text, captcha_image} end def get_opt(option_name) do host = List.first(:ejabberd_option.hosts()) :gen_mod.get_module_opt(host, Elixir.ModCaptchaRust, option_name) end end tmpcma5cyg4/mod_default_contacts/0000755000232200023220000000000014516675355017763 5ustar debalancedebalancetmpcma5cyg4/mod_default_contacts/README.md0000644000232200023220000000206714516675355021247 0ustar debalancedebalancemod_default_contacts - Add roster contact(s) on registration ============================================================ * Author: Holger Weiss Description ----------- This module allows for specifying one or more contacts that should be added to the user's roster automatically on successful registration (via `mod_register`, or, for example, `ejabberdctl register`). Note that no presence subscription is performed, and the rosters of the contacts aren't modified. Configuration ------------- In order to use this module, add a configuration snippet such as the following: ```yaml modules: mod_default_contacts: contacts: - name: "Bob Virding" jid: bob@example.com - name: "Alice Armstrong" jid: alice@example.com ``` The configurable `mod_default_contacts` options are: - `contacts` (default: `[]`) The list of contact JIDs that should be auto-added to the user's roster on account registration. Each list item must specify the `jid:` and optionally the `name:` of the contact. tmpcma5cyg4/mod_default_contacts/mod_default_contacts.spec0000644000232200023220000000036714516675355025026 0ustar debalancedebalanceauthor: "Holger Weiss " category: "roster" summary: "Auto-add roster contacts on registration" home: "https://github.com/processone/ejabberd-contrib/tree/master/" url: "git@github.com:processone/ejabberd-contrib.git" tmpcma5cyg4/mod_default_contacts/conf/0000755000232200023220000000000014516675355020710 5ustar debalancedebalancetmpcma5cyg4/mod_default_contacts/conf/mod_default_contacts.yml0000644000232200023220000000006514516675355025615 0ustar debalancedebalance#modules: # mod_default_contacts: # contacts: [] tmpcma5cyg4/mod_default_contacts/src/0000755000232200023220000000000014516675355020552 5ustar debalancedebalancetmpcma5cyg4/mod_default_contacts/src/mod_default_contacts.erl0000644000232200023220000000610514516675355025441 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : mod_default_contacts.erl %%% Author : Holger Weiss %%% Purpose : Auto-add contacts on registration %%% Created : 14 May 2019 by Holger Weiss %%% %%% %%% ejabberd, Copyright (C) 2019-2020 ProcessOne %%% %%% 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. %%% %%%---------------------------------------------------------------------- -module(mod_default_contacts). -author('holger@zedat.fu-berlin.de'). -behavior(gen_mod). %% gen_mod callbacks. -export([start/2, stop/1, reload/3, mod_opt_type/1, depends/2, mod_options/1, mod_doc/0]). %% ejabberd_hooks callbacks. -export([register_user/2]). -include("logger.hrl"). -include_lib("xmpp/include/xmpp.hrl"). %%-------------------------------------------------------------------- %% gen_mod callbacks. %%-------------------------------------------------------------------- -spec start(binary(), gen_mod:opts()) -> ok. start(Host, _Opts) -> ejabberd_hooks:add(register_user, Host, ?MODULE, register_user, 50). -spec stop(binary()) -> ok. stop(Host) -> ejabberd_hooks:delete(register_user, Host, ?MODULE, register_user, 50). -spec reload(binary(), gen_mod:opts(), gen_mod:opts()) -> ok. reload(_Host, _NewOpts, _OldOpts) -> ok. -spec mod_opt_type(atom()) -> econf:validator(). mod_opt_type(contacts) -> econf:list( econf:and_then( econf:options( #{jid => econf:jid(), name => econf:binary()}, [{required, [jid]}]), fun(Opts) -> Jid = proplists:get_value(jid, Opts), Name = proplists:get_value(name, Opts, <<>>), #roster_item{jid = Jid, name = Name} end)). -spec mod_options(binary()) -> [{atom(), any()}]. mod_options(_Host) -> [{contacts, []}]. -spec depends(binary(), gen_mod:opts()) -> [{module(), hard | soft}]. depends(_Host, _Opts) -> [{mod_roster, hard}]. mod_doc() -> #{}. %%-------------------------------------------------------------------- %% ejabberd_hooks callbacks. %%-------------------------------------------------------------------- -spec register_user(binary(), binary()) -> any(). register_user(LUser, LServer) -> ?DEBUG("Auto-creating roster entries for ~s@~s", [LUser, LServer]), Items = gen_mod:get_module_opt(LServer, ?MODULE, contacts), mod_roster:set_items(LUser, LServer, #roster_query{items = Items}). tmpcma5cyg4/mod_default_contacts/COPYING0000644000232200023220000004346414516675355021031 0ustar debalancedebalanceAs a special exception, the authors give permission to link this program with the OpenSSL library and distribute the resulting binary. 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. tmpcma5cyg4/mod_logsession/0000755000232200023220000000000014516675355016626 5ustar debalancedebalancetmpcma5cyg4/mod_logsession/README.md0000644000232200023220000000365114516675355020112 0ustar debalancedebalancemod_logsession - Log session connections to file ================================================ * Requirements: ejabberd 19.08 or higher * Homepage: http://www.ejabberd.im/mod_logsession * Author: Badlop Description ----------- This module is intended to log in a text file the session connections. Right now it only logs the forbidden connection attempts and the failed authentication attempts. Each vhost is logged in a different file. Note: to log the failed authentication attempts, you need to patch ejabberd. Configuration ------------- - `sessionlog` Define the name of log files, or set to `auto`. The keyword `@HOST@` is substituted with the name of the vhost. If set to `auto`, it will store in the ejabberd log path with the filename `"session_@HOST@.log"` Default value: `auto` Example Configuration --------------------- ```yaml modules: ... mod_logsession: sessionlog: "/var/log/ejabberd/session_@HOST@.log" ... ``` With that configuration, if the server has three vhosts: "localhost", "example.org" and "example.net", then the forbidden accesses will be logged in the files: ``` /var/log/ejabberd/session_localhost.log /var/log/ejabberd/session_example.org.log /var/log/ejabberd/session_example.net.log ``` Log Format ---------- The content of the file is the date and time of the attempted login and the JID of the denied user. For example: ``` 2008-01-08 12:20:50 Forbidden session for tron@localhost/teeest 2008-01-08 12:36:01 Forbidden session for baduser@localhost/aaa22 2010-04-02 17:21:37 Failed authentication for someuser@localhost from 127.0.0.1 port 58973 2010-04-02 17:25:20 Failed authentication for badlop@localhost from 127.0.0.1 port 45842 ``` Reopen Log Files ---------------- This module provides an ejabberd command to reopen the log file of a host where the module is enabled. Example usage: ``` ejabberdctl reopen-seslog localhost ejabberdctl reopen-seslog jabber.example.org ``` tmpcma5cyg4/mod_logsession/mod_logsession.spec0000644000232200023220000000034214516675355022525 0ustar debalancedebalanceauthor: "Badlop " category: "log" summary: "Log session connections to file" home: "https://github.com/processone/ejabberd-contrib/tree/master/" url: "git@github.com:processone/ejabberd-contrib.git" tmpcma5cyg4/mod_logsession/ChangeLog0000644000232200023220000000050214516675355020375 0ustar debalancedebalance2008-12-12 Badlop * src/mod_logsession.erl: Replace the ejabberdctl command with an ejabberd command; requires ejabberd trunk SVN * README.txt: Documented the change and the requirement 2008-04-25 Badlop * mod_logsession: New module to log session connections tmpcma5cyg4/mod_logsession/conf/0000755000232200023220000000000014516675355017553 5ustar debalancedebalancetmpcma5cyg4/mod_logsession/conf/mod_logsession.yml0000644000232200023220000000015014516675355023316 0ustar debalancedebalancemodules: mod_logsession: sessionlog: auto # sessionlog: "/var/log/ejabberd/session_@HOST@.log" tmpcma5cyg4/mod_logsession/src/0000755000232200023220000000000014516675355017415 5ustar debalancedebalancetmpcma5cyg4/mod_logsession/src/mod_logsession.erl0000644000232200023220000001350214516675355023146 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : mod_logsession.erl %%% Author : Badlop %%% Purpose : Log session connections to file %%% Created : 8 Jan 2008 by Badlop %%% %%% %%% ejabberd, Copyright (C) 2008-2020 ProcessOne %%% %%% 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. %%% %%%---------------------------------------------------------------------- -module(mod_logsession). -author('badlop@process-one.net'). -behaviour(gen_mod). -export([start/2, stop/1, depends/2, mod_options/1, mod_opt_type/1, mod_doc/0, mod_status/0]). -export([loop/3, reopen_log/0, failed_auth/3, forbidden/1]). -include_lib("xmpp/include/xmpp.hrl"). -include("ejabberd_commands.hrl"). -define(PROCNAME, ejabberd_logsession). %%%---------------------------------------------------------------------- %%% BEHAVIOUR CALLBACKS %%%---------------------------------------------------------------------- start(Host, Opts) -> ejabberd_hooks:add(reopen_log_hook, Host, ?MODULE, reopen_log, 50), ejabberd_hooks:add(forbidden_session_hook, Host, ?MODULE, forbidden, 50), ejabberd_hooks:add(c2s_auth_result, Host, ?MODULE, failed_auth, 50), ejabberd_commands:register_commands(commands()), Filename1 = case gen_mod:get_opt(sessionlog, Opts) of auto -> filename:join(filename:dirname(ejabberd_logger:get_log_path()), "session_@HOST@.log"); SL -> SL end, Filename = replace_host(Host, Filename1), File = open_file(Filename), register(get_process_name(Host), spawn(?MODULE, loop, [Filename, File, Host])), ok. stop(Host) -> ejabberd_hooks:delete(reopen_log_hook, Host, ?MODULE, reopen_log, 50), ejabberd_hooks:delete(forbidden_session_hook, Host, ?MODULE, forbidden, 50), ejabberd_hooks:delete(c2s_auth_result, Host, ?MODULE, failed_auth, 50), ejabberd_commands:unregister_commands(commands()), Proc = get_process_name(Host), exit(whereis(Proc), stop), {wait, Proc}. depends(_Host, _Opts) -> []. mod_opt_type(sessionlog) -> econf:either(auto, econf:string()). mod_options(_Host) -> [{sessionlog, auto}]. mod_doc() -> #{}. mod_status() -> Host = ejabberd_config:get_myname(), Pid = get_process_name(Host), Pid ! {get_filename, self()}, Filename = receive {filename, F} -> F end, io_lib:format("Logging ~p to: ~s", [binary_to_list(Host), Filename]). %%%---------------------------------------------------------------------- %%% REQUEST HANDLERS %%%---------------------------------------------------------------------- reopen_log() -> lists:foreach( fun(Host) -> gen_server:cast(get_process_name(Host), reopenlog) end, ejabberd_option:hosts()). forbidden(JID) -> Host = JID#jid.lserver, get_process_name(Host) ! {log, {forbidden, JID}}. failed_auth(State, true, _) -> State; failed_auth(#{lserver := Host, ip := IPPT} = State, {false, Reason}, U) -> get_process_name(Host) ! {log, {failed_auth, U, IPPT, Reason}}, State. commands() -> [#ejabberd_commands{name = reopen_seslog, tags = [logs, server], desc = "Reopen mod_logsession log files", module = ?MODULE, function = reopen_log, args = [], result = {res, rescode}}]. %%%---------------------------------------------------------------------- %%% LOOP %%%---------------------------------------------------------------------- loop(Filename, File, Host) -> receive {log, Data} -> log(File, Host, Data), loop(Filename, File, Host); reopenlog -> File2 = reopen_file(File, Filename), loop(Filename, File2, Host); {get_filename, Pid} -> Pid ! {filename, Filename}, loop(Filename, File, Host); stop -> close_file(File) end. %%%---------------------------------------------------------------------- %%% UTILITIES %%%---------------------------------------------------------------------- get_process_name(Host) -> gen_mod:get_module_proc(Host, ?PROCNAME). replace_host(Host, Filename) -> re:replace(Filename, "@HOST@", binary_to_list(Host), [global, {return, list}]). open_file(Filename) -> {ok, File} = file:open(Filename, [append]), File. close_file(File) -> file:close(File). reopen_file(File, Filename) -> close_file(File), open_file(Filename). log(File, Host, Data) -> DateString = make_date(calendar:local_time()), MessageString = make_message(Host, Data), io:format(File, "~s ~s~n", [DateString, MessageString]). make_date(Date) -> {{Y, Mo, D}, {H, Mi, S}} = Date, %% Combined format: %%io_lib:format("[~p/~p/~p:~p:~p:~p]", [D, Mo, Y, H, Mi, S]). %% Erlang format: io_lib:format("~w-~.2.0w-~.2.0w ~.2.0w:~.2.0w:~.2.0w", [Y, Mo, D, H, Mi, S]). make_message(Host, {failed_auth, Username, {IPTuple, IPPort}, Reason}) -> IPString = inet_parse:ntoa(IPTuple), io_lib:format("Failed authentication for ~s@~s from ~s port ~p: ~s", [Username, Host, IPString, IPPort, Reason]); make_message(_Host, {forbidden, JID}) -> io_lib:format("Forbidden session for ~s", [jid:encode(JID)]). tmpcma5cyg4/mod_logsession/src/failed_auth.patch0000644000232200023220000000466014516675355022711 0ustar debalancedebalanceFrom 86a811a92b27afe43adcc3ab3692df13949c4221 Mon Sep 17 00:00:00 2001 From: Badlop Date: Mon, 23 Jun 2014 13:47:10 +0200 Subject: [PATCH] Patch for mod_logsession --- src/ejabberd_c2s.erl | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/ejabberd_c2s.erl b/src/ejabberd_c2s.erl index 9ce66d0..d59ec58 100644 --- a/src/ejabberd_c2s.erl +++ b/src/ejabberd_c2s.erl @@ -659,6 +659,11 @@ wait_for_auth({xmlstreamelement, El}, StateData) -> privacy_list = PrivList}, fsm_next_state(session_established, NewStateData); _ -> + ejabberd_hooks:run(failed_auth_hook, + StateData#state.server, + [legacy, U, + StateData#state.server, + StateData#state.ip]), IP = peerip(StateData#state.sockmod, StateData#state.socket), ?INFO_MSG("(~w) Failed legacy authentication for " @@ -753,6 +758,11 @@ wait_for_feature_request({xmlstreamelement, El}, fsm_next_state(wait_for_sasl_response, StateData#state{sasl_state = NewSASLState}); {error, Error, Username} -> + ejabberd_hooks:run(failed_auth_hook, + StateData#state.server, + [sasl_auth, Username, + StateData#state.server, + StateData#state.ip]), IP = peerip(StateData#state.sockmod, StateData#state.socket), ?INFO_MSG("(~w) Failed authentication for ~s@~s from IP ~s", [StateData#state.socket, @@ -935,6 +945,11 @@ wait_for_sasl_response({xmlstreamelement, El}, fsm_next_state(wait_for_sasl_response, StateData#state{sasl_state = NewSASLState}); {error, Error, Username} -> + ejabberd_hooks:run(failed_auth_hook, + StateData#state.server, + [sasl_resp, Username, + StateData#state.server, + StateData#state.ip]), IP = peerip(StateData#state.sockmod, StateData#state.socket), ?INFO_MSG("(~w) Failed authentication for ~s@~s from IP ~s", [StateData#state.socket, @@ -947,6 +962,12 @@ wait_for_sasl_response({xmlstreamelement, El}, children = []}]}), fsm_next_state(wait_for_feature_request, StateData); {error, Error} -> + Username = element(5, element(9, StateData#state.sasl_state)), + ejabberd_hooks:run(failed_auth_hook, + StateData#state.server, + [sasl_resp, Username, + StateData#state.server, + StateData#state.ip]), send_element(StateData, #xmlel{name = <<"failure">>, attrs = [{<<"xmlns">>, ?NS_SASL}], -- 1.8.5.3 tmpcma5cyg4/mod_logsession/COPYING0000644000232200023220000004332414516675355017667 0ustar debalancedebalanceAs a special exception, the authors give permission to link this program with the OpenSSL library and distribute the resulting binary. GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. tmpcma5cyg4/mod_grafite/0000755000232200023220000000000014516675355016062 5ustar debalancedebalancetmpcma5cyg4/mod_grafite/README.md0000644000232200023220000000113114516675355017335 0ustar debalancedebalancemod_grafite - Gathers statistics and publishes via statsd/grafite ================================================================= * Author: Thiago Rocha Camargo (rochacamargothiago@gmail.com) Gathers statistics and publishes via statsd/grafite Configuration ------------- Configurable options: - `statsdhost`: Host of the statsd server - `statsdport`: Port of the statsd server Example Configuration --------------------- ```yaml modules: mod_grafite: statsdhost: "carbonr.xmpp.com.br" statsdport: 8125 ``` Feature Requests --------------- - Add support for configurable Hooks tmpcma5cyg4/mod_grafite/mod_grafite.spec0000644000232200023220000000040514516675355021215 0ustar debalancedebalanceauthor: "Thiago Rocha Camargo " category: "statistics" summary: "Publishes Statistics via statsd/grafite" home: "https://github.com/processone/ejabberd-contrib/tree/master/" url: "git@github.com:processone/ejabberd-contrib.git" tmpcma5cyg4/mod_grafite/conf/0000755000232200023220000000000014516675355017007 5ustar debalancedebalancetmpcma5cyg4/mod_grafite/conf/mod_grafite.yml0000644000232200023220000000012714516675355022012 0ustar debalancedebalance#modules: # mod_grafite: # statsdhost: "carbonr.xmpp.com.br" # statsdport: 8125 tmpcma5cyg4/mod_grafite/src/0000755000232200023220000000000014516675355016651 5ustar debalancedebalancetmpcma5cyg4/mod_grafite/src/mod_grafite.erl0000644000232200023220000001437314516675355021645 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : mod_grafite.erl %%% Author : Thiago Rocha Camargo %%% Purpose : Gathers statistics and publishes via statsd/grafite %%% Created : %%% Id : $Id: mod_grafite.erl 0000 2016-07-11 16:42:30Z xmppjingle $ %%%---------------------------------------------------------------------- %%%% Definitions -module(mod_grafite). -author('rochacamargothiago@gmail.com'). -behaviour(gen_mod). -include("logger.hrl"). -include_lib("xmpp/include/xmpp.hrl"). -export([start/2, stop/1, mod_opt_type/1, mod_options/1, depends/2, mod_doc/0, udp_loop_start/1, push/2]). -export([offline_message_hook/3, sm_register_connection_hook/3, sm_remove_connection_hook/3, user_send_packet/4, user_receive_packet/5, s2s_send_packet/3, s2s_receive_packet/3, remove_user/2, register_user/2, component_connected/1, component_disconnected/1]). -record(state, {socket, host, port}). -define(PROCNAME, ejabberd_mod_grafite). -define(GRAFITE_KEY(Node, Host, Probe), "mod_grafite.ejabberd." ++ erlang:binary_to_list(Node) ++ "_" ++ erlang:binary_to_list(Host) ++ "." ++ erlang:atom_to_list(Probe)). %%==================================================================== %% API %%==================================================================== start(Host, Opts) -> [ejabberd_hooks:add(Hook, Host, ?MODULE, Hook, 20) || Hook <- hooks()], [ejabberd_hooks:add(Hook, ?MODULE, Hook, 18) || Hook <- global_hooks()], StatsDH = gen_mod:get_opt(statsdhost, Opts), {ok, StatsDHost} = getaddrs(StatsDH), StatsDPort = gen_mod:get_opt(statsdport, Opts), register(?PROCNAME, spawn(?MODULE, udp_loop_start, [#state{host = StatsDHost, port = StatsDPort}])), ok. stop(Host) -> [ejabberd_hooks:delete(Hook, Host, ?MODULE, Hook, 20) || Hook <- hooks()], [ejabberd_hooks:delete(Hook, Host, ?MODULE, Hook, 20) || Hook <- global_hooks()], ok. depends(_Host, _Opts) -> []. mod_doc() -> #{}. hooks() -> [offline_message_hook, sm_register_connection_hook, sm_remove_connection_hook, user_send_packet, user_receive_packet, s2s_send_packet, s2s_receive_packet, remove_user, register_user]. global_hooks() -> [component_connected, component_disconnected]. %%==================================================================== %% Hooks handlers %%==================================================================== offline_message_hook(_From, #jid{lserver=LServer}, _Packet) -> push(LServer, offline_message). sm_register_connection_hook(_SID, #jid{lserver=LServer}, _Info) -> push(LServer, sm_register_connection). sm_remove_connection_hook(_SID, #jid{lserver=LServer}, _Info) -> push(LServer, sm_remove_connection). user_send_packet(Packet, _C2SState, #jid{lserver=LServer}, _To) -> push(LServer, user_send_packet), Packet. user_receive_packet(Packet, _C2SState, _JID, _From, #jid{lserver=LServer}) -> push(LServer, user_receive_packet), Packet. s2s_send_packet(#jid{lserver=LServer}, _To, _Packet) -> push(LServer, s2s_send_packet). s2s_receive_packet(_From, #jid{lserver=LServer}, _Packet) -> push(LServer, s2s_receive_packet). remove_user(_User, Server) -> push(jid:nameprep(Server), remove_user). register_user(_User, Server) -> push(jid:nameprep(Server), register_user). component_connected(Host) -> push(Host, component_connected). component_disconnected(Host) -> push(Host, component_disconnected). %%==================================================================== %% metrics push handler %%==================================================================== push(Host, Probe) -> Payload = encode_metrics(Host, Probe), whereis(?PROCNAME) ! {send, Payload}. encode_metrics(Host, Probe) -> [_, NodeId] = str:tokens(misc:atom_to_binary(node()), <<"@">>), [Node | _] = str:tokens(NodeId, <<".">>), Key = Probe, Data = encode(gauge, ?GRAFITE_KEY(Node, Host, Probe), 1, 1.0), ?INFO_MSG("Stats: ~p ~p ~n", [Data, encode(gauge, Key, 1, undefined)]), Data. %%==================================================================== %% Grafite/StatsD %%==================================================================== encode(gauge, Key, Value, _SampleRate) -> [Key, ":", format_value(Value), "|g"]. format_value(Value) when is_integer(Value) -> integer_to_list(Value). %%==================================================================== %% UDP Utils %%==================================================================== udp_loop_start(#state{}=S) -> LocalPort = 44444, case gen_udp:open(LocalPort) of {ok, Socket} -> ?INFO_MSG("UDP Stats Socket Open: [~p]~n", [LocalPort]), udp_loop(S#state{socket = Socket}); _ -> ?INFO_MSG("Could not start UDP Socket [~p]~n", [LocalPort]) end. udp_loop(#state{} = S) -> receive {send, Packet} -> send_udp(Packet, S), udp_loop(S); _ -> udp_loop(S) end. send_udp(Payload, #state{socket = Socket, host = Host, port = Port} = State) -> case gen_udp:send(Socket, Host, Port, Payload) of ok -> ok; _Error -> ?INFO_MSG("UDP Send Failed: [~p] (~p)~n", [State, Payload]) end. getaddrs({_, _, _, _} = Address) -> {ok, Address}; getaddrs(Hostname) when is_binary(Hostname) -> getaddrs(binary_to_list(Hostname)); getaddrs(Hostname) -> case inet:getaddrs(Hostname, inet) of {ok, Addrs} -> {ok, random_element(Addrs)}; {error, Reason} -> ?ERROR_MSG("getaddrs error: ~p~n", [Reason]), {error, Reason} end. random_element([Element]) -> Element; random_element([_|_] = List) -> T = list_to_tuple(List), Index = random(tuple_size(T)), element(Index, T). random(N) -> erlang:phash2({self(), timestamp()}, N) + 1. timestamp() -> os:timestamp(). %%==================================================================== %% mod Options %%==================================================================== mod_opt_type(statsdhost) -> econf:string(); mod_opt_type(statsdport) -> econf:pos_int(); mod_opt_type(_) -> [statsdhost, statsdport]. mod_options(_Host) -> [{statsdhost, "localhost"}, {statsdport, 8125}]. tmpcma5cyg4/mod_muc_log_http/0000755000232200023220000000000014516675355017125 5ustar debalancedebalancetmpcma5cyg4/mod_muc_log_http/README.md0000644000232200023220000000170014516675355020402 0ustar debalancedebalancemod_muc_log_http - Serve MUC logs on the web ============================================ * Requires: ejabberd 19.08 or higher * Homepage: http://ejabberd.im/mod_muc_log_http * Author: Badlop Description ----------- This module serves the directory containing MUC logs already configured on `mod_muc_log`. So, there's no need to setup a web server to allow your users to view the MUC logs. It is a small modification of `mod_http_fileserver`, customized for log serving. Configuration ------------- This module has no configurable options, simply enable it. Example Configuration --------------------- The directory to serve is already defined on `mod_muc_log`. ```yaml listen: - port: 5282 module: ejabberd_http request_handlers: /muclogs: mod_muc_log_http modules: mod_muc_log: outdir: "/tmp/muclogs" mod_muc_log_http: {} ``` With that example configuration, open your web browser at: `http://server:5282/muclogs/` tmpcma5cyg4/mod_muc_log_http/mod_muc_log_http.spec0000644000232200023220000000033414516675355023324 0ustar debalancedebalanceauthor: "Badlop " category: "log" summary: "Serve MUC logs on the web" home: "https://github.com/processone/ejabberd-contrib/tree/master/" url: "git@github.com:processone/ejabberd-contrib.git" tmpcma5cyg4/mod_muc_log_http/ChangeLog0000644000232200023220000000231714516675355020702 0ustar debalancedebalance2009-06-14 Badlop * src/mod_muc_log_http.erl: Include mod_muc_room.hrl 2009-03-11 Badlop * src/mod_muc_log_http.erl: Fix capitalization of HTTP headers 2009-02-28 Badlop * src/mod_muc_log_http.erl: Add support to run in several vhosts * README.txt: Explain that it requires recent ejabberd SVN 2008-09-30 Badlop * src/mod_muc_log_http.erl: Update record definitions to ejabberd trunk SVN 2008-05-17 Badlop * src/mod_muc_log_http.erl: Use httpd_util:to_lower when not compiling with Erlang R12 (EJAB-628) * Emakefile: Assumes that Erlang/OTP R11B-4 or newer is used * README.txt: Explain how to compile in older versions 2008-04-12 Badlop * src/mod_muc_log_http.erl: Include Last-Modified HTTP header in responses to allow caching (EJAB-546) 2008-03-12 Badlop * README.txt: Updated text formatting. Require ejabberd 2.0.0 * mod_muc_log_http.erl: Updated to ejabberd 2.0.0 * ChangeLog: New file to log changes 2007-04-13 Badlop * mod_muc_log_http: New module to serve MUC HTML logs over HTTP tmpcma5cyg4/mod_muc_log_http/conf/0000755000232200023220000000000014516675355020052 5ustar debalancedebalancetmpcma5cyg4/mod_muc_log_http/conf/mod_muc_log_http.yml0000644000232200023220000000027114516675355024120 0ustar debalancedebalancelisten: - port: 5282 module: ejabberd_http request_handlers: /muclogs: mod_muc_log_http modules: # mod_muc_log: # outdir: "/tmp/muclogs" mod_muc_log_http: {} tmpcma5cyg4/mod_muc_log_http/src/0000755000232200023220000000000014516675355017714 5ustar debalancedebalancetmpcma5cyg4/mod_muc_log_http/src/mod_muc_log_http.erl0000644000232200023220000001747414516675355023760 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : mod_muc_log_http.erl %%% Author : Badlop, Massimiliano Mirra %%% Purpose : MUC logs simple file server %%% Created : %%% Id : %%%---------------------------------------------------------------------- -module(mod_muc_log_http). -behaviour(gen_mod). -export([start/2, stop/1, depends/2, mod_options/1, mod_doc/0, mod_status/0]). -export([process/2]). -include_lib("xmpp/include/xmpp.hrl"). -include("ejabberd_http.hrl"). -include("mod_muc_room.hrl"). -include("logger.hrl"). -include_lib("kernel/include/file.hrl"). % TODO: % - If chatroom is password protected, ask password % - If chatroom is only for members, ask for username and password %% Copied from mod_muc/mod_muc.erl -record(muc_online_room, {name_host, pid}). %%%---------------------------------------------------------------------- %%% REQUEST HANDLERS %%%---------------------------------------------------------------------- process(Path, #request{raw_path = RawPath} = Request) -> Continue = case Path of [E] -> binary:match(E, <<".">>) /= nomatch; _ -> false end, case Continue orelse binary:at(RawPath, size(RawPath) - 1) == $/ of true -> serve(Path, Request); _ -> {301, [{<<"Location">>, <>}], <<>>} end. serve(LocalPathBin, #request{host = Host} = Request) -> DocRoot = binary_to_list(gen_mod:get_module_opt(Host, mod_muc_log, outdir)), LocalPath = [binary_to_list(LPB) || LPB <- LocalPathBin], FileName = filename:join(filename:split(DocRoot) ++ LocalPath), case file:read_file(FileName) of {ok, FileContents} -> ?DEBUG("Delivering content.", []), {200, [{"Server", "ejabberd"}, {"Last-Modified", last_modified(FileName)}, {"Content-Type", content_type(FileName)}], FileContents}; {error, eisdir} -> FileNameIndex = FileName ++ "/index.html", case file:read_file_info(FileNameIndex) of {ok, _FileInfo} -> serve(LocalPathBin ++ [<<"index.html">>], Request); {error, _Error} -> show_dir_listing(FileName, LocalPath) end; {error, Error} -> ?DEBUG("Delivering error: ~p", [Error]), case Error of eacces -> {403, [], "Forbidden"}; enoent -> {404, [], "Not found"}; _Else -> {404, [], atom_to_list(Error)} end end. %%%---------------------------------------------------------------------- %%% Dir listing %%%---------------------------------------------------------------------- build_datetimelist(DateTime) -> {{Ye, Mo, Da}, {Ho, Mi, Se}} = DateTime, Nums = [Mo, Da, Ho, Mi, Se], Nums2 = [fill(Num) || Num <- Nums], [integer_to_list(Ye)] ++ Nums2. fill(Num) when Num < 10 -> io_lib:format("0~p", [Num]); fill(Num) -> io_lib:format("~p", [Num]). %%%---------------------------------------------------------------------- %%% MUC INFO %%%---------------------------------------------------------------------- get_room_pid(Name, Host) -> case ets:lookup(muc_online_room, {Name, Host}) of [] -> unknown; [Room_ets] -> Room_ets#muc_online_room.pid end. get_room_config(Room_pid) -> {ok, C} = p1_fsm:sync_send_all_state_event(Room_pid, get_config), C. %%%---------------------------------------------------------------------- %%% MUC LIST %%%---------------------------------------------------------------------- show_dir_listing(DirName, LocalPath) -> Header = io_lib:format("Name Last modified Size Description~n", []), Address = io_lib:format("
ejabberd/~s Server
", [ejabberd_config:version()]), {ok, Listing} = file:list_dir(DirName), Listing2 = lists:sort(Listing), Listing3 = case LocalPath of [] -> lists:filter( fun(RoomFull) -> case string:tokens(RoomFull, "@") of [Room, Host] -> case get_room_pid(Room, Host) of unknown -> true; Room_pid -> (get_room_config(Room_pid))#config.public end; _ -> false % Don't show files that are not rooms end end, Listing2); _ -> Listing2 end, Listing4 = lists:map( fun(RoomFull) -> Desc = case string:tokens(RoomFull, "@") of [Room, Host] -> case get_room_pid(Room, Host) of unknown -> "-"; Room_pid -> (get_room_config(Room_pid))#config.title end; _ -> "-" end, {RoomFull, Desc} end, Listing3), DirNest = ["Chatroom logs" | LocalPath], {_, Indexof1} = lists:foldl( fun(E, {N, Res}) -> D = string:copies("../", N), Res2 = Res ++ io_lib:format("~s", [D, E]) ++ " > ", {N-1, Res2} end, {length(DirNest)-1, ""}, DirNest), Title1 = lists:foldl( fun(E, Res) -> Res ++ E ++ " > " end, "", DirNest), Title = io_lib:format("~s", [Title1]), Indexof = io_lib:format("

~s

", [Indexof1]), Files = lists:foldl( fun({Filename, Description}, Res) -> {ok, Fi} = file:read_file_info(DirName ++ "/" ++ Filename), {Filename2, Size} = case Fi#file_info.type of directory -> {Filename ++ "/", "-"}; _ -> {Filename, integer_to_list(Fi#file_info.size)} end, DateTimeList = build_datetimelist(Fi#file_info.ctime), Time = io_lib:format("~s-~s-~s ~s:~s:~s", DateTimeList), FillSpace = lists:flatten(lists:duplicate(50-length(Filename2), " ")), FileString = io_lib:format("~s~s ~s ~10s ~s~n", [Filename2, Filename2, FillSpace, Time, Size, Description]), Res ++ FileString end, "", Listing4), Content = "" ++ Title ++ "
"
		++ Indexof
		++ Header
		++ "
" ++ Files ++ "
" ++ Address ++ "", {200, [{"Server", "ejabberd"}, {"Content-Type", "text/html"}], Content}. %%%---------------------------------------------------------------------- %%% UTILITIES %%%---------------------------------------------------------------------- content_type(Filename) -> case string:to_lower(filename:extension(Filename)) of ".jpg" -> "image/jpeg"; ".jpeg" -> "image/jpeg"; ".gif" -> "image/gif"; ".png" -> "image/png"; ".html" -> "text/html"; ".css" -> "text/css"; ".txt" -> "text/plain"; ".xul" -> "application/vnd.mozilla.xul+xml"; ".jar" -> "application/java-archive"; ".xpi" -> "application/x-xpinstall"; _Else -> "application/octet-stream" end. last_modified(FileName) -> {ok, FileInfo} = file:read_file_info(FileName), Then = FileInfo#file_info.mtime, httpd_util:rfc1123_date(Then). %%%---------------------------------------------------------------------- %%% BEHAVIOUR CALLBACKS %%%---------------------------------------------------------------------- start(_Host, _Opts) -> ok. stop(_Host) -> ok. depends(_Host, _Opts) -> [{mod_muc_log, hard}]. mod_options(_Host) -> []. mod_doc() -> #{}. mod_status() -> Host = ejabberd_config:get_myname(), Url = case find_handler_port_path(any, ?MODULE) of [] -> undefined; [{ThisTls, Port, Path} | _] -> Protocol = case ThisTls of false -> <<"http">>; true -> <<"https">> end, <>))/binary, "/">> end, io_lib:format("Serving MUC logs in: ~s", [binary_to_list(Url)]). find_handler_port_path(Tls, Module) -> lists:filtermap( fun({{Port, _, _}, ejabberd_http, #{tls := ThisTls, request_handlers := Handlers}}) when (Tls == any) or (Tls == ThisTls) -> case lists:keyfind(Module, 2, Handlers) of false -> false; {Path, Module} -> {true, {ThisTls, Port, Path}} end; (_) -> false end, ets:tab2list(ejabberd_listener)). tmpcma5cyg4/mod_muc_log_http/COPYING0000644000232200023220000004332414516675355020166 0ustar debalancedebalanceAs a special exception, the authors give permission to link this program with the OpenSSL library and distribute the resulting binary. GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. tmpcma5cyg4/mod_deny_omemo/0000755000232200023220000000000014516675355016574 5ustar debalancedebalancetmpcma5cyg4/mod_deny_omemo/README.md0000644000232200023220000000240314516675355020052 0ustar debalancedebalancemod_deny_omemo - Prevent OMEMO sessions from being established ============================================================== * Author: Holger Weiss Description ----------- Unless the configured access rule (called `omemo` by default) returns `allow`, this module prevents OMEMO sessions from being established. Requests to query the devicelist from other users are rejected. Requests to publish a devicelist are also rejected, and all OMEMO nodes referenced in that devicelist are removed. Incoming devicelist updates are silently dropped. OMEMO-encrypted messages are bounced with an error message. Configuration ------------- In order to use this module, add configuration snippets such as the following: ```yaml access_rules: # [...] omemo: - deny: - user: "alice@example.com" - user: "bob@example.com" - allow # Permit OMEMO except for the JIDs above. modules: # [...] mod_deny_omemo: {} ``` The configurable `mod_deny_omemo` options are: - `access` (default: `omemo`) This option defines the access rule to control who will be able to establish OMEMO sessions. The default value is `omemo`. Establishing OMEMO sessions is only permitted if an access rule of that name exists and returns `allow`. tmpcma5cyg4/mod_deny_omemo/mod_deny_omemo.spec0000644000232200023220000000037414516675355022446 0ustar debalancedebalanceauthor: "Holger Weiss " category: "policy" summary: "Prevent OMEMO sessions from being established" home: "https://github.com/processone/ejabberd-contrib/tree/master/" url: "git@github.com:processone/ejabberd-contrib.git" tmpcma5cyg4/mod_deny_omemo/conf/0000755000232200023220000000000014516675355017521 5ustar debalancedebalancetmpcma5cyg4/mod_deny_omemo/conf/mod_deny_omemo.yml0000644000232200023220000000004014516675355023230 0ustar debalancedebalance#modules: # mod_deny_omemo: {} tmpcma5cyg4/mod_deny_omemo/src/0000755000232200023220000000000014516675355017363 5ustar debalancedebalancetmpcma5cyg4/mod_deny_omemo/src/mod_deny_omemo.erl0000644000232200023220000001722014516675355023063 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : mod_deny_omemo.erl %%% Author : Holger Weiss %%% Purpose : Prevent OMEMO sessions from being established %%% Created : 18 Mar 2018 by Holger Weiss %%% %%% %%% ejabberd, Copyright (C) 2018-2020 ProcessOne %%% %%% 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. %%% %%%---------------------------------------------------------------------- -module(mod_deny_omemo). -author('holger@zedat.fu-berlin.de'). -behavior(gen_mod). %% gen_mod callbacks. -export([start/2, stop/1, reload/3, mod_opt_type/1, depends/2, mod_options/1, mod_doc/0]). %% ejabberd_hooks callbacks. -export([user_receive_packet/1, user_send_packet/1]). -include("logger.hrl"). -include_lib("xmpp/include/xmpp.hrl"). -define(NS_AXOLOTL, "eu.siacs.conversations.axolotl"). -define(DEVICELIST_NODE, ?NS_AXOLOTL ".devicelist"). -type c2s_state() :: ejabberd_c2s:state(). -type hook_result() :: {stanza() | drop, c2s_state()} | {stop, {drop, c2s_state()}}. %%-------------------------------------------------------------------- %% gen_mod callbacks. %%-------------------------------------------------------------------- -spec start(binary(), gen_mod:opts()) -> ok. start(Host, _Opts) -> ejabberd_hooks:add(user_send_packet, Host, ?MODULE, user_send_packet, 50), ejabberd_hooks:add(user_receive_packet, Host, ?MODULE, user_receive_packet, 50). -spec stop(binary()) -> ok. stop(Host) -> ejabberd_hooks:delete(user_send_packet, Host, ?MODULE, user_send_packet, 50), ejabberd_hooks:delete(user_receive_packet, Host, ?MODULE, user_receive_packet, 50). -spec reload(binary(), gen_mod:opts(), gen_mod:opts()) -> ok. reload(_Host, _NewOpts, _OldOpts) -> ok. -spec mod_opt_type(atom()) -> econf:validator(). mod_opt_type(access) -> econf:acl(). -spec mod_options(binary()) -> [{atom(), any()}]. mod_options(_Host) -> [{access, omemo}]. -spec depends(binary(), gen_mod:opts()) -> [{module(), hard | soft}]. depends(_Host, _Opts) -> [{mod_pubsub, hard}]. mod_doc() -> #{}. %%-------------------------------------------------------------------- %% ejabberd_hooks callbacks. %%-------------------------------------------------------------------- -spec user_send_packet({stanza() | drop, c2s_state()}) -> hook_result(). user_send_packet({#message{}, _C2SState} = Acc) -> maybe_reject_msg(Acc); user_send_packet({#iq{type = set, from = #jid{luser = LUser, lserver = LServer}, to = #jid{luser = LUser, lserver = LServer, lresource = <<>>}, sub_els = [SubEl]}, _C2SState} = Acc) -> try xmpp:decode(SubEl) of #pubsub{publish = Publish} -> maybe_reject_iq(Publish, Acc); _ -> Acc catch _:{xmpp_codec, _Reason} -> Acc end; user_send_packet({#iq{type = get, from = #jid{luser = FromU, lserver = FromS}, to = #jid{luser = ToU, lserver = ToS, lresource = <<>>}, sub_els = [SubEl]}, _C2SState} = Acc) when FromU /= ToU; FromS /= ToS -> try xmpp:decode(SubEl) of #pubsub{items = Items} -> maybe_reject_iq(Items, Acc); _ -> Acc catch _:{xmpp_codec, _Reason} -> Acc end; user_send_packet(Acc) -> Acc. -spec user_receive_packet({stanza() | drop, c2s_state()}) -> hook_result(). user_receive_packet({#message{} = Msg, #{lserver := LServer, jid := JID} = C2SState} = Acc) -> case xmpp:get_subtag(Msg, #ps_event{}) of #ps_event{items = Items} -> Access = gen_mod:get_module_opt(LServer, ?MODULE, access), case acl:match_rule(LServer, Access, JID) of allow -> Acc; deny -> case find_omemo_nodes(Items) of [] -> Acc; _Nodes -> ?DEBUG("Dropping devicelist update sent to ~s", [jid:encode(JID)]), {stop, {drop, C2SState}} end end; _ -> maybe_reject_msg(Acc) end; user_receive_packet(Acc) -> Acc. %%-------------------------------------------------------------------- %% Internal functions. %%-------------------------------------------------------------------- -spec maybe_reject_msg({message(), c2s_state()}) -> {message(), c2s_state()} | {stop, {drop, c2s_state()}}. maybe_reject_msg({#message{lang = Lang} = Msg, #{lserver := LServer, jid := JID} = C2SState} = Acc) -> Access = gen_mod:get_module_opt(LServer, ?MODULE, access), case acl:match_rule(LServer, Access, JID) of allow -> Acc; deny -> case is_omemo_msg(Msg) of true -> ?DEBUG("Rejecting message from ~s", [jid:encode(JID)]), bounce_error(Msg, Lang), {stop, {drop, C2SState}}; false -> Acc end end. -spec maybe_reject_iq(ps_publish() | ps_items(), {iq(), c2s_state()}) -> {iq(), c2s_state()} | {stop, {drop, c2s_state()}}. maybe_reject_iq(El, {#iq{type = Type, lang = Lang} = IQ, #{lserver := LServer, jid := JID} = C2SState} = Acc) -> Access = gen_mod:get_module_opt(LServer, ?MODULE, access), case acl:match_rule(LServer, Access, JID) of allow -> Acc; deny -> case find_omemo_nodes(El) of [] -> Acc; Nodes -> ?DEBUG("Rejecting IQ ~s of ~s", [Type, jid:encode(JID)]), case Type of set -> delete_nodes(JID, Nodes); get -> ok end, bounce_error(IQ, Lang), {stop, {drop, C2SState}} end end. -spec find_omemo_nodes(ps_publish() | ps_items()) -> [binary()]. find_omemo_nodes(#ps_items{node = Node, items = Items}) -> find_omemo_nodes(Node, Items); find_omemo_nodes(#ps_publish{node = Node, items = Items}) -> find_omemo_nodes(Node, Items); find_omemo_nodes(_) -> []. -spec find_omemo_nodes(binary(), [ps_item()]) -> [binary()]. find_omemo_nodes(<> = Node, [Item]) -> [Node | find_bundle_nodes(Item)]; find_omemo_nodes(<> = Node, []) -> [Node]; find_omemo_nodes(_Node, _Item) -> []. -spec find_bundle_nodes(ps_item()) -> [binary()]. find_bundle_nodes(#ps_item{sub_els = [#xmlel{name = <<"list">>, attrs = [{<<"xmlns">>, <>}], children = Devices}]}) -> [<> || #xmlel{name = <<"device">>, attrs = [{<<"id">>, ID}]} <- Devices]; find_bundle_nodes(_Item) -> []. -spec delete_nodes(jid(), [binary()]) -> ok. delete_nodes(JID, Nodes) -> LJID = jid:remove_resource(jid:tolower(JID)), ?DEBUG("Removing the following nodes of ~s: ~p", [jid:encode(LJID), Nodes]), lists:foreach(fun(Node) -> mod_pubsub:delete_node(LJID, Node, JID) end, Nodes). -spec is_omemo_msg(message()) -> boolean(). is_omemo_msg(#message{type = error}) -> false; is_omemo_msg(#message{sub_els = SubEls}) -> case lists:keyfind(<<"encrypted">>, #xmlel.name, SubEls) of #xmlel{attrs = Attrs} -> lists:member({<<"xmlns">>, <>}, Attrs); false -> false end. -spec bounce_error(stanza(), binary()) -> ok. bounce_error(Pkt, Lang) -> Txt = <<"OMEMO is disabled">>, Err = xmpp:err_policy_violation(Txt, Lang), ejabberd_router:route_error(Pkt, Err). tmpcma5cyg4/mod_deny_omemo/COPYING0000644000232200023220000004346414516675355017642 0ustar debalancedebalanceAs a special exception, the authors give permission to link this program with the OpenSSL library and distribute the resulting binary. 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. tmpcma5cyg4/mod_shcommands/0000755000232200023220000000000014516675355016575 5ustar debalancedebalancetmpcma5cyg4/mod_shcommands/README.md0000644000232200023220000000317614516675355020063 0ustar debalancedebalancemod_shcommands - Execute shell commands ======================================= * Requires: ejabberd 19.08 or higher * Author: Badlop * http://ejabberd.im/mod_shcommands ***************** W A R N I N G ***************** USE THIS MODULE AT YOUR OWN RISK This module allows ejabberd administrators to remotely execute shell commands which could compromise both the ejabberd server and the whole machine. ***************** W A R N I N G ***************** Description ----------- This module provides the ejabberd server administrator a method to remotely execute shell commands in the ejabberd server. It provides a page in the ejabberd Web Admin. Only the administrators of the whole server can access this page. Three types of commands are possible: * ejabberd_ctl: makes a call to ejabberd_ctl * erlang shell: executes an erlang command * system shell: executes a command on the system shell The result of the execution will be shown. In the system shell, only non-interactive commands will work correctly, for example this will work: ``` ps -all ``` Don't use commands that start an interactive mode: * DON'T TRY THIS: top * DON'T TRY THIS: vim readme.txt This module does not check if the commands are dangerous or problematic, so this module is only recommended for experienced ejabberd and Erlang/OTP administrators. Configuration ------------- This module has no configurable options, simply enable it: ``` modules: mod_shcommands: {} ``` tmpcma5cyg4/mod_shcommands/ChangeLog0000644000232200023220000000050414516675355020346 0ustar debalancedebalance2009-05-09 Badlop * src/mod_shcommands.erl: Fix unused variables and web calls. 2007-12-26 Badlop * src/mod_shcommands.erl: Translate menu items of webadmin hooks in each module (EJAB-485) 2007-09-01 Badlop * mod_shcommands: Initial commit. tmpcma5cyg4/mod_shcommands/conf/0000755000232200023220000000000014516675355017522 5ustar debalancedebalancetmpcma5cyg4/mod_shcommands/conf/mod_shcommands.yml0000644000232200023220000000003614516675355023237 0ustar debalancedebalancemodules: mod_shcommands: {} tmpcma5cyg4/mod_shcommands/mod_shcommands.spec0000644000232200023220000000033314516675355022443 0ustar debalancedebalanceauthor: "Badlop " category: "admin" summary: "Execute shell commands" home: "https://github.com/processone/ejabberd-contrib/tree/master/" url: "git@github.com:processone/ejabberd-contrib.git" tmpcma5cyg4/mod_shcommands/src/0000755000232200023220000000000014516675355017364 5ustar debalancedebalancetmpcma5cyg4/mod_shcommands/src/mod_shcommands.erl0000644000232200023220000001624014516675355023066 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : mod_shcommands.erl %%% Author : Badlop %%% Purpose : Execute shell commands %%% Created : 1 Sep 2007 by Badlop %%% Id : $Id: mod_shcommands.erl 1034 2009-11-17 21:44:17Z badlop $ %%%---------------------------------------------------------------------- -module(mod_shcommands). -author('badlop@ono.com'). -behaviour(gen_mod). -export([start/2, stop/1, depends/2, mod_options/1, mod_doc/0, mod_status/0]). -export([execute_system/1, execute_erlang/1]). -export([web_menu_node/3, web_page_node/5]). -include_lib("xmpp/include/xmpp.hrl"). -include("ejabberd_commands.hrl"). -include("ejabberd_http.hrl"). -include("ejabberd_web_admin.hrl"). -include("translate.hrl"). %%------------------- %% gen_mod functions %%------------------- start(_Host, _Opts) -> ejabberd_hooks:add(webadmin_menu_node, ?MODULE, web_menu_node, 50), ejabberd_hooks:add(webadmin_page_node, ?MODULE, web_page_node, 50), ejabberd_commands:register_commands(get_commands_spec()), ok. stop(Host) -> ejabberd_hooks:delete(webadmin_menu_node, ?MODULE, web_menu_node, 50), ejabberd_hooks:delete(webadmin_page_node, ?MODULE, web_page_node, 50), case gen_mod:is_loaded_elsewhere(Host, ?MODULE) of false -> ejabberd_commands:unregister_commands(get_commands_spec()); true -> ok end. depends(_Host, _Opts) -> []. mod_options(_Host) -> []. mod_doc() -> #{}. mod_status() -> "Page available in WebAdmin -> Nodes -> your node -> Shell Commands". %%------------------- %% Commands %%------------------- get_commands_spec() -> [#ejabberd_commands{name = execute_system, tags = [system], desc = "Execute a system shell command", policy = admin, module = ?MODULE, function = execute_system, args_desc = ["Command to execute in the system shell"], args_example = ["uptime"], result_example = "12:02:10 up 1:34, 7 users, load average: 0,58, 0,56, 0,61", args = [{command, string}], result = {res, string}}, #ejabberd_commands{name = execute_erlang, tags = [system, erlang], desc = "Execute an erlang shell command", policy = admin, module = ?MODULE, function = execute_erlang, args = [{command, string}], args_desc = ["Command to execute in the Erlang shell"], args_example = ["erlang:system_info(system_version)."], result_example = "Erlang/OTP 22 [erts-10.7] [64-bit] [smp:2:2]\n", result = {res, string}} ]. execute_system(Command) -> {E, _} = parse1_command(<<"executeshe">>, {none, none, Command}, node()), lists:flatten(E). execute_erlang(Command) -> {E, _} = parse1_command(<<"executeerl">>, {none, Command, none}, node()), lists:flatten(io_lib:format("~p", [E])). %%------------------- %% Web Admin Menu %%------------------- web_menu_node(Acc, _Node, Lang) -> Acc ++ [{<<"shcommands">>, translate:translate(Lang, ?T("Shell Commands"))}]. %%------------------- %% Web Admin Page %%------------------- web_page_node(_, Node, [<<"shcommands">>], Query, Lang) -> Res = [?XC(<<"h1">>, translate:translate(Lang, ?T("Shell Commands"))) | get_content(Node, Query, Lang)], {stop, Res}; web_page_node(Acc, _, _, _, _) -> Acc. %%------------------- %% Generate content %%------------------- get_content(Node, Query, Lang) -> Instruct = translate:translate(Lang, ?T("Type a command in a textbox and click Execute.")), {{CommandCtl, CommandErl, CommandShell}, Res} = case catch parse_and_execute(Query, Node) of {'EXIT', _} -> {{"", "", ""}, Instruct}; Result_tuple -> Result_tuple end, TitleHTML = [ ?XC(<<"p">>, translate:translate(Lang, ?T("Type a command in a textbox and click Execute."))), ?XC(<<"p">>, translate:translate(Lang, ?T("Use only commands which immediately return a result."))), ?XC(<<"p">>, translate:translate(Lang, ?T("WARNING: Use this only if you know what you are doing."))) ], CommandHTML = [?XAE(<<"form">>, [{<<"method">>, <<"post">>}], [?XAE(<<"table">>, [], [?XE(<<"tbody">>, [?XE(<<"tr">>, [?X(<<"td">>), ?XCT(<<"td">>, <<"ejabberd_ctl">>), ?XE(<<"td">>, [?INPUTS(<<"text">>, <<"commandctl">>, list_to_binary(CommandCtl), <<"70">>), ?INPUTT(<<"submit">>, <<"executectl">>, translate:translate(Lang, ?T("Execute")))]) ] ), ?XE(<<"tr">>, [?X(<<"td">>), ?XCT(<<"td">>, <<"erlang shell">>), ?XE(<<"td">>, [?INPUTS(<<"text">>, <<"commanderl">>, list_to_binary(CommandErl), <<"70">>), ?INPUTT(<<"submit">>, <<"executeerl">>, translate:translate(Lang, ?T("Execute")))]) ] ), ?XE(<<"tr">>, [?X(<<"td">>), ?XCT(<<"td">>, <<"system shell">>), ?XE(<<"td">>, [?INPUTS(<<"text">>, <<"commandshe">>, list_to_binary(CommandShell), <<"70">>), ?INPUTT(<<"submit">>, <<"executeshe">>, translate:translate(Lang, ?T("Execute")))]) ] ) ] )])] )], ResHTML = [?XAC(<<"textarea">>, [{<<"wrap">>, <<"off">>}, {<<"style">>, <<"font-family:monospace;">>}, {<<"name">>, <<"result">>}, {<<"rows">>, <<"30">>}, {<<"cols">>, <<"80">>}], Res) ], TitleHTML ++ CommandHTML ++ ResHTML. parse_and_execute(Query, Node) -> {[Exec], _} = lists:partition( fun(ExType) -> lists:keymember(ExType, 1, Query) end, [<<"executectl">>, <<"executeerl">>, <<"executeshe">>]), Commands = {get_val(<<"commandctl">>, Query), get_val(<<"commanderl">>, Query), get_val(<<"commandshe">>, Query)}, {_, R} = parse1_command(Exec, Commands, Node), {Commands, R}. get_val(Val, Query) -> {value, {_, R}} = lists:keysearch(Val, 1, Query), binary_to_list(R). parse1_command(<<"executectl">>, {Command, _, _}, Node) -> Command2 = string:tokens(Command, " "), {_E, Efile} = execute(ctl, Node, Command2), {Efile, io_lib:format("ejabberdctl ~p ~s~n~s", [Node, Command, Efile])}; parse1_command(<<"executeerl">>, {_, Command, _}, Node) -> {ok, A2, _} = erl_scan:string(Command), {ok, A3} = erl_parse:parse_exprs(A2), {E, Efile} = execute(erl, Node, A3), {E, io_lib:format("(~p)1> ~s~s~n~p", [Node, Command, Efile, E])}; parse1_command(<<"executeshe">>, {_, _, Command}, Node) -> E = rpc:call(Node, os, cmd, [Command]), C1 = lists:map( fun(C) -> string:strip(os:cmd(C), right, $\n) end, ["whoami", "hostname -s", "pwd"]), {E, io_lib:format("~s@~s:~s$ ~s~n~s", C1 ++ [Command, E])}. execute(Type, Node, C) -> GL = group_leader(), Filename = <<"temp", (p1_rand:get_string())/binary>>, {ok, File} = file:open(Filename, [write]), group_leader(File, self()), Res = case Type of ctl -> rpc:call(Node, ejabberd_ctl, process, [C]); erl -> rpc:call(Node, erl_eval, exprs, [C, []]) end, E = case Res of {value, V, _} -> V; O -> O end, group_leader(GL, self()), file:close(File), {ok, B} = file:read_file(Filename), file:delete(Filename), E2 = case binary_to_list(B) of [] -> []; List -> "\n"++List end, {E, E2}. tmpcma5cyg4/mod_shcommands/COPYING0000644000232200023220000004332414516675355017636 0ustar debalancedebalanceAs a special exception, the authors give permission to link this program with the OpenSSL library and distribute the resulting binary. GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. tmpcma5cyg4/mod_log_chat/0000755000232200023220000000000014516675355016221 5ustar debalancedebalancetmpcma5cyg4/mod_log_chat/README.md0000644000232200023220000000062514516675355017503 0ustar debalancedebalancemod_log_chat ============ `mod_log_chat` is an ejabberd module aimed at logging chat messages in text files. `mod_log_chat` creates one file per couple of chatters and per day (it doesn't log muc messages, use `mod_muc_log` for this). It can store messages in plain text or HTML format. Be sure that the directories where you want to create your log files exists and are writable by you ejabberd user. tmpcma5cyg4/mod_log_chat/TODO0000644000232200023220000000010214516675355016702 0ustar debalancedebalance - Custom templates and CSS in the configuration file - XML formattmpcma5cyg4/mod_log_chat/mod_log_chat.spec0000644000232200023220000000037014516675355021514 0ustar debalancedebalanceauthor: "Jérôme Sautret " category: "log" summary: "Logging chat messages in text files" home: "https://github.com/processone/ejabberd-contrib/tree/master/" url: "git@github.com:processone/ejabberd-contrib.git" tmpcma5cyg4/mod_log_chat/conf/0000755000232200023220000000000014516675355017146 5ustar debalancedebalancetmpcma5cyg4/mod_log_chat/conf/mod_log_chat.yml0000644000232200023220000000126114516675355022310 0ustar debalancedebalance# edit this file to fit your needs # log all vhosts chats in /var/log/ejabberd/chat directory in html modules: mod_log_chat: path: auto # path: /var/log/ejabberd/chat # format: html # log only vh1.myjabberserver.net vhost in /var/log/ejabberd/vh1.myjabberserver.net directory # in HTML format and vh2.myjabberserver.net vhost in /var/log/ejabberd/vh2.myjabberserver.net directory # in text format # mod_log_chat: # host_config: # - "vh1.myjabberserver.net": # - path: /var/log/ejabberd/vh1.myjabberserver.net # - format: html # - "vh2.myjabberserver.net": # - path: /var/log/ejabberd/vh2.myjabberserver.net # - format: text tmpcma5cyg4/mod_log_chat/src/0000755000232200023220000000000014516675355017010 5ustar debalancedebalancetmpcma5cyg4/mod_log_chat/src/mod_log_chat.erl0000644000232200023220000002426014516675355022137 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : mod_log_chat.erl %%% Author : Jérôme Sautret %%% Purpose : Log 2 ways chat messages in files %%% Id : $Id: mod_log_chat.erl 412 2007-11-15 10:10:09Z mremond $ %%%---------------------------------------------------------------------- -module(mod_log_chat). -author('jerome.sautret@process-one.net'). -behaviour(gen_mod). -export([start/2, stop/1, depends/2, mod_opt_type/1, mod_options/1, mod_doc/0, mod_status/0]). -export([init/1, log_packet_send/1, log_packet_receive/1]). -include("logger.hrl"). -include_lib("xmpp/include/xmpp.hrl"). -define(PROCNAME, ?MODULE). -record(config, {path, format}). start(Host, Opts) -> ?DEBUG(" ~p ~p~n", [Host, Opts]), case gen_mod:get_opt(host_config, Opts) of [] -> start_vh(Host, Opts); HostConfig -> start_vhs(Host, HostConfig) end, ok. start_vhs(_, []) -> ok; start_vhs(Host, [{Host, Opts}| Tail]) -> ?DEBUG("start_vhs ~p ~p~n", [Host, [{Host, Opts}| Tail]]), start_vh(Host, Opts), start_vhs(Host, Tail); start_vhs(Host, [{_VHost, _Opts}| Tail]) -> ?DEBUG("start_vhs ~p ~p~n", [Host, [{_VHost, _Opts}| Tail]]), start_vhs(Host, Tail). start_vh(Host, Opts) -> Path = case gen_mod:get_opt(path, Opts) of auto -> filename:dirname(ejabberd_logger:get_log_path()); PP -> PP end, Format = gen_mod:get_opt(format, Opts), ejabberd_hooks:add(user_send_packet, Host, ?MODULE, log_packet_send, 55), ejabberd_hooks:add(user_receive_packet, Host, ?MODULE, log_packet_receive, 55), register(gen_mod:get_module_proc(Host, ?PROCNAME), spawn(?MODULE, init, [#config{path=Path, format=Format}])). init(Config)-> ?DEBUG("Starting ~p with config ~p~n", [?MODULE, Config]), loop(Config). loop(Config) -> receive {call, Caller, get_config} -> Caller ! {config, Config}, loop(Config); stop -> exit(normal) end. stop(Host) -> ejabberd_hooks:delete(user_send_packet, Host, ?MODULE, log_packet_send, 55), ejabberd_hooks:delete(user_receive_packet, Host, ?MODULE, log_packet_receive, 55), gen_mod:get_module_proc(Host, ?PROCNAME) ! stop, ok. log_packet_send({Packet, C2SState}) -> From = xmpp:get_from(Packet), To = xmpp:get_to(Packet), log_packet(From, To, Packet, From#jid.lserver), {Packet, C2SState}. log_packet_receive({Packet, C2SState}) -> From = xmpp:get_from(Packet), To = xmpp:get_to(Packet), %% only log at send time if the message is local to the server case From#jid.lserver == To#jid.lserver of true -> ok; false -> log_packet(From, To, Packet, To#jid.lserver) end, {Packet, C2SState}. log_packet(From, To, #message{type = Type} = Packet, Host) -> case Type of groupchat -> %% mod_muc_log already does it ?DEBUG("dropping groupchat: ~s", [fxml:element_to_binary(xmpp:encode(Packet))]), ok; error -> %% we don't log errors ?DEBUG("dropping error: ~s", [fxml:element_to_binary(xmpp:encode(Packet))]), ok; _ -> write_packet(From, To, Packet, Host) end; log_packet(_From, _To, _Packet, _Host) -> ok. write_packet(From, To, Packet, Host) -> gen_mod:get_module_proc(Host, ?PROCNAME) ! {call, self(), get_config}, Config = receive {config, Result} -> Result end, Format = Config#config.format, {Subject, Body} = {case Packet#message.subject of [] -> <<>>; SubjEl -> escape(Format, xmpp:get_text(SubjEl)) end, escape(Format, xmpp:get_text(Packet#message.body))}, case Subject == <<>> andalso Body == <<>> of true -> %% don't log empty messages ?DEBUG("not logging empty message from ~s",[jid:encode(From)]), ok; false -> Path = Config#config.path, FromJid = jid:encode(jid:make(From#jid.luser, From#jid.lserver)), ToJid = jid:encode(jid:make(To#jid.luser, To#jid.lserver)), {FilenameTemplate, DateString, Header, MessageType} = case calendar:local_time() of {{Y, M, D}, {H, Min, S}} -> SortedJid = lists:sort([FromJid, ToJid]), Title = io_lib:format(template(Format, title), [FromJid, ToJid, Y, M, D]), {lists:flatten(io_lib:format("~s/~~p-~~2.2.0w-~~2.2.0w ~s - ~s~s", [Path | SortedJid]++[template(Format, extension)])), io_lib:format(template(Format, date), [Y, M, D, H, Min, S]), io_lib:format(template(Format, header), lists:duplicate(count(template(Format, header), "~s"), Title) ), case hd(SortedJid) of FromJid -> message1; ToJid -> message2 end } end, ?DEBUG("FilenameTemplate ~p~n",[FilenameTemplate]), Filename = make_filename(FilenameTemplate, [Y, M, D]), ?DEBUG("logging message from ~s into ~s~n",[jid:encode(From), Filename]), File = case file:read_file_info(Filename) of {ok, _} -> open_logfile(Filename); {error, enoent} -> close_previous_logfile(FilenameTemplate, Format, {Y, M, D}), NewFile = open_logfile(Filename), io:format(NewFile, Header, []), NewFile end, MessageText = case Subject == <<>> of true -> Body; false -> io_lib:format(template(Format, subject), [Subject])++Body end, ?DEBUG("MessageTemplate ~s~n",[template(Format, MessageType)]), ?DEBUG("Data: ~s ~s ~s ~s ~s ~s ~n",[DateString, FromJid, From#jid.lresource, ToJid, To#jid.lresource, MessageText]), io:format(File, lists:flatten(template(Format, MessageType)), [DateString, FromJid, From#jid.lresource, ToJid, To#jid.lresource, MessageText]), file:close(File) end. make_filename(Template, [Y, M, D]) -> list_to_binary(io_lib:format(Template, [Y, M, D])). open_logfile(Filename) -> case file:open(Filename, [append]) of {ok, File} -> File; {error, Reason} -> ?ERROR_MSG("Cannot write into file ~s: ~p~n", [Filename, Reason]) end. close_previous_logfile(FilenameTemplate, Format, Date) -> Yesterday = calendar:gregorian_days_to_date(calendar:date_to_gregorian_days(Date) - 1), Filename = make_filename(FilenameTemplate, tuple_to_list(Yesterday)), case file:read_file_info(Filename) of {ok, _} -> File = open_logfile(Filename), io:format(File, template(Format, footer), []), file:close(File); {error, enoent} -> ok end. escape(html, <<$<, Text/binary>>, Acc) -> escape(html,Text,<>); escape(html, <<$&, Text/binary>>, Acc) -> escape(html,Text,<>); escape(html, <>, Acc) -> escape(html,Text,<>); escape(html, <<>>, Acc) -> Acc. escape(html, Text) -> escape(html,Text,<<>>); escape(text, Text) -> Text. % return the number of occurence of Word in String count(String, Word) -> case string:str(String, Word) of 0 -> 0; N -> 1+count(string:substr(String, N+length(Word)), Word) end. template(text, extension) -> ".log"; template(text, title) -> "Messages log between ~s and ~s on ~p-~2.2.0w-~2.2.0w"; template(text, header) -> "~s~n-----------------------------------------------------------------------~n"; template(text, subject) -> "Subject: ~s~n"; template(text, message) -> "~~s ~~s/~~s -> ~~s/~~s~n~s~~s~n"; template(text, message1) -> io_lib:format(template(text, message), ["> "]); template(text, message2) -> io_lib:format(template(text, message), ["< "]); template(text, date) -> "~p-~2.2.0w-~2.2.0w ~2.2.0w:~2.2.0w:~2.2.0w"; template(text, footer) -> "---- End ----~n"; template(html, extension) -> ".html"; template(html, title) -> template(text, title); template(html, header) -> "~n"++ "~s"++ css()++ "~n

~s

~n"; template(html, subject) -> "
Subject: ~s
"; template(html, message) -> "
~~s ~~s/~~s -> ~~s/~~s~~n~~s
~~n"; template(html, message1) -> io_lib:format(template(html, message), [1]); template(html, message2) -> io_lib:format(template(html, message), [2]); template(html, date) -> "~p-~2.2.0w-~2.2.0w ~2.2.0w:~2.2.0w:~2.2.0w"; template(html, footer) -> "". css() -> "~n". depends(_Host, _Opts) -> []. mod_opt_type(host_config) -> econf:list(econf:any()); mod_opt_type(path) -> econf:either(auto, econf:directory(write)); mod_opt_type(format) -> fun (A) when is_atom(A) -> A end. mod_options(_Host) -> [{host_config, []}, {path, auto}, {format, text}]. mod_doc() -> #{}. mod_status() -> Host = ejabberd_config:get_myname(), gen_mod:get_module_proc(Host, ?PROCNAME) ! {call, self(), get_config}, Config = receive {config, Result} -> Result end, Format = Config#config.format, Path = Config#config.path, io_lib:format("Logging with format '~p' to path: ~s", [Format, Path]). tmpcma5cyg4/mod_log_chat/COPYING0000644000232200023220000006364214516675355017267 0ustar debalancedebalance GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 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. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, 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 and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, 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 library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete 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 distribute a copy of this License along with the Library. 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 Library or any portion of it, thus forming a work based on the Library, 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) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, 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 Library, 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 Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you 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. If distribution of 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 satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be 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. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library 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. 9. 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 Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library 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 with this License. 11. 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 Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library 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 Library. 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. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library 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. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser 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 Library 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 Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, 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 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. 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 LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), 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 Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. 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 library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! tmpcma5cyg4/mod_webadmin_config/0000755000232200023220000000000014516675355017554 5ustar debalancedebalancetmpcma5cyg4/mod_webadmin_config/README.md0000644000232200023220000000143314516675355021034 0ustar debalancedebalancemod_webadmin_config: Show Configuration in Web Admin ==================================================== This module shows a page in ejabberd's Web Admin to view and reload the configuration. The page is available in Web Admin -> Nodes -> your node. It shows the node's current configuration as stored in the internal memory, which includes the content of the main `ejabberd.yml`, the content of any files added with `include_config_file`, and the configuration added by contributed modules. The page also allows to reload the configuration, similarly to the `reload_config` API command. It also displays a diff of last changes detected in the configuration. # Configuration The module has no options to configure, it's simply enabled with: ```yaml modules: mod_webadmin_config: {} ``` tmpcma5cyg4/mod_webadmin_config/mod_webadmin_config.spec0000644000232200023220000000034414516675355024403 0ustar debalancedebalanceauthor: "Badlop " category: "admin" summary: "Show configuration in Web Admin" home: "https://github.com/processone/ejabberd-contrib/tree/master/" url: "git@github.com:processone/ejabberd-contrib.git" tmpcma5cyg4/mod_webadmin_config/conf/0000755000232200023220000000000014516675355020501 5ustar debalancedebalancetmpcma5cyg4/mod_webadmin_config/conf/mod_webadmin_config.yml0000644000232200023220000000004314516675355025173 0ustar debalancedebalancemodules: mod_webadmin_config: {} tmpcma5cyg4/mod_webadmin_config/src/0000755000232200023220000000000014516675355020343 5ustar debalancedebalancetmpcma5cyg4/mod_webadmin_config/src/mod_webadmin_config.erl0000644000232200023220000001305614516675355025026 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : mod_webadmin_config.erl %%% Author : Badlop %%% Purpose : Show Configuration in Web Admin %%% Created : 5 Aug 2022 by Badlop %%%---------------------------------------------------------------------- -module(mod_webadmin_config). -author('badlop@process-one.net'). -behaviour(gen_mod). -export([start/2, stop/1, depends/2, mod_options/1, mod_doc/0, mod_status/0]). -export([get_content/3]). -export([web_menu_node/3, web_page_node/5]). -include_lib("xmpp/include/xmpp.hrl"). -include("ejabberd_http.hrl"). -include("ejabberd_web_admin.hrl"). -include("logger.hrl"). -include("translate.hrl"). -define(OLDFILE, "old.yml"). -define(NEWFILE, "new.yml"). %%------------------- %% gen_mod functions %%------------------- start(_Host, _Opts) -> ejabberd_hooks:add(webadmin_menu_node, ?MODULE, web_menu_node, 50), ejabberd_hooks:add(webadmin_page_node, ?MODULE, web_page_node, 50), ok. stop(_Host) -> ejabberd_hooks:delete(webadmin_menu_node, ?MODULE, web_menu_node, 50), ejabberd_hooks:delete(webadmin_page_node, ?MODULE, web_page_node, 50), ok. depends(_Host, _Opts) -> []. mod_options(_Host) -> []. mod_doc() -> #{}. mod_status() -> "Page available in WebAdmin -> Nodes -> your node -> Configuration". %%------------------- %% Web Admin Menu %%------------------- web_menu_node(Acc, _Node, Lang) -> Acc ++ [{<<"config">>, translate:translate(Lang, ?T("Configuration"))}]. %%------------------- %% Web Admin Page %%------------------- web_page_node(_, Node, [<<"config">>], Query, Lang) -> Res = rpc:call(Node, mod_webadmin_config, get_content, [Node, Query, Lang]), {stop, Res}; web_page_node(Acc, _, _, _, _) -> Acc. %%------------------- %% Config Changes %%------------------- config_tmp_filename(Filename) -> filename:join(filename:dirname(ejabberd_logger:get_log_path()), Filename). dump_config(Filename) -> ejabberd_config:dump(config_tmp_filename(Filename)). get_last_config_changes() -> OldFn = config_tmp_filename(?OLDFILE), NewFn = config_tmp_filename(?NEWFILE), case {file:read_file(OldFn), file:read_file(NewFn)} of {{ok, _}, {ok, _}} -> os:cmd("diff -u " ++ config_tmp_filename(?OLDFILE) ++ " " ++ config_tmp_filename(?NEWFILE)); _ -> "Old and/or new configuration not found." end. get_lines_length(Data) -> [LongString] = io_lib:format("~s", [lists:flatten(Data)]), %% The newline character \n is integer 10 in erlang lists:foldl(fun (10, Sum) -> Sum + 1; (_, Sum) -> Sum end, 0, LongString ). get_config_paths_els() -> Bins = [ejabberd_config:path(), ext_mod:config_dir() | ext_mod:modules_configs()], [?LI([?C(Bin)]) || Bin <- Bins]. %%------------------- %% Generate content %%------------------- get_content(Node, Query, Lang) -> Res = node_reload_parse_query(Node, Query, Lang), Y = ejabberd_config:get_option(yaml_config), Data = fast_yaml:encode(Y), LastConfigChanges = get_last_config_changes(), ResEl = case Res of ok -> [?XREST(?T("Submitted"))]; {error, ErrorText} -> [?XREST(<<"Error: ", ErrorText/binary>>)]; nothing -> [] end, ConfigurationPathsEls = get_config_paths_els(), ?H1GL(str:translate_and_format(Lang, ?T("Configuration at ~p"), [Node]), <<"file-format/#reload-at-runtime">>, <<"Reload at Runtime">>) ++ ResEl ++ [?XCT(<<"h3">>, ?T("Configuration paths:")), ?XE(<<"ul">>, ConfigurationPathsEls), ?BR, ?XAE(<<"form">>, [{<<"action">>, <<"">>}, {<<"method">>, <<"post">>}], [?INPUTT(<<"submit">>, <<"reload">>, ?T("Reload Configuration"))] ), ?XCT(<<"h3">>, ?T("Configuration changes in last reload:")), ?XAC(<<"textarea">>, [{<<"wrap">>, <<"off">>}, {<<"style">>, <<"font-family:monospace;">>}, {<<"class">>, <<"result">>}, {<<"name">>, <<"result">>}, {<<"rows">>, integer_to_binary(get_lines_length(LastConfigChanges))}, {<<"cols">>, <<"80">>}], list_to_binary(LastConfigChanges) ), ?XCT(<<"h3">>, ?T("Configuration in memory:")), ?XAC(<<"textarea">>, [{<<"wrap">>, <<"off">>}, {<<"style">>, <<"font-family:monospace;">>}, {<<"class">>, <<"result">>}, {<<"name">>, <<"result">>}, {<<"rows">>, integer_to_binary(get_lines_length(Data))}, {<<"cols">>, <<"80">>}], list_to_binary(Data) ) ]. node_reload_parse_query(Node, Query, _Lang) -> case lists:keysearch(<<"reload">>, 1, Query) of {value, _} -> dump_config(?OLDFILE), case ejabberd_cluster:call(Node, ejabberd_config, reload, []) of ok -> dump_config(?NEWFILE), ok; {error, Error} -> ?ERROR_MSG("~p~n", [Error]), {error, (str:format("~p", [Error]))}; {badrpc, Error} -> ?ERROR_MSG("Bad RPC: ~p~n", [Error]), {error, <<"Bad RPC: ", (str:format("~p", [Error]))/binary>>} end; _ -> nothing end. tmpcma5cyg4/mod_webadmin_config/COPYING0000644000232200023220000004346414516675355020622 0ustar debalancedebalanceAs a special exception, the authors give permission to link this program with the OpenSSL library and distribute the resulting binary. 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. tmpcma5cyg4/ejabberd_auth_http/0000755000232200023220000000000014516675355017420 5ustar debalancedebalancetmpcma5cyg4/ejabberd_auth_http/README.md0000644000232200023220000001561214516675355020704 0ustar debalancedebalance# HTTP authentication module ## Overview The purpose of this module is to connect with an external REST API and delegate the authentication operations to it whenever possible. The component must implement the API described in one of the next sections for `ejabberd_auth_http` to work out of the box. Thanks to ejabberd design, the user base does not have to be local and this approach allows you to avoid user base duplication, without having to grant access to your main backend database. The module can be especially useful for users maintaining their own, central user database, which is shared with other services. It fits perfectly when client application uses custom authentication token and ejabberd has to validate it externally. This module requires ejabberd 20.02 or higher. ## Configuration ### How to enable The simplest way is to just replace default `auth_method` option in `ejabberd.yml` with `auth_method: http`. However, enabling the module **is not enough!** Please follow instructions below. ### Configuration options `ejabberd_auth_http` requires some parameters to function properly. The following options can be set in `auth_opts` in `ejabberd.yml`: * `host` (mandatory, `string`) - consists of protocol, hostname (or IP) and port (optional). Examples: * `host: "http://localhost:12000"` * `host: "https://10.20.30.40"` * `connection_pool_size` (optional, `integer`, default: 10) - the number of connections open to auth service * `connection_opts` (optional, default: `[]`) - extra options for hackers: http://erlang.org/doc/man/gen_tcp.html#type-connect_option * `basic_auth` (optional, default: `""`) - HTTP Basic Authentication in format `"username:password"`; auth service doesn't have to require authentication for HTTP auth to work * `path_prefix` (optional, default: `"/"`) - a path prefix to be inserted between `host` and method name; must be terminated with `/` Example configuration: ``` auth_method: http auth_opts: host: "http://localhost:12000" connection_pool_size: 10 connection_opts: [] basic_auth: "" path_prefix: "/" ``` ## SCRAM support `ejabberd_auth_http` can use the SCRAM method. When SCRAM is enabled, the passwords sent to the auth service are serialised and the same serialised format is expected when fetching a password from the component. It is transparent when ejabberd is responsible for all DB operations such as password setting, account creation etc. The service CAN perform the (de)serialisation of SCRAM-encoded passwords, using a format that will be described in near future in separate document. ## Authentication service API All GET requests include the following URL-encoded query string: `?user=&server=&pass=`. All POST requests have the following URL-encoded string in the request body: `user=&server=&pass=`. If certain method does not need a password, the value of `pass` is **undefined**, so it shouldn't be used. For the best integration, the return code range should not exceed the list below: * 500 - internal server error * 409 - conflict * 404 - not found * 403 - not allowed * 401 - not authorised * 400 - other error, should be sent in response body * 204 - success, no return data * 201 - created * 200 - success, return value in response body Whenever the specification says "anything else", service should use one of the codes from the list above. Some requests consider multiple return codes a "success". It is up to the server-side developer to pick one of the codes. ### `check_password` * **Method:** GET * **Type:** mandatory when SCRAM is not used * **Return values:** * 200, `true` or `false` in body * anything else - will be treated as `false` * **Description:** Must respond if the password is valid for user. ### `get_password` * **Method:** GET * **Type:** mandatory when SCRAM or DIGEST SASL mechanism is used * **Return values:** * 200, password in the body * anything else - `get_password` will fail * **Description:** Must return the user's password in plaintext or in the SCRAM serialised form. ### `user_exists` * **Method:** GET * **Type:** mandatory * **Return values:** * 200, `true` or `false` in body * anything else - will be treated as `false` * **Description:** Must return the information whether the user exists in DB. ### `set_password` * **Method:** POST * **Type:** mandatory when `mod_register` is enabled * **Return values:** * 200 or 201 or 204 - success * anything else - will be treated as `false` * **Description:** Must set user's password in the internal database to a provided value. The value should not be transformed (except for URL-decoding) before writing into DB. ### `remove_user` * **Method:** POST * **Type:** mandatory when `mod_register` is enabled * **Return values:** * 200 or 201 or 204 - success * 404 - user does not exist * 403 - not allowed for some reason * 40X - will be treated as `bad request` * **Description:** Removes a user account. ### `remove_user_validate` * **Method:** POST * **Type:** mandatory when `mod_register` is enabled * **Return values:** * 200 or 201 or 204 - success * 404 - user does not exist * 403 - invalid user password or not allowed for other reason * 40X - will be treated as `bad request` * **Description:** Removes a user account only if provided password is valid. ### `register` * **Method:** POST * **Type:** mandatory when `mod_register` is enabled * **Return values:** * 201 - success * 409 - user already exists * anything else - will be treated as failure * **Description:** Creates a user account. ## Authentication service API recipes Below are some examples of the auth service APIs and ejabberd-side configuration along with use cases. ### System using common, custom auth token An Auth token is provided as a password. * **Service implements:** `check_password`, `user_exists` * **ejabberd config:** `auth_password format`: `plain`, `mod_register` disabled * **Client side:** MUST NOT use `DIGEST-MD5` mechanism; use `PLAIN` ### Central database of plaintext passwords * **Service implements:** `check_password`, `get_password`, `user_exists` * **ejabberd config:** `auth_password_format`: `plain`, `mod_register` disabled * **Client side:** May use any available auth method ### Central database able to process SCRAM * **Service implements:** `get_password`, `user_exists` * **ejabberd config:** `auth_password_format`: `scram`, `mod_register` disabled * **Client side:** May use any available auth method ### All-included * **Service implements:** all methods * **ejabberd config:** `auth_password_format`: `scram` (recommended) or `plain`, `mod_register` enabled * **Client side:** May use any available auth method ## Troubleshooting If the service supports multiple passwords per user you need to disable authentication caching with `auth_use_cache: false`. See [https://github.com/processone/ejabberd-contrib/issues/288](https://github.com/processone/ejabberd-contrib/issues/288). tmpcma5cyg4/ejabberd_auth_http/rebar.config0000644000232200023220000000022514516675355021701 0ustar debalancedebalance{deps, [ {cuesport, ".*", {git, "https://github.com/goj/cuesport"}}, {fusco, ".*", {git, "https://github.com/esl/fusco"}} ]}. tmpcma5cyg4/ejabberd_auth_http/ejabberd_auth_http.spec0000644000232200023220000000036214516675355024113 0ustar debalancedebalanceauthor: "Piotr Nosek " category: "auth" summary: "Authentication via HTTP request" home: "https://github.com/processone/ejabberd-contrib/tree/master/" url: "git@github.com:processone/ejabberd-contrib.git" tmpcma5cyg4/ejabberd_auth_http/src/0000755000232200023220000000000014516675355020207 5ustar debalancedebalancetmpcma5cyg4/ejabberd_auth_http/src/scram2.erl0000644000232200023220000001516214516675355022107 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : scram.erl %%% Author : Stephen Röttger %%% Purpose : SCRAM (RFC 5802) %%% Created : 7 Aug 2011 by Stephen Röttger %%% %%% %%% ejabberd, Copyright (C) 2002-2020 ProcessOne %%% %%% 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., 59 Temple Place, Suite 330, Boston, MA %%% 02111-1307 USA %%% %%%---------------------------------------------------------------------- -module(scram2). -author('stephen.roettger@googlemail.com'). -include_lib("xmpp/include/scram.hrl"). -include("logger.hrl"). %% External exports %% ejabberd doesn't implement SASLPREP, so we use the similar RESOURCEPREP instead -export([ % Core SCRAM functions salted_password/3, stored_key/1, server_key/1, server_signature/2, client_signature/2, client_key/1, client_key/2]). -export([ enabled/1, iterations/0, iterations/1, password_to_scram/1, password_to_scram/2, check_password/2, check_digest/4 ]). -export([serialize/1, deserialize/1]). -export([scram_to_tuple/1]). -define(SALT_LENGTH, 16). -define(SCRAM_SERIAL_PREFIX, "==SCRAM==,"). -spec salted_password(binary(), binary(), non_neg_integer()) -> binary(). salted_password(Password, Salt, IterationCount) -> hi(jid:resourceprep(Password), Salt, IterationCount). -spec client_key(binary()) -> binary(). client_key(SaltedPassword) -> crypto_hmac(sha, SaltedPassword, <<"Client Key">>). -spec stored_key(binary()) -> binary(). stored_key(ClientKey) -> crypto:hash(sha, ClientKey). -spec server_key(binary()) -> binary(). server_key(SaltedPassword) -> crypto_hmac(sha, SaltedPassword, <<"Server Key">>). -spec client_signature(binary(), binary()) -> binary(). client_signature(StoredKey, AuthMessage) -> crypto_hmac(sha, StoredKey, AuthMessage). -spec client_key(binary(), binary()) -> binary(). client_key(ClientProof, ClientSignature) -> list_to_binary(lists:zipwith(fun (X, Y) -> X bxor Y end, binary_to_list(ClientProof), binary_to_list(ClientSignature))). -spec server_signature(binary(), binary()) -> binary(). server_signature(ServerKey, AuthMessage) -> crypto_hmac(sha, ServerKey, AuthMessage). hi(Password, Salt, IterationCount) -> U1 = crypto_hmac(sha, Password, <>), list_to_binary(lists:zipwith(fun (X, Y) -> X bxor Y end, binary_to_list(U1), binary_to_list(hi_round(Password, U1, IterationCount - 1)))). hi_round(Password, UPrev, 1) -> crypto_hmac(sha, Password, UPrev); hi_round(Password, UPrev, IterationCount) -> U = crypto_hmac(sha, Password, UPrev), list_to_binary(lists:zipwith(fun (X, Y) -> X bxor Y end, binary_to_list(U), binary_to_list(hi_round(Password, U, IterationCount - 1)))). enabled(Host) -> case ejabberd_config:get_option({auth_opts, Host}) of undefined -> false; AuthOpts -> {password_format, scram} == lists:keyfind(password_format, 1, AuthOpts) end. iterations() -> ?SCRAM_DEFAULT_ITERATION_COUNT. iterations(Host) -> case ejabberd_config:get_option({auth_opts, Host}) of undefined -> iterations(); AuthOpts -> case lists:keyfind(scram_iterations, 1, AuthOpts) of false -> iterations(); {_, Iterations} -> Iterations end end. password_to_scram(Password) -> password_to_scram(Password, ?SCRAM_DEFAULT_ITERATION_COUNT). password_to_scram(#scram{} = Password, _) -> Password; password_to_scram(Password, IterationCount) -> Salt = p1_rand:bytes(?SALT_LENGTH), SaltedPassword = salted_password(Password, Salt, IterationCount), StoredKey = stored_key(scram2:client_key(SaltedPassword)), ServerKey = server_key(SaltedPassword), #scram{storedkey = base64:encode(StoredKey), serverkey = base64:encode(ServerKey), salt = base64:encode(Salt), iterationcount = IterationCount}. check_password(Password, Scram) -> IterationCount = Scram#scram.iterationcount, Salt = base64:decode(Scram#scram.salt), SaltedPassword = salted_password(Password, Salt, IterationCount), StoredKey = stored_key(client_key(SaltedPassword)), (base64:decode(Scram#scram.storedkey) == StoredKey). serialize(#scram{storedkey = StoredKey, serverkey = ServerKey, salt = Salt, iterationcount = IterationCount})-> IterationCountBin = integer_to_binary(IterationCount), << <>/binary, StoredKey/binary,$,,ServerKey/binary, $,,Salt/binary,$,,IterationCountBin/binary>>. deserialize(<>) -> case catch binary:split(Serialized, <<",">>, [global]) of [StoredKey, ServerKey,Salt,IterationCount] -> {ok, #scram{storedkey = StoredKey, serverkey = ServerKey, salt = Salt, iterationcount = binary_to_integer(IterationCount)}}; _ -> ?WARNING_MSG("Incorrect serialized SCRAM: ~p, ~p", [Serialized]), {error, incorrect_scram} end; deserialize(Bin) -> ?WARNING_MSG("Corrupted serialized SCRAM: ~p, ~p", [Bin]), {error, corrupted_scram}. -spec scram_to_tuple(scram()) -> {binary(), binary(), binary(), non_neg_integer()}. scram_to_tuple(Scram) -> {base64:decode(Scram#scram.storedkey), base64:decode(Scram#scram.serverkey), base64:decode(Scram#scram.salt), Scram#scram.iterationcount}. -spec check_digest(scram(), binary(), fun(), binary()) -> boolean(). check_digest(#scram{storedkey = StoredKey}, Digest, DigestGen, Password) -> Passwd = base64:decode(StoredKey), DigRes = if Digest /= <<"">> -> Digest == DigestGen(Passwd); true -> false end, if DigRes -> true; true -> (Passwd == Password) and (Password /= <<"">>) end. crypto_hmac(sha, Key, Data) -> misc:crypto_hmac(sha, Key, Data). tmpcma5cyg4/ejabberd_auth_http/src/ejabberd_auth_http.erl0000644000232200023220000002610314516675355024533 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : ejabberd_auth_http.erl %%% Author : Piotr Nosek %%% Purpose : Authentication via HTTP request %%% Created : 23 Sep 2013 by Piotr Nosek %%%---------------------------------------------------------------------- -module(ejabberd_auth_http). -author('piotr.nosek@erlang-solutions.com'). -behaviour(ejabberd_auth). %% External exports -export([start/1, set_password/3, check_password/4, check_password/6, try_register/3, get_password/2, get_password_s/2, user_exists/2, remove_user/2, remove_user/3, plain_password_required/1, store_type/1, login/2, get_password/3, stop/1]). -include_lib("xmpp/include/scram.hrl"). -include("logger.hrl"). %%%---------------------------------------------------------------------- %%% API %%%---------------------------------------------------------------------- -spec start(binary()) -> ok. start(Host) -> AuthOpts = ejabberd_config:get_option({auth_opts, Host}), {_, AuthHost} = lists:keyfind(host, 1, AuthOpts), PoolSize = proplists:get_value(connection_pool_size, AuthOpts, 10), Opts = proplists:get_value(connection_opts, AuthOpts, []), ChildMods = [fusco], ChildMFA = {fusco, start_link, [binary_to_list(AuthHost), Opts]}, Proc = gen_mod:get_module_proc(Host, ?MODULE), ChildSpec = {Proc, {cuesport, start_link, [pool_name(Host), PoolSize, ChildMods, ChildMFA]}, transient, 2000, supervisor, [cuesport | ChildMods]}, supervisor:start_child(ejabberd_backend_sup, ChildSpec), ok. -spec plain_password_required(binary()) -> false. plain_password_required(_Server) -> false. -spec store_type(binary()) -> external. store_type(_) -> external. -spec check_password(binary(), binary(), binary(), binary()) -> {ets_cache:tag(), boolean()}. check_password(LUser, _AuthzId, LServer, Password) -> case scram2:enabled(LServer) of false -> case make_req(get, <<"check_password">>, LUser, LServer, Password) of {ok, <<"true">>} -> {cache, true}; _ -> {nocache, false} end; true -> case verify_scram_password(LUser, LServer, Password) of {ok, true} -> {cache, true}; _ -> {nocache, false} end end. -spec check_password(binary(), binary(), binary(), binary(), binary(), fun()) -> boolean(). check_password(LUser, _AuthzId, LServer, Password, Digest, DigestGen) -> case make_req(get, <<"get_password">>, LUser, LServer, <<"">>) of {error, _} -> false; {ok, GotPasswd} -> case scram2:enabled(LServer) of true -> case scram2:deserialize(GotPasswd) of {ok, #scram{} = Scram} -> scram2:check_digest(Scram, Digest, DigestGen, Password); _ -> false end; false -> check_digest(Digest, DigestGen, Password, GotPasswd) end end. -spec check_digest(binary(), fun(), binary(), binary()) -> boolean(). check_digest(Digest, DigestGen, Password, Passwd) -> DigRes = if Digest /= <<>> -> Digest == DigestGen(Passwd); true -> false end, if DigRes -> true; true -> (Passwd == Password) and (Password /= <<>>) end. -spec set_password(binary(), binary(), binary()) -> {ets_cache:tag(), {ok, binary()} | {error, not_allowed}}. set_password(LUser, LServer, Password) -> PasswordFinal = case scram2:enabled(LServer) of true -> scram2:serialize(scram2:password_to_scram( Password, scram2:iterations(LServer))); false -> Password end, case make_req(post, <<"set_password">>, LUser, LServer, PasswordFinal) of {error, _Error} -> {nocache, {error, not_allowed}}; {ok, _} -> {cache, {ok, Password}} end. -spec try_register(binary(), binary(), binary()) -> {ets_cache:tag(), {ok, binary()} | {error, exists | not_allowed}}. try_register(LUser, LServer, Password) -> PasswordFinal = case scram2:enabled(LServer) of true -> scram2:serialize(scram2:password_to_scram( Password, scram2:iterations(LServer))); false -> Password end, case make_req(post, <<"register">>, LUser, LServer, PasswordFinal) of {ok, <<"created">>} -> {cache, {ok, Password}}; {error, conflict} -> {nocache, {error, exists}}; _Error -> {nocache, {error, not_allowed}} end. -spec get_password(binary(), binary()) -> {cache, error}. get_password(_, _) -> {cache, error}. -spec get_password_s(binary(), binary()) -> {cache, error}. get_password_s(_User, _Server) -> {cache, error}. -spec user_exists(binary(), binary()) -> {ets_cache:tag(), boolean()}. user_exists(LUser, LServer) -> case make_req(get, <<"user_exists">>, LUser, LServer, <<"">>) of {ok, <<"true">>} -> {cache, true}; _ -> {nocache, false} end. -spec remove_user(binary(), binary()) -> ok | {error, db_failure | not_allowed}. remove_user(LUser, LServer) -> remove_user_req(LUser, LServer, <<"">>, <<"remove_user">>). -spec remove_user(binary(), binary(), binary()) -> ok | {error, db_failure | not_allowed}. remove_user(LUser, LServer, Password) -> case scram2:enabled(LServer) of false -> remove_user_req(LUser, LServer, Password, <<"remove_user_validate">>); true -> case verify_scram_password(LUser, LServer, Password) of {ok, false} -> {error, not_allowed}; {ok, true} -> remove_user_req(LUser, LServer, <<"">>, <<"remove_user">>); {error, _Error} -> {error, db_failure} end end. -spec remove_user_req(binary(), binary(), binary(), binary()) -> ok | {error, not_allowed | db_failure}. remove_user_req(LUser, LServer, Password, Method) -> case make_req(post, Method, LUser, LServer, Password) of {error, not_allowed} -> {error, not_allowed}; {error, not_found} -> {error, db_failure}; {error, _} -> {error, db_failure}; _ -> ok end. %%%---------------------------------------------------------------------- %%% Request maker %%%---------------------------------------------------------------------- -ifdef(OTP_BELOW_25). -dialyzer({no_missing_calls, [uri_quote/1]}). uri_quote(URL) -> http_uri:encode(URL). -else. uri_quote(URL) -> uri_string:quote(URL). % Available since OTP 25.0 -endif. -spec make_req(post | get, binary(), binary(), binary(), binary()) -> {ok, Body :: binary()} | {error, term()}. make_req(_, _, LUser, LServer, _) when LUser == error orelse LServer == error -> {error, {prep_failed, LUser, LServer}}; make_req(Method, Path, LUser, LServer, Password) -> AuthOpts = ejabberd_config:get_option({auth_opts, LServer}), BasicAuth = case lists:keyfind(basic_auth, 1, AuthOpts) of {_, BasicAuth0} -> BasicAuth0; _ -> "" end, PathPrefix = case lists:keyfind(path_prefix, 1, AuthOpts) of {_, Prefix} -> Prefix; false -> <<"/">> end, BasicAuth64 = base64:encode(BasicAuth), LUserE = list_to_binary(uri_quote(binary_to_list(LUser))), LServerE = list_to_binary(uri_quote(binary_to_list(LServer))), PasswordE = list_to_binary(uri_quote(binary_to_list(Password))), Query = <<"user=", LUserE/binary, "&server=", LServerE/binary, "&pass=", PasswordE/binary>>, Header = [{<<"Authorization">>, <<"Basic ", BasicAuth64/binary>>}], ContentType = {<<"Content-Type">>, <<"application/x-www-form-urlencoded">>}, Connection = cuesport:get_worker(existing_pool_name(LServer)), ?DEBUG("Making request '~s' for user ~s@~s...", [Path, LUser, LServer]), {Url, MethodStr, Headers, Query2} = case Method of get -> {<>, "GET", Header, ""}; post -> {<>, "POST", [ContentType|Header], Query} end, http_request(Connection, Url, MethodStr, Headers, Query2, 0). http_request(Connection, Url, MethodStr, Headers, Query, RedirectCounter) -> {ok, {{Code, _Reason}, RespHeaders, RespBody, _, _}} = fusco:request(Connection, Url, MethodStr, Headers, Query, 2, 5000), ?DEBUG("Request result: ~s: ~p", [Code, RespBody]), case Code of <<"409">> -> {error, conflict}; <<"404">> -> {error, not_found}; <<"401">> -> {error, not_authorized}; <<"403">> -> {error, not_allowed}; <<"400">> -> {error, RespBody}; <<"503">> -> {error, RespBody}; <<"204">> -> {ok, <<"">>}; <<"201">> -> {ok, <<"created">>}; <<"200">> -> {ok, RespBody}; R when (R==<<"301">>) or (R==<<"307">>) or (R==<<"308">>) -> handle_redirect(RespHeaders, Connection, MethodStr, Headers, Query, RedirectCounter+1); _ -> {error, RespBody} end. handle_redirect(RespHeaders, Connection, MethodStr, Headers, Query, RedirectCounter) when RedirectCounter < 5 -> {_, Location} = lists:keyfind(<<"location">>, 1, RespHeaders), http_request(Connection, Location, MethodStr, Headers, Query, RedirectCounter); handle_redirect(_, _, _, _, _, _) -> {error, redirect_loop}. %%%---------------------------------------------------------------------- %%% Other internal functions %%%---------------------------------------------------------------------- -spec pool_name(binary()) -> atom(). pool_name(Host) -> list_to_atom("ejabberd_auth_http_" ++ binary_to_list(Host)). -spec existing_pool_name(binary()) -> atom(). existing_pool_name(Host) -> list_to_existing_atom("ejabberd_auth_http_" ++ binary_to_list(Host)). -spec verify_scram_password(binary(), binary(), binary()) -> {ok, boolean()} | {error, bad_request | not_exists}. verify_scram_password(LUser, LServer, Password) -> case make_req(get, <<"get_password">>, LUser, LServer, <<"">>) of {ok, RawPassword} -> case scram2:deserialize(RawPassword) of {ok, #scram{} = ScramRecord} -> {ok, scram2:check_password(Password, ScramRecord)}; _ -> {error, bad_request} end; _ -> {error, not_exists} end. login(_User, _Server) -> erlang:error(not_implemented). get_password(_User, _Server, _DefaultValue) -> erlang:error(not_implemented). stop(Host) -> Proc = gen_mod:get_module_proc(Host, ?MODULE), supervisor:terminate_child(ejabberd_backend_sup, Proc), supervisor:delete_child(ejabberd_backend_sup, Proc). tmpcma5cyg4/ejabberd_auth_http/COPYING0000644000232200023220000004346414516675355020466 0ustar debalancedebalanceAs a special exception, the authors give permission to link this program with the OpenSSL library and distribute the resulting binary. 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. tmpcma5cyg4/mod_isolation/0000755000232200023220000000000014516675355016442 5ustar debalancedebalancetmpcma5cyg4/mod_isolation/README.md0000644000232200023220000000071614516675355017725 0ustar debalancedebalancemod_isolation: Isolate virtual hosts from each other ==================================================== The module blocks communication of users between different virtual hosts. # Configuration The module doesn't have any options, so the simplest way to configure is: ```yaml modules: mod_isolation: {} ``` Hint: if you also want to block whole s2s, use built-in ejabberd's `s2s_access` option: ```yaml s2s_access: none modules: mod_isolation: {} ``` tmpcma5cyg4/mod_isolation/conf/0000755000232200023220000000000014516675355017367 5ustar debalancedebalancetmpcma5cyg4/mod_isolation/conf/mod_isolation.yml0000644000232200023220000000013514516675355022751 0ustar debalancedebalancemodules: mod_isolation: {} ### If you want to block whole s2s as well: # s2s_access: none tmpcma5cyg4/mod_isolation/mod_isolation.spec0000644000232200023220000000040414516675355022154 0ustar debalancedebalanceauthor: "Evgeny Khramtsov " category: "policy" summary: "Prevent routing of packets between virtual hosts" home: "https://github.com/processone/ejabberd-contrib/tree/master/" url: "git@github.com:processone/ejabberd-contrib.git" tmpcma5cyg4/mod_isolation/src/0000755000232200023220000000000014516675355017231 5ustar debalancedebalancetmpcma5cyg4/mod_isolation/src/mod_isolation.erl0000644000232200023220000000511014516675355022572 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% %%% 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. %%% %%%---------------------------------------------------------------------- -module(mod_isolation). -behaviour(gen_mod). %% gen_mod callbacks -export([start/2, stop/1, reload/3, mod_options/1, depends/2, mod_doc/0, mod_status/0]). %% hooks -export([filter_packet/1]). -include_lib("xmpp/include/xmpp.hrl"). %%%=================================================================== %%% API %%%=================================================================== start(_Host, _Opts) -> ejabberd_hooks:add(filter_packet, ?MODULE, filter_packet, 50). stop(Host) -> case gen_mod:is_loaded_elsewhere(Host, ?MODULE) of false -> ejabberd_hooks:delete(filter_packet, ?MODULE, filter_packet, 50); true -> ok end. reload(_, _, _) -> ok. mod_options(_) -> []. depends(_Host, _Opts) -> []. mod_doc() -> #{}. mod_status() -> "Isolation enabled". %%%=================================================================== %%% Internal functions %%%=================================================================== filter_packet(drop) -> drop; filter_packet(Pkt) -> case xmpp:get_meta(Pkt, already_filtered, false) of true -> Pkt; false -> From = xmpp:get_from(Pkt), To = xmpp:get_to(Pkt), try {ejabberd_router:host_of_route(From#jid.lserver), ejabberd_router:host_of_route(To#jid.lserver)} of {Host, Host} -> Pkt; {_Host1, _Host2} -> Pkt1 = xmpp:put_meta(Pkt, already_filtered, true), Lang = xmpp:get_lang(Pkt), %% We already have translations for this phrase Txt = <<"Access denied by service policy">>, Err = xmpp:err_forbidden(Txt, Lang), ejabberd_router:route_error(Pkt1, Err), {stop, drop} catch _:{unregistered_route, _} -> %% This will go to s2s manager Pkt end end. tmpcma5cyg4/mod_isolation/COPYING0000644000232200023220000004346414516675355017510 0ustar debalancedebalanceAs a special exception, the authors give permission to link this program with the OpenSSL library and distribute the resulting binary. 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. tmpcma5cyg4/mod_spam_filter/0000755000232200023220000000000014516675355016746 5ustar debalancedebalancetmpcma5cyg4/mod_spam_filter/README.md0000644000232200023220000000657314516675355020240 0ustar debalancedebalancemod_spam_filter - Filter spam messages based on JID/content =========================================================== * Author: Holger Weiss Description ----------- This module allows for filtering spam messages and subscription requests received from remote servers based on lists of known spammer JIDs and/or URLs mentioned in spam messages. Traffic classified as spam is rejected with an error (and an `[info]` message is logged) unless the sender is subscribed to the recipient's presence. An access rule can be specified to control which recipients are subject to spam filtering. Configuration ------------- To enable this module, configure it like this: ```yaml modules: mod_spam_filter: spam_jids_file: "/etc/ejabberd/spam-filter/jids.txt" spam_urls_file: "/etc/ejabberd/spam-filter/urls.txt" ``` The configurable `mod_spam_filter` options are: - `spam_dump_file` (default: `none`) This option specifies the path to a file that messages classified as spam will be written to. The messages are dumped in raw XML format, and a `` tag with the current timestamp is added. The `@HOST@` keyword will be substituted with the name of the virtual host. Note that this module doesn't limit the file size, so if you use this option, make sure to monitor disk file usage and to rotate the file if necessary. After rotation, the command `ejabberdctl reopen-log` can be called to let the module reopen the spam dump file. - `spam_jids_file` (default: `none`) This option specifies the path to a plain text file containing a list of known spammer JIDs, one JID per line. Messages and subscription requests sent from one of the listed JIDs will be classified as spam. Messages containing at least one of the listed JIDs will be classified as spam as well. Furthermore, the sender's JID will be cached, so that future traffic originating from that JID will also be classified as spam. - `spam_urls_file` (default: `none`) This option specifies the path to a plain text file containing a list of URLs known to be mentioned in spam message bodies. Messages containing at least one of the listed URLs will be classified as spam. Furthermore, the sender's JID will be cached, so that future traffic originating from that JID will be classified as spam as well. - `access_spam` (default: `none`) This option defines the access rule to control who will be subject to spam filtering. If the rule returns `allow` for a given recipient, spam messages aren't rejected for that recipient. By default, all recipients are subject to spam filtering. - `cache_size` (default: `10000`) This option specifies the maximum number of JIDs that will be cached due to sending spam URLs (see above). If that limit is exceeded, the least recently used entries are removed from the cache. Setting this option to `0` disables the caching feature. Note that separate caches are used for each virtual host, and that the caches aren't distributed across cluster nodes. ejabberd Commands ----------------- This module provides ejabberdctl/API calls to reread the spam JID/URL files, to print the JID cache contents, and to remove entries from that cache. See: ``` $ ejabberdctl help reload-spam-filter-files $ ejabberdctl help get-spam-filter-cache $ ejabberdctl help expire-spam-filter-cache $ ejabberdctl help drop-from-spam-filter-cache ``` tmpcma5cyg4/mod_spam_filter/mod_spam_filter.spec0000644000232200023220000000040114516675355022761 0ustar debalancedebalanceauthor: "Holger Weiss " category: "data" summary: "Filter spam messages based on sender JID and content" home: "https://github.com/processone/ejabberd-contrib/tree/master/" url: "git@github.com:processone/ejabberd-contrib.git" tmpcma5cyg4/mod_spam_filter/conf/0000755000232200023220000000000014516675355017673 5ustar debalancedebalancetmpcma5cyg4/mod_spam_filter/conf/mod_spam_filter.yml0000644000232200023220000000004114516675355023555 0ustar debalancedebalance#modules: # mod_spam_filter: {} tmpcma5cyg4/mod_spam_filter/src/0000755000232200023220000000000014516675355017535 5ustar debalancedebalancetmpcma5cyg4/mod_spam_filter/src/mod_spam_filter.erl0000644000232200023220000006535614516675355023424 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : mod_spam_filter.erl %%% Author : Holger Weiss %%% Purpose : Filter spam messages based on sender JID and content %%% Created : 31 Mar 2019 by Holger Weiss %%% %%% %%% ejabberd, Copyright (C) 2019-2020 ProcessOne %%% %%% 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. %%% %%%---------------------------------------------------------------------- -module(mod_spam_filter). -author('holger@zedat.fu-berlin.de'). -behaviour(gen_server). -behaviour(gen_mod). %% gen_mod callbacks. -export([start/2, stop/1, reload/3, depends/2, mod_doc/0, mod_opt_type/1, mod_options/1]). %% gen_server callbacks. -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). %% ejabberd_hooks callbacks. -export([s2s_in_handle_info/2, s2s_receive_packet/1, reopen_log/0]). %% ejabberd_commands callbacks. -export([get_commands_spec/0, reload_spam_filter_files/1, get_spam_filter_cache/1, expire_spam_filter_cache/2, drop_from_spam_filter_cache/2]). -include("ejabberd_commands.hrl"). -include("logger.hrl"). -include_lib("xmpp/include/xmpp.hrl"). -define(COMMAND_TIMEOUT, timer:seconds(30)). -type url() :: binary(). -type filename() :: binary() | none. -type jid_set() :: sets:set(ljid()). -type url_set() :: sets:set(url()). -type s2s_in_state() :: ejabberd_s2s_in:state(). -record(state, {host = <<>> :: binary(), dump_fd = undefined :: file:io_device() | undefined, url_set = sets:new() :: url_set(), jid_set = sets:new() :: jid_set(), jid_cache = #{} :: map(), max_cache_size = 0 :: non_neg_integer() | unlimited}). -type state() :: #state{}. %%-------------------------------------------------------------------- %% gen_mod callbacks. %%-------------------------------------------------------------------- -spec start(binary(), gen_mod:opts()) -> ok | {error, any()}. start(Host, Opts) -> ejabberd_commands:register_commands(get_commands_spec()), gen_mod:start_child(?MODULE, Host, Opts). -spec stop(binary()) -> ok | {error, any()}. stop(Host) -> case gen_mod:is_loaded_elsewhere(Host, ?MODULE) of false -> ejabberd_commands:unregister_commands(get_commands_spec()); true -> ok end, gen_mod:stop_child(?MODULE, Host). -spec reload(binary(), gen_mod:opts(), gen_mod:opts()) -> ok. reload(Host, NewOpts, OldOpts) -> Proc = get_proc_name(Host), gen_server:cast(Proc, {reload, NewOpts, OldOpts}). -spec depends(binary(), gen_mod:opts()) -> [{module(), hard | soft}]. depends(_Host, _Opts) -> []. -spec mod_opt_type(atom()) -> econf:validator(). mod_opt_type(spam_dump_file) -> econf:either( econf:enum([none]), econf:binary()); mod_opt_type(spam_jids_file) -> econf:either( econf:enum([none]), econf:file()); mod_opt_type(spam_urls_file) -> econf:either( econf:enum([none]), econf:file()); mod_opt_type(access_spam) -> econf:acl(); mod_opt_type(cache_size) -> econf:pos_int(unlimited). -spec mod_options(binary()) -> [{atom(), any()}]. mod_options(_Host) -> [{spam_dump_file, none}, {spam_jids_file, none}, {spam_urls_file, none}, {access_spam, none}, {cache_size, 10000}]. mod_doc() -> #{}. %%-------------------------------------------------------------------- %% gen_server callbacks. %%-------------------------------------------------------------------- -spec init(list()) -> {ok, state()} | {stop, term()}. init([Host, Opts]) -> process_flag(trap_exit, true), DumpFile = expand_host(gen_mod:get_opt(spam_dump_file, Opts), Host), JIDsFile = gen_mod:get_opt(spam_jids_file, Opts), URLsFile = gen_mod:get_opt(spam_urls_file, Opts), try read_files(JIDsFile, URLsFile) of {JIDsSet, URLsSet} -> ejabberd_hooks:add(s2s_in_handle_info, Host, ?MODULE, s2s_in_handle_info, 90), ejabberd_hooks:add(s2s_receive_packet, Host, ?MODULE, s2s_receive_packet, 50), ejabberd_hooks:add(reopen_log_hook, ?MODULE, reopen_log, 50), DumpFd = if DumpFile == none -> undefined; true -> case filelib:ensure_dir(DumpFile) of ok -> ok; {error, Reason} -> Dirname = filename:dirname(DumpFile), throw({open, Dirname, Reason}) end, Modes = [append, raw, binary, delayed_write], case file:open(DumpFile, Modes) of {ok, Fd} -> Fd; {error, Reason1} -> throw({open, DumpFile, Reason1}) end end, {ok, #state{host = Host, jid_set = JIDsSet, url_set = URLsSet, dump_fd = DumpFd, max_cache_size = gen_mod:get_opt(cache_size, Opts)}} catch {Op, File, Reason} when Op == open; Op == read -> ?CRITICAL_MSG("Cannot ~s ~s: ~s", [Op, File, format_error(Reason)]), {stop, config_error} end. -spec handle_call(term(), {pid(), term()}, state()) -> {reply, {spam_filter, term()}, state()} | {noreply, state()}. handle_call({check_jid, From}, _From, #state{jid_set = JIDsSet} = State) -> {Result, State1} = filter_jid(From, JIDsSet, State), {reply, {spam_filter, Result}, State1}; handle_call({check_body, URLs, JIDs, From}, _From, #state{url_set = URLsSet, jid_set = JIDsSet} = State) -> {Result1, State1} = filter_body(URLs, URLsSet, From, State), {Result2, State2} = filter_body(JIDs, JIDsSet, From, State1), Result = if Result1 == spam -> Result1; true -> Result2 end, {reply, {spam_filter, Result}, State2}; handle_call({reload_files, JIDsFile, URLsFile}, _From, State) -> {Result, State1} = reload_files(JIDsFile, URLsFile, State), {reply, {spam_filter, Result}, State1}; handle_call({expire_cache, Age}, _From, State) -> {Result, State1} = expire_cache(Age, State), {reply, {spam_filter, Result}, State1}; handle_call({drop_from_cache, JID}, _From, State) -> {Result, State1} = drop_from_cache(JID, State), {reply, {spam_filter, Result}, State1}; handle_call(get_cache, _From, #state{jid_cache = Cache} = State) -> {reply, {spam_filter, maps:to_list(Cache)}, State}; handle_call(Request, From, State) -> ?ERROR_MSG("Got unexpected request from ~p: ~p", [From, Request]), {noreply, State}. -spec handle_cast(term(), state()) -> {noreply, state()}. handle_cast({dump, _XML}, #state{dump_fd = undefined} = State) -> {noreply, State}; handle_cast({dump, XML}, #state{dump_fd = Fd} = State) -> case file:write(Fd, [XML, <<$\n>>]) of ok -> ok; {error, Reason} -> ?ERROR_MSG("Cannot write spam to dump file: ~s", [file:format_error(Reason)]) end, {noreply, State}; handle_cast({reload, NewOpts, OldOpts}, #state{host = Host} = State) -> State1 = case {gen_mod:get_opt(spam_dump_file, OldOpts), gen_mod:get_opt(spam_dump_file, NewOpts)} of {OldDumpFile, NewDumpFile} when NewDumpFile /= OldDumpFile -> close_dump_file(expand_host(OldDumpFile, Host), State), open_dump_file(expand_host(NewDumpFile, Host), State); {_OldDumpFile, _NewDumpFile} -> State end, State2 = case {gen_mod:get_opt(cache_size, OldOpts), gen_mod:get_opt(cache_size, NewOpts)} of {OldMax, NewMax} when NewMax < OldMax -> shrink_cache(State1#state{max_cache_size = NewMax}); {OldMax, NewMax} when NewMax > OldMax -> State1#state{max_cache_size = NewMax}; {_OldMax, _NewMax} -> State1 end, JIDsFile = gen_mod:get_opt(spam_jids_file, NewOpts), URLsFile = gen_mod:get_opt(spam_urls_file, NewOpts), {_Result, State3} = reload_files(JIDsFile, URLsFile, State2), {noreply, State3}; handle_cast(reopen_log, State) -> {noreply, reopen_dump_file(State)}; handle_cast(Request, State) -> ?ERROR_MSG("Got unexpected request from: ~p", [Request]), {noreply, State}. -spec handle_info(term(), state()) -> {noreply, state()}. handle_info(Info, State) -> ?ERROR_MSG("Got unexpected info: ~p", [Info]), {noreply, State}. -spec terminate(normal | shutdown | {shutdown, term()} | term(), state()) -> ok. terminate(Reason, #state{host = Host} = State) -> ?DEBUG("Stopping spam filter process for ~s: ~p", [Host, Reason]), DumpFile = gen_mod:get_module_opt(Host, ?MODULE, spam_dump_file), DumpFile1 = expand_host(DumpFile, Host), close_dump_file(DumpFile1, State), ejabberd_hooks:delete(s2s_receive_packet, Host, ?MODULE, s2s_receive_packet, 50), ejabberd_hooks:delete(s2s_in_handle_info, Host, ?MODULE, s2s_in_handle_info, 90), case gen_mod:is_loaded_elsewhere(Host, ?MODULE) of false -> ejabberd_hooks:delete(reopen_log_hook, ?MODULE, reopen_log, 50); true -> ok end. -spec code_change({down, term()} | term(), state(), term()) -> {ok, state()}. code_change(_OldVsn, #state{host = Host} = State, _Extra) -> ?DEBUG("Updating spam filter process for ~s", [Host]), {ok, State}. %%-------------------------------------------------------------------- %% Hook callbacks. %%-------------------------------------------------------------------- -spec s2s_receive_packet({stanza() | drop, s2s_in_state()}) -> {stanza(), s2s_in_state()} | {stop, {drop, s2s_in_state()}}. s2s_receive_packet({drop, _State} = Acc) -> Acc; s2s_receive_packet({#message{from = From, to = #jid{lserver = LServer} = To, type = Type, body = Body} = Msg, State} = Acc) when Type /= groupchat, Type /= error -> case needs_checking(From, To) of true -> case check_from(LServer, From) of ham -> case check_body(LServer, From, xmpp:get_text(Body)) of ham -> Acc; spam -> reject(Msg), {drop, State} end; spam -> reject(Msg), {drop, State} end; false -> Acc end; s2s_receive_packet({#presence{from = From, to = #jid{lserver = LServer} = To, type = subscribe} = Presence, State} = Acc) -> case needs_checking(From, To) of true -> case check_from(LServer, From) of ham -> Acc; spam -> reject(Presence), {drop, State} end; false -> Acc end; s2s_receive_packet({_Stanza, _State} = Acc) -> Acc. -spec s2s_in_handle_info(s2s_in_state(), any()) -> s2s_in_state() | {stop, s2s_in_state()}. s2s_in_handle_info(State, {_Ref, {spam_filter, _}}) -> ?DEBUG("Dropping expired spam filter result", []), {stop, State}; s2s_in_handle_info(State, _) -> State. -spec reopen_log() -> ok. reopen_log() -> lists:foreach(fun(Host) -> Proc = get_proc_name(Host), gen_server:cast(Proc, reopen_log) end, get_spam_filter_hosts()). %%-------------------------------------------------------------------- %% Internal functions. %%-------------------------------------------------------------------- -spec needs_checking(jid(), jid()) -> boolean(). needs_checking(From, #jid{lserver = LServer} = To) -> case gen_mod:is_loaded(LServer, ?MODULE) of true -> Access = gen_mod:get_module_opt(LServer, ?MODULE, access_spam), case acl:match_rule(LServer, Access, To) of allow -> ?DEBUG("Spam not filtered for ~s", [jid:encode(To)]), false; deny -> ?DEBUG("Spam is filtered for ~s", [jid:encode(To)]), not mod_roster:is_subscribed(From, To) end; false -> ?DEBUG("~s not loaded for ~s", [?MODULE, LServer]), false end. -spec check_from(binary(), jid()) -> ham | spam. check_from(Host, From) -> Proc = get_proc_name(Host), LFrom = jid:remove_resource(jid:tolower(From)), try gen_server:call(Proc, {check_jid, LFrom}) of {spam_filter, Result} -> Result catch exit:{timeout, _} -> ?WARNING_MSG("Timeout while checking ~s against list of spammers", [jid:encode(From)]), ham end. -spec check_body(binary(), jid(), binary()) -> ham | spam. check_body(Host, From, Body) -> case {extract_urls(Body), extract_jids(Body)} of {none, none} -> ?DEBUG("No JIDs/URLs found in message", []), ham; {URLs, JIDs} -> Proc = get_proc_name(Host), LFrom = jid:remove_resource(jid:tolower(From)), try gen_server:call(Proc, {check_body, URLs, JIDs, LFrom}) of {spam_filter, Result} -> Result catch exit:{timeout, _} -> ?WARNING_MSG("Timeout while checking body", []), ham end end. -spec extract_urls(binary()) -> {urls, [url()]} | none. extract_urls(Body) -> RE = <<"https?://\\S+">>, Options = [global, {capture, all, binary}], case re:run(Body, RE, Options) of {match, Captured} when is_list(Captured) -> {urls, lists:flatten(Captured)}; nomatch -> none end. -spec extract_jids(binary()) -> {jids, [ljid()]} | none. extract_jids(Body) -> RE = <<"\\S+@\\S+">>, Options = [global, {capture, all, binary}], case re:run(Body, RE, Options) of {match, Captured} when is_list(Captured) -> {jids, lists:filtermap(fun try_decode_jid/1, lists:flatten(Captured))}; nomatch -> none end. -spec try_decode_jid(binary()) -> {true, ljid()} | false. try_decode_jid(S) -> try jid:decode(S) of #jid{} = JID -> {true, jid:remove_resource(jid:tolower(JID))} catch _:{bad_jid, _} -> false end. -spec filter_jid(ljid(), jid_set(), state()) -> {ham | spam, state()}. filter_jid(From, Set, State) -> case sets:is_element(From, Set) of true -> ?DEBUG("Spam JID found: ~s", [jid:encode(From)]), {spam, State}; false -> case cache_lookup(From, State) of {true, State1} -> ?DEBUG("Spam JID found: ~s", [jid:encode(From)]), {spam, State1}; {false, State1} -> ?DEBUG("JID not listed: ~s", [jid:encode(From)]), {ham, State1} end end. -spec filter_body({urls, [url()]} | {jids, [ljid()]} | none, url_set() | jid_set(), jid(), state()) -> {ham | spam, state()}. filter_body({_, Addrs}, Set, From, State) -> case lists:any(fun(Addr) -> sets:is_element(Addr, Set) end, Addrs) of true -> ?DEBUG("Spam addresses found: ~p", [Addrs]), {spam, cache_insert(From, State)}; false -> ?DEBUG("Addresses not listed: ~p", [Addrs]), {ham, State} end; filter_body(none, _Set, _From, State) -> {ham, State}. -spec reload_files(filename(), filename(), state()) -> {ok | {error, binary()}, state()}. reload_files(JIDsFile, URLsFile, #state{host = Host} = State) -> try read_files(JIDsFile, URLsFile) of {JIDsSet, URLsSet} -> case sets_equal(JIDsSet, State#state.jid_set) of true -> ?INFO_MSG("Reloaded spam JIDs for ~s (unchanged)", [Host]); false -> ?INFO_MSG("Reloaded spam JIDs for ~s (changed)", [Host]) end, case sets_equal(URLsSet, State#state.url_set) of true -> ?INFO_MSG("Reloaded spam URLs for ~s (unchanged)", [Host]); false -> ?INFO_MSG("Reloaded spam URLs for ~s (changed)", [Host]) end, {ok, State#state{jid_set = JIDsSet, url_set = URLsSet}} catch {Op, File, Reason} when Op == open; Op == read -> Txt = format("Cannot ~s ~s for ~s: ~s", [Op, File, Host, format_error(Reason)]), ?ERROR_MSG("~s", [Txt]), {{error, Txt}, State} end. -spec read_files(filename(), filename()) -> {jid_set(), url_set()}. read_files(JIDsFile, URLsFile) -> {read_file(JIDsFile, fun parse_jid/1), read_file(URLsFile, fun parse_url/1)}. -spec read_file(filename(), fun((binary()) -> ljid() | url())) -> jid_set() | url_set(). read_file(none, _ParseLine) -> sets:new(); read_file(File, ParseLine) -> case file:open(File, [read, binary, raw, {read_ahead, 65536}]) of {ok, Fd} -> try read_line(Fd, ParseLine, sets:new()) catch throw:E -> throw({read, File, E}) after ok = file:close(Fd) end; {error, Reason} -> throw({open, File, Reason}) end. -spec read_line(file:io_device(), fun((binary()) -> ljid() | url()), jid_set() | url_set()) -> jid_set() | url_set(). read_line(Fd, ParseLine, Set) -> case file:read_line(Fd) of {ok, Line} -> read_line(Fd, ParseLine, sets:add_element(ParseLine(Line), Set)); {error, Reason} -> throw(Reason); eof -> Set end. -spec parse_jid(binary()) -> ljid(). parse_jid(S) -> try jid:decode(trim(S)) of #jid{} = JID -> jid:remove_resource(jid:tolower(JID)) catch _:{bad_jid, _} -> throw({bad_jid, S}) end. -spec parse_url(binary()) -> url(). parse_url(S) -> URL = trim(S), RE = <<"https?://\\S+$">>, Options = [anchored, caseless, {capture, none}], case re:run(URL, RE, Options) of match -> URL; nomatch -> throw({bad_url, S}) end. -spec trim(binary()) -> binary(). trim(S) -> re:replace(S, <<"\\s+$">>, <<>>, [{return, binary}]). -spec reject(stanza()) -> ok. reject(#message{from = From, to = To, type = Type, lang = Lang} = Msg) when Type /= groupchat, Type /= error -> ?INFO_MSG("Rejecting unsolicited message from ~s to ~s", [jid:encode(From), jid:encode(To)]), Txt = <<"Your message is unsolicited">>, Err = xmpp:err_policy_violation(Txt, Lang), maybe_dump_spam(Msg), ejabberd_router:route_error(Msg, Err); reject(#presence{from = From, to = To, lang = Lang} = Presence) -> ?INFO_MSG("Rejecting unsolicited presence from ~s to ~s", [jid:encode(From), jid:encode(To)]), Txt = <<"Your traffic is unsolicited">>, Err = xmpp:err_policy_violation(Txt, Lang), ejabberd_router:route_error(Presence, Err); reject(_) -> ok. -spec open_dump_file(filename(), state()) -> state(). open_dump_file(none, State) -> State#state{dump_fd = undefined}; open_dump_file(Name, State) -> Modes = [append, raw, binary, delayed_write], case file:open(Name, Modes) of {ok, Fd} -> ?DEBUG("Opened ~s", [Name]), State#state{dump_fd = Fd}; {error, Reason} -> ?ERROR_MSG("Cannot open ~s: ~s", [Name, file:format_error(Reason)]), State#state{dump_fd = undefined} end. -spec close_dump_file(filename(), state()) -> ok. close_dump_file(_Name, #state{dump_fd = undefined}) -> ok; close_dump_file(Name, #state{dump_fd = Fd}) -> case file:close(Fd) of ok -> ?DEBUG("Closed ~s", [Name]); {error, Reason} -> ?ERROR_MSG("Cannot close ~s: ~s", [Name, file:format_error(Reason)]) end. -spec reopen_dump_file(state()) -> state(). reopen_dump_file(#state{host = Host} = State) -> DumpFile = gen_mod:get_module_opt(Host, ?MODULE, spam_dump_file), DumpFile1 = expand_host(DumpFile, Host), close_dump_file(DumpFile1, State), open_dump_file(DumpFile1, State). -spec maybe_dump_spam(message()) -> ok. maybe_dump_spam(#message{to = #jid{lserver = LServer}} = Msg) -> By = jid:make(<<>>, LServer), Proc = get_proc_name(LServer), Time = erlang:timestamp(), Msg1 = misc:add_delay_info(Msg, By, Time), XML = fxml:element_to_binary(xmpp:encode(Msg1)), gen_server:cast(Proc, {dump, XML}). -spec get_proc_name(binary()) -> atom(). get_proc_name(Host) -> gen_mod:get_module_proc(Host, ?MODULE). -spec get_spam_filter_hosts() -> [binary()]. get_spam_filter_hosts() -> [H || H <- ejabberd_option:hosts(), gen_mod:is_loaded(H, ?MODULE)]. -spec expand_host(binary() | none, binary()) -> binary() | none. expand_host(none, _Host) -> none; expand_host(Input, Host) -> misc:expand_keyword(<<"@HOST@">>, Input, Host). -spec sets_equal(sets:set(), sets:set()) -> boolean(). sets_equal(A, B) -> sets:is_subset(A, B) andalso sets:is_subset(B, A). -spec format(io:format(), [term()]) -> binary(). format(Format, Data) -> iolist_to_binary(io_lib:format(Format, Data)). -spec format_error(atom() | tuple()) -> binary(). format_error({bad_jid, JID}) -> <<"Not a valid JID: ", JID/binary>>; format_error({bad_url, URL}) -> <<"Not an HTTP(S) URL: ", URL/binary>>; format_error(Reason) -> list_to_binary(file:format_error(Reason)). %%-------------------------------------------------------------------- %% Caching. %%-------------------------------------------------------------------- -spec cache_insert(ljid(), state()) -> state(). cache_insert(_LJID, #state{max_cache_size = 0} = State) -> State; cache_insert(LJID, #state{jid_cache = Cache, max_cache_size = MaxSize} = State) when MaxSize /= unlimited, map_size(Cache) >= MaxSize -> cache_insert(LJID, shrink_cache(State)); cache_insert(LJID, #state{jid_cache = Cache} = State) -> ?INFO_MSG("Caching spam JID: ~s", [jid:encode(LJID)]), Cache1 = Cache#{LJID => erlang:monotonic_time(second)}, State#state{jid_cache = Cache1}. -spec cache_lookup(ljid(), state()) -> {boolean(), state()}. cache_lookup(LJID, #state{jid_cache = Cache} = State) -> case Cache of #{LJID := _Timestamp} -> Cache1 = Cache#{LJID => erlang:monotonic_time(second)}, State1 = State#state{jid_cache = Cache1}, {true, State1}; #{} -> {false, State} end. -spec shrink_cache(state()) -> state(). shrink_cache(#state{jid_cache = Cache, max_cache_size = MaxSize} = State) -> ShrinkedSize = round(MaxSize / 2), N = map_size(Cache) - ShrinkedSize, L = lists:keysort(2, maps:to_list(Cache)), Cache1 = maps:from_list(lists:nthtail(N, L)), State#state{jid_cache = Cache1}. -spec expire_cache(integer(), state()) -> {{ok, binary()}, state()}. expire_cache(Age, #state{jid_cache = Cache} = State) -> Threshold = erlang:monotonic_time(second) - Age, Cache1 = maps:filter(fun(_, TS) -> TS >= Threshold end, Cache), NumExp = map_size(Cache) - map_size(Cache1), Txt = format("Expired ~B cache entries", [NumExp]), {{ok, Txt}, State#state{jid_cache = Cache1}}. -spec drop_from_cache(ljid(), state()) -> {{ok, binary()}, state()}. drop_from_cache(LJID, #state{jid_cache = Cache} = State) -> Cache1 = maps:remove(LJID, Cache), if map_size(Cache1) < map_size(Cache) -> Txt = format("~s removed from cache", [jid:encode(LJID)]), {{ok, Txt}, State#state{jid_cache = Cache1}}; true -> Txt = format("~s wasn't cached", [jid:encode(LJID)]), {{ok, Txt}, State} end. %%-------------------------------------------------------------------- %% ejabberd command callbacks. %%-------------------------------------------------------------------- -spec get_commands_spec() -> [ejabberd_commands()]. get_commands_spec() -> [#ejabberd_commands{name = reload_spam_filter_files, tags = [filter], desc = "Reload spam JID/URL files", module = ?MODULE, function = reload_spam_filter_files, args = [{host, binary}], result = {res, rescode}}, #ejabberd_commands{name = get_spam_filter_cache, tags = [filter], desc = "Show spam filter cache contents", module = ?MODULE, function = get_spam_filter_cache, args = [{host, binary}], result = {spammers, {list, {spammer, {tuple, [{jid, string}, {timestamp, integer}]}}}}}, #ejabberd_commands{name = expire_spam_filter_cache, tags = [filter], desc = "Remove old/unused spam JIDs from cache", module = ?MODULE, function = expire_spam_filter_cache, args = [{host, binary}, {seconds, integer}], result = {res, restuple}}, #ejabberd_commands{name = drop_from_spam_filter_cache, tags = [filter], desc = "Drop JID from spam filter cache", module = ?MODULE, function = drop_from_spam_filter_cache, args = [{host, binary}, {jid, binary}], result = {res, restuple}}]. -spec reload_spam_filter_files(binary()) -> ok | {error, string()}. reload_spam_filter_files(<<"global">>) -> try lists:foreach(fun(Host) -> ok = reload_spam_filter_files(Host) end, get_spam_filter_hosts()) catch error:{badmatch, {error, _Reason} = Error} -> Error end; reload_spam_filter_files(Host) -> LServer = jid:nameprep(Host), case {gen_mod:get_module_opt(LServer, ?MODULE, spam_jids_file), gen_mod:get_module_opt(LServer, ?MODULE, spam_urls_file)} of {JIDsFile, URLsFile} -> Proc = get_proc_name(LServer), try gen_server:call(Proc, {reload_files, JIDsFile, URLsFile}, ?COMMAND_TIMEOUT) of {spam_filter, ok} -> ok; {spam_filter, {error, Txt}} -> {error, binary_to_list(Txt)} catch exit:{noproc, _} -> {error, "Not configured for " ++ binary_to_list(Host)}; exit:{timeout, _} -> {error, "Timeout while querying ejabberd"} end end. -spec get_spam_filter_cache(binary()) -> [{binary(), integer()}] | {error, string()}. get_spam_filter_cache(Host) -> LServer = jid:nameprep(Host), Proc = get_proc_name(LServer), try gen_server:call(Proc, get_cache, ?COMMAND_TIMEOUT) of {spam_filter, Cache} -> [{jid:encode(JID), TS + erlang:time_offset(second)} || {JID, TS} <- Cache] catch exit:{noproc, _} -> {error, "Not configured for " ++ binary_to_list(Host)}; exit:{timeout, _} -> {error, "Timeout while querying ejabberd"} end. -spec expire_spam_filter_cache(binary(), integer()) -> {ok | error, string()}. expire_spam_filter_cache(<<"global">>, Age) -> try lists:foreach(fun(Host) -> {ok, _} = expire_spam_filter_cache(Host, Age) end, get_spam_filter_hosts()) of ok -> {ok, "Expired cache entries"} catch error:{badmatch, {error, _Reason} = Error} -> Error end; expire_spam_filter_cache(Host, Age) -> LServer = jid:nameprep(Host), Proc = get_proc_name(LServer), try gen_server:call(Proc, {expire_cache, Age}, ?COMMAND_TIMEOUT) of {spam_filter, {Status, Txt}} -> {Status, binary_to_list(Txt)} catch exit:{noproc, _} -> {error, "Not configured for " ++ binary_to_list(Host)}; exit:{timeout, _} -> {error, "Timeout while querying ejabberd"} end. -spec drop_from_spam_filter_cache(binary(), binary()) -> {ok | error, string()}. drop_from_spam_filter_cache(<<"global">>, JID) -> try lists:foreach(fun(Host) -> {ok, _} = drop_from_spam_filter_cache(Host, JID) end, get_spam_filter_hosts()) of ok -> {ok, "Dropped " ++ binary_to_list(JID) ++ " from caches"} catch error:{badmatch, {error, _Reason} = Error} -> Error end; drop_from_spam_filter_cache(Host, EncJID) -> LServer = jid:nameprep(Host), Proc = get_proc_name(LServer), try jid:decode(EncJID) of #jid{} = JID -> LJID = jid:remove_resource(jid:tolower(JID)), try gen_server:call(Proc, {drop_from_cache, LJID}, ?COMMAND_TIMEOUT) of {spam_filter, {Status, Txt}} -> {Status, binary_to_list(Txt)} catch exit:{noproc, _} -> {error, "Not configured for " ++ binary_to_list(Host)}; exit:{timeout, _} -> {error, "Timeout while querying ejabberd"} end catch _:{bad_jid, _} -> {error, "Not a valid JID: " ++ binary_to_list(EncJID)} end. tmpcma5cyg4/mod_spam_filter/COPYING0000644000232200023220000004346414516675355020014 0ustar debalancedebalanceAs a special exception, the authors give permission to link this program with the OpenSSL library and distribute the resulting binary. 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. tmpcma5cyg4/mod_cron/0000755000232200023220000000000014516675355015402 5ustar debalancedebalancetmpcma5cyg4/mod_cron/README.md0000644000232200023220000001134514516675355016665 0ustar debalancedebalancemod_cron - Execute scheduled tasks ================================== * Requires: ejabberd 19.08 or higher * http://www.ejabberd.im/mod_cron * Author: Badlop This module allows advanced ejabberd administrators to schedule tasks for periodic and automatic execution. This module is a similar concept than the Unix's cron program. Each time a scheduled task finishes its execution, a message is printed in the ejabberd log file. Basic Configuration ------------------- Add the module to the `modules` section on the configuration file: ```yaml modules: mod_cron: {} ``` Then, using the `tasks` option, you can add a list of tasks. For each task there are options to define _when_ to run it, and options to define _what_ to run. When ---- Those options determine when a task is ran: * `time: integer()` * `units: seconds | minutes | hours | days` Indicates the time unit to use. * `timer_type: interval | fixed` Default value is `interval`. Fixed timers occur at a fixed time after the [minute|hour|day] e.g. every hour on the 5th minute (1:05PM, 2:05PM etc). Interval timers occur every interval (starting on an even unit) e.g. every 10 minutes starting at 1PM, 1:10PM, 1:20PM etc. Fixed timers are the equivalent of unix cron's comma syntax e.g. `"2 * * *"` and interval timers are the `/` syntax e.g. `"*/5 * * *"`. What ---- You can define a task to run some ejabberd API (either in command or in ctl syntax), or any arbitrary erlang function. ### Command Use the option `command` and provide `arguments` in the correct format: ```yaml command: delete_old_mam_messages arguments: - "all" - 0 ``` This requires a recent ejabberd version that includes [this commit](https://github.com/processone/ejabberd/commit/10481ed895016893ee9dc3fe23cd937fdc46ded6), and `api_permissions` configured to allow mod_cron, for example: ```yaml api_permissions: "console commands": from: - ejabberd_ctl - mod_cron who: all what: "*" ``` ### Ctl Use the option `ctl` and provide all `arguments` with quotes: ```yaml ctl: delete_old_mam_messages arguments: - "all" - "0" ``` ### Erlang Function Use `module`, `function`, and provide `arguments` in the correct format: ```yaml module: ejabberd_auth function: try_register arguments: - "user1" - "localhost" - "somepass" ``` Please note the arguments in string format will be converted to binaries. If the function expects strings, you can add the option `args_type: string`: ```yaml module: mnesia function: backup args_type: string arguments: - "/var/log/ejabberd/mnesia.backup" ``` Example Tasks ------------- Those example tasks show how to specify arguments in the basic erlang formats: ```yaml modules: mod_cron: tasks: - time: 30 units: seconds module: erlang function: is_integer arguments: - 123456 - time: 31 units: seconds module: erlang function: is_float arguments: - 123.456 - time: 32 units: seconds module: erlang function: is_atom arguments: - 'this_is_atom' - time: 33 units: seconds module: erlang function: is_atom arguments: - this_is_atom_too - time: 34 units: seconds module: erlang function: is_binary arguments: - "Keep this as a binary" - time: 35 units: seconds module: erlang function: is_list args_type: string arguments: - "Convert this as a string" ``` It is even possible to pass an argument that is a list of elements, see: ```yaml modules: mod_cron: tasks: - time: 36 units: seconds module: io function: format args_type: string arguments: - "log message, integer: ~p, float: ~p, atom: ~p, binary: ~p~n~n" - - 12345678 - 123.456 - atom_this_is - "this is a binary" ``` If you don't need to provide arguments at all, you can remove `arguments`, or provide it with an empty list: ```yaml modules: mod_cron: tasks: - time: 10 units: seconds command: connected_users - time: 15 units: seconds ctl: delete_expired_pubsub_items - time: 20 units: seconds module: mod_pubsub function: delete_expired_items arguments: [] ``` ejabberd Commands ----------------- This module provides two new commands that can be executed using ejabberdctl: * cron_list: list scheduled tasks * cron_del taskid: delete this task from the schedule Web Admin --------- This module provides a page in the Host section of the Web Admin. Currently that page only allows to view the tasks scheduled for that host. tmpcma5cyg4/mod_cron/ChangeLog0000644000232200023220000000146014516675355017155 0ustar debalancedebalance2009-06-09 Badlop * src/mod_cron.erl: Fix paths (thanks to Bman) 2008-10-12 Badlop * src/mod_cron.erl: Update from ctl to commands (EJAB-694) 2008-07-29 Badlop * src/mod_cron.erl: Fix call to ejabberd_hooks:delete 2007-12-26 Badlop * src/mod_cron.erl: Translate menu items of webadmin hooks in each module (EJAB-485) 2007-08-31 Badlop * src/mod_cron.erl (web_page_host): Small improvement on page format. 2007-08-23 Badlop * src/mod_cron.erl: Added page in Web Admin; currently only tasks view is possible. * README.txt: Idem. 2007-08-05 Badlop * ChangeLog: New file to track changes. * src/mod_cron.erl: Fixed indentation. tmpcma5cyg4/mod_cron/conf/0000755000232200023220000000000014516675355016327 5ustar debalancedebalancetmpcma5cyg4/mod_cron/conf/mod_cron.yml0000644000232200023220000000003214516675355020645 0ustar debalancedebalance#modules: # mod_cron: {} tmpcma5cyg4/mod_cron/src/0000755000232200023220000000000014516675355016171 5ustar debalancedebalancetmpcma5cyg4/mod_cron/src/mod_cron.erl0000644000232200023220000002372214516675355020503 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : mod_cron.erl %%% Author : Badlop %%% Purpose : Execute scheduled tasks %%% Created : 12 July 2007 %%% Id : $Id: mod_cron.erl 1034 2009-11-17 21:44:17Z badlop $ %%%---------------------------------------------------------------------- -module(mod_cron). -author('badlop@ono.com'). -behaviour(gen_mod). -export([start/2, stop/1, depends/2, mod_options/1, mod_opt_type/1, mod_doc/0]). -export([cron_list/1, cron_del/1, run_task/3, web_menu_host/3, web_page_host/3, apply_interval/3, apply_interval1/3]). -include("ejabberd_commands.hrl"). -include("ejabberd_http.hrl"). -include("ejabberd_web_admin.hrl"). -include("logger.hrl"). -include("translate.hrl"). -include_lib("xmpp/include/xmpp.hrl"). -record(task, {taskid, timerref, host, task}). %% --------------------- %% gen_mod %% --------------------- start(Host, Opts) -> ejabberd_commands:register_commands(commands()), ejabberd_hooks:add(webadmin_menu_host, Host, ?MODULE, web_menu_host, 50), ejabberd_hooks:add(webadmin_page_host, Host, ?MODULE, web_page_host, 50), Tasks = gen_mod:get_opt(tasks, Opts), catch ets:new(cron_tasks, [ordered_set, named_table, public, {keypos, 2}]), [add_task(Host, Task) || Task <- Tasks], ok. stop(Host) -> ejabberd_commands:unregister_commands(commands()), ejabberd_hooks:delete(webadmin_menu_host, Host, ?MODULE, web_menu_host, 50), ejabberd_hooks:delete(webadmin_page_host, Host, ?MODULE, web_page_host, 50), %% Delete tasks of this host [delete_task(Task) || Task <- get_tasks(Host)], ok. depends(_Host, _Opts) -> []. mod_opt_type(tasks) -> econf:list(econf:any()). mod_options(_Host) -> [{tasks, []}]. mod_doc() -> #{}. %% --------------------- %% Task management %% --------------------- time_to_ms(IntervalUnit, IntervalNum) -> case IntervalUnit of seconds -> timer:seconds(IntervalNum); minutes -> timer:minutes(IntervalNum); hours -> timer:hours(IntervalNum); days -> timer:hours(IntervalNum)*24 end. time_until_event(IntervalMS) -> NowMS = p1_time_compat:system_time(micro_seconds), MSSinceLastEvent = (NowMS rem IntervalMS), (IntervalMS - MSSinceLastEvent). begin_interval_timer(TaskId, TimeUnit, TimeNum, StartParams) -> IntervalMS = time_to_ms(TimeUnit, TimeNum), MSToGo = time_until_event(IntervalMS), {ok, TimerRef} = timer:apply_after(MSToGo, ?MODULE, apply_interval, [TaskId, IntervalMS, StartParams]), TimerRef. begin_fixed_timer(TaskId, TimeUnit, TimeNum, StartParams) -> %% A fixed second timer happens minutely, minute timer happens hourly, a fixed hour timer happens daily. IntervalMS = case TimeUnit of seconds -> timer:minutes(1); minutes -> timer:hours(1); hours -> timer:hours(1) * 24; _ -> undefined end, FixedTimeMS = time_to_ms(TimeUnit, TimeNum), %% Calculate time until the next IntervalUnit, then add FixedTimeMS %% e.g. now is 00:00:32 wait until the next minute (28s), then keep waiting %% 5 more seconds to get 00:01:05 (= wait 33s). %% We then fire the event at 00:01:05 and wait a minute to fire again %% at 00:02:05 etc. MSToGo1 = time_until_event(IntervalMS) + FixedTimeMS, %% If we were, for example, at 1:03PM and the event is hourly at %% 1:05PM then we dont want to wait 57+5 minutes, we want to wait %% 2 minutes. MSToGo2 = if MSToGo1 > IntervalMS -> MSToGo1 - IntervalMS; true -> MSToGo1 end, ?DEBUG("MS To Go Fixed: ~p ~p", [MSToGo1, MSToGo2]), {ok, TimerRef} = timer:apply_after(MSToGo2, ?MODULE, apply_interval, [TaskId, IntervalMS, StartParams]), TimerRef. apply_interval(TaskId, IntervalMS, StartParams) -> %% apply_after doesnt belong to a pid (which is needed for apply_after to stay alive), so make one spawn(?MODULE, apply_interval1, [TaskId, IntervalMS, StartParams]). apply_interval1(TaskId, IntervalMS, [M, F, A]=StartParams) -> % we've already waited for the interval to expire once to get here, % and apply_interval doesn't apply first, so run the task once then start the timer run_task(M, F, A), {ok, TimerRef} = timer:apply_interval(IntervalMS, ?MODULE, run_task, StartParams), update_timer_ref(TaskId, TimerRef), %% Wait forever so the timer process stays alive receive _ -> ok end. update_timer_ref(TaskId, NewTimerRef) -> [Task] = ets:lookup(cron_tasks, TaskId), NewTask = Task#task{timerref=NewTimerRef}, ets:insert(cron_tasks, NewTask). %% Method to add new task add_task(Host, Task) -> [TimeNum, TimeUnit, Mod1, Fun1, ArgsType, Args1, InTimerType, Command, Ctl] = [proplists:get_value(Key, Task) || Key <- [time, units, module, function, args_type, arguments, timer_type, command, ctl]], TimerType = case InTimerType of <<"fixed">> -> fixed; fixed -> fixed; _ -> interval end, %% Get new task identifier TaskId = get_new_taskid(), Args2 = parse_args_type(ArgsType, Args1), {Mod, Fun, Args} = prepare_mfa(Mod1, Fun1, Args2, Command, Ctl), TimerRef = case TimerType of interval -> begin_interval_timer(TaskId, TimeUnit, TimeNum, [Mod, Fun, Args]); fixed -> begin_fixed_timer(TaskId, TimeUnit, TimeNum, [Mod, Fun, Args]) end, %% Store TRef Taskr = #task{ taskid = TaskId, timerref = TimerRef, host = Host, task = Task }, ets:insert(cron_tasks, Taskr). get_new_taskid() -> case ets:last(cron_tasks) of '$end_of_table' -> 0; Id -> Id + 1 end. parse_args_type(_, undefined) -> []; parse_args_type(string, Args) -> lists:map(fun(Arg) when is_binary(Arg) -> binary_to_list(Arg); (Arg) -> Arg end, Args); parse_args_type(_, Args) -> Args. parse_args_ctl(Ctl, Args2) -> [[atom_to_list(Ctl) | Args2]]. parse_args_command(Command, Args2) -> CI = #{caller_module => ?MODULE}, [Command, Args2, CI]. prepare_mfa(undefined, undefined, Args2, Command, undefined) when Command /= undefined -> {ejabberd_commands, execute_command2, parse_args_command(Command, Args2)}; prepare_mfa(undefined, undefined, Args2, undefined, Ctl) when Ctl /= undefined -> {ejabberd_ctl, process, parse_args_ctl(Ctl, parse_args_type(string, Args2))}; prepare_mfa(Mod1, Fun1, Args2, undefined, undefined) -> {Mod1, Fun1, Args2}. %% Method to run existing task run_task(Mod, Fun, Args) -> case catch apply(Mod, Fun, Args) of {'EXIT', Reason} -> ?ERROR_MSG("Error in scheduled task ~p:~p~p:~n~p", [Mod, Fun, Args, Reason]); {error, Reason} -> ?ERROR_MSG("Error in scheduled task ~p:~p~p:~n~p", [Mod, Fun, Args, Reason]); ok -> ?INFO_MSG("Scheduled task ~p:~p~p finished ok", [Mod, Fun, Args]); Res -> ?INFO_MSG("Scheduled task ~p:~p~p returned:~n~p", [Mod, Fun, Args, Res]) end. %% Method to delete task, given a taskid delete_taskid(TaskId) -> [Task] = ets:lookup(cron_tasks, TaskId), delete_task(Task). %% Method to delete task, given the whole task delete_task(Task) -> timer:cancel(Task#task.timerref), ets:delete(cron_tasks, Task#task.taskid). %% Method to know existing tasks on a given host get_tasks(Host) -> ets:select(cron_tasks, [{#task{host = Host, _ = '_'}, [], ['$_']}]). %% Method to know taskids of existing tasks on a given host %%get_tasks_ids(Host) -> %% L = ets:match(cron_tasks, #task{host = Host, taskid = '$1', _ = '_'}), %% [Id || [Id] <- L]. %% --------------------- %% ejabberd commands %% --------------------- commands() -> [ #ejabberd_commands{name = cron_list, tags = [cron], desc = "List tasks scheduled in a host", module = ?MODULE, function = cron_list, args = [{host, binary}], result = {tasks, {list, {task, {tuple, [{id, integer}, {task, string}]}}}}}, #ejabberd_commands{name = cron_del, tags = [cron], desc = "Delete this task from the schedule", module = ?MODULE, function = cron_del, args = [{taskid, integer}], result = {res, rescode}} ]. cron_list(Host) -> Tasks = get_tasks(Host), [{T#task.taskid, io_lib:format("~p", [T#task.task])} || T <- Tasks]. cron_del(TaskId) -> delete_taskid(TaskId), ok. %% --------------------- %% Web Admin %% --------------------- web_menu_host(Acc, _Host, Lang) -> [{<<"cron">>, translate:translate(Lang, ?T("Cron Tasks"))} | Acc]. web_page_host(_, Host, #request{path = [<<"cron">>], lang = Lang} = _Request) -> Tasks = get_tasks(Host), Tasks_table = make_tasks_table(Tasks, Lang), Res = [?XC(<<"h1">>, <<"Cron Tasks">>)] ++ Tasks_table, {stop, Res}; web_page_host(Acc, _, _) -> Acc. make_tasks_table(Tasks, Lang) -> TList = lists:map( fun(T) -> [TimeNum, TimeUnit, Mod, Fun, Args, InTimerType] = [proplists:get_value(Key, T#task.task) || Key <- [time, units, module, function, arguments, timer_type]], ?XE(<<"tr">>, [?XC(<<"td">>, list_to_binary(integer_to_list(TimeNum)++" " ++atom_to_list(TimeUnit)++" " ++atom_to_list(InTimerType))), ?XC(<<"td">>, list_to_binary(atom_to_list(Mod))), ?XC(<<"td">>, list_to_binary(atom_to_list(Fun))), ?XC(<<"td">>, list_to_binary(io_lib:format("~p", [Args])))]) end, Tasks), [?XE(<<"table">>, [?XE(<<"thead">>, [?XE(<<"tr">>, [?XCT(<<"td">>, <<"Periodicity">>), ?XCT(<<"td">>, <<"Module">>), ?XCT(<<"td">>, <<"Function">>), ?XCT(<<"td">>, <<"Arguments">>)])]), ?XE(<<"tbody">>, TList)])]. tmpcma5cyg4/mod_cron/mod_cron.spec0000644000232200023220000000033714516675355020061 0ustar debalancedebalanceauthor: "Badlop " category: "admin" summary: "Execute scheduled commands" home: "https://github.com/processone/ejabberd-contrib/tree/master/" url: "git@github.com:processone/ejabberd-contrib.git" tmpcma5cyg4/mod_cron/COPYING0000644000232200023220000004332414516675355016443 0ustar debalancedebalanceAs a special exception, the authors give permission to link this program with the OpenSSL library and distribute the resulting binary. GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. tmpcma5cyg4/mod_statsdx/0000755000232200023220000000000014516675355016133 5ustar debalancedebalancetmpcma5cyg4/mod_statsdx/README.md0000644000232200023220000000430414516675355017413 0ustar debalancedebalancemod_statsdx - Calculates and gathers statistics actively ======================================================== * Requires: ejabberd 19.08 or higher * Homepage: http://www.ejabberd.im/mod_statsdx * Author: Badlop Measures several statistics. It provides a new section in ejabberd Web Admin and two ejabberd commands to view the information. Configuration ------------- Configurable options: - `hooks` Set to `true` to enable hooks and related statistics. This option by default `false` because it is expected to consume many resources in very populated servers. If set to `traffic`, it will also keep counters of traffic stanzas. Example Configuration --------------------- To start using the module, simply enable it: ```yaml modules: mod_statsdx: {} ``` To enable the `hooks` option: ```yaml modules: mod_statsdx: hooks: true ``` Feature Requests ---------------- - fix the problem with plain/ssl/tlsusers, it crashes ejabberd - traffic: send bytes per second, received bps - connections to a transport - traffic: send presence per second, received mps - Number of SASL c2s connections - improve to work in distributed server mod_stats2file ============== Generates files with all kind of statistics This module writes a file with all kind of statistics every few minutes. Available output formats are html (example), text file with descriptions and raw text file (for MRTG, RRDTool...). Configuration ------------- This module requires `mod_statsdx`. Configurable options: - `interval`: Time between updates, in minutes (default: `5`) - `type`: Type of output. Allowed values: `html`, `txt`, `dat` (default: `html`) - `basefilename`: Base filename including absolute path (default: `"/tmp/ejasta"`) - `split`: If split the statistics in several files (default: `false`) - `hosts`: List of virtual hosts that will be checked. By default `all` Example Configuration --------------------- The module can be simply enabled, accepting the default options configuration: ```yaml modules: mod_stats2file: {} ``` Or set some options: ```yaml modules: mod_stats2file: interval: 60 type: txt split: true basefilename: "/var/www/stats" hosts: ["localhost", "server3.com"] ``` tmpcma5cyg4/mod_statsdx/mod_statsdx.spec0000644000232200023220000000035714516675355021345 0ustar debalancedebalanceauthor: "Badlop " category: "stats" summary: "Calculates and gathers statistics actively" home: "https://github.com/processone/ejabberd-contrib/tree/master/" url: "git@github.com:processone/ejabberd-contrib.git" tmpcma5cyg4/mod_statsdx/ChangeLog0000644000232200023220000000350014516675355017703 0ustar debalancedebalance2009-11-24 Badlop * src/mod_statsdx.erl: Add getstatsdx ejabberd commands. 2009-02-04 Badlop * src/mod_statsdx.erl: Fix a few stats 2009-02-03 Badlop * src/mod_statsdx.erl: New configuration {hooks, traffic}. In addition to hooks for client versions, in this case also tracks stanza traffic. Show in WebAdmin of the virtual host. * README.txt: Document traffic hooks 2009-02-02 Badlop * src/mod_statsdx.erl: New stats for erlang memory. Show new stats in node page. Show big integers with separation for easy reading. 2008-09-16 Badlop * src/mod_statsdx.erl: Fixed code indentation and trailing-whitespace. Catch table creation. Improved hooks feature. Remove the unused hook webadmin_user. Disable code for traffic stats and don't show empty section 'Ratios' in webadmin. Create an ETS table for the whole server, and a table for each vhost. Add subpages in WebAdmin to view filtered sessions. 2008-09-03 Badlop * src/mod_statsdx.erl: If client answers with unexpected response, forget stanza instead of crashing. * src/mod_statsdx.erl: The option 'hooks' in mod_statsdx is disabled by default. * README.txt: Likewise * README.txt: Several cosmetic changes. 2007-12-26 Badlop * src/mod_statsdx.erl: Translate menu items of webadmin hooks in each module (EJAB-485) 2007-08-31 Badlop * src/mod_statsdx.erl: Added pages to Web Admin. Apply Emacs-mode indentation. * src/ejabberd_web_admin.erl: No need to patch core web admin file. * Emakefile: Idem. 2007-08-21 Badlop * src/*.erl: Removed authusers statistic. * src/*.erl: Fixed credits. * ChangeLog: New file to track changes. tmpcma5cyg4/mod_statsdx/conf/0000755000232200023220000000000014516675355017060 5ustar debalancedebalancetmpcma5cyg4/mod_statsdx/conf/mod_statsdx.yml0000644000232200023220000000007214516675355022133 0ustar debalancedebalancemodules: mod_statsdx: hooks: false # hooks: true tmpcma5cyg4/mod_statsdx/src/0000755000232200023220000000000014516675355016722 5ustar debalancedebalancetmpcma5cyg4/mod_statsdx/src/mod_statsdx.erl0000644000232200023220000020063714516675355021767 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : mod_statsdx.erl %%% Author : Badlop %%% Purpose : Calculates and gathers statistics actively %%% Created : %%% Id : $Id: mod_statsdx.erl 1118 2011-07-11 17:16:30Z badlop $ %%%---------------------------------------------------------------------- %%%% Definitions -module(mod_statsdx). -author('badlop@ono.com'). -behaviour(gen_mod). -export([start/2, stop/1, depends/2, mod_opt_type/1, mod_options/1, mod_doc/0, mod_status/0]). -export([loop/1, get_statistic/2, pre_uninstall/0, received_response/3, received_response/7, %% Commands getstatsdx/1, getstatsdx/2, get_top_users/2, %% WebAdmin web_menu_main/2, web_page_main/2, web_menu_node/3, web_page_node/5, web_menu_host/3, web_page_host/3, web_user/4, %% Hooks register_user/2, remove_user/2, %user_send_packet/1, user_send_packet_traffic/1, user_receive_packet_traffic/1, %%user_logout_sm/3, request_iqversion/4, user_login/1, user_logout/2]). -include("ejabberd_commands.hrl"). -include_lib("xmpp/include/xmpp.hrl"). -include("logger.hrl"). -include("mod_roster.hrl"). -include("ejabberd_http.hrl"). -include("ejabberd_web_admin.hrl"). -include("translate.hrl"). -define(XCTB(Name, Text), ?XCT(list_to_binary(Name), list_to_binary(Text))). -define(PROCNAME, ejabberd_mod_statsdx). %% Copied from ejabberd_s2s.erl Used in function get_s2sconnections/1 -record(s2s, {fromto :: {binary(), binary()}, pid :: pid()}). %%%================================== %%%% Module control start(Host, Opts) -> Hooks = gen_mod:get_opt(hooks, Opts), %% Default value for the counters CD = case Hooks of true -> 0; traffic -> 0; false -> "disabled" end, ejabberd_commands:register_commands(commands()), %% If the process that handles statistics for the server is not started yet, %% start it now case whereis(?PROCNAME) of undefined -> application:start(os_mon), initialize_stats_server(); _ -> ok end, ?PROCNAME ! {initialize_stats, Host, Hooks, CD}, ok. stop(Host) -> finish_stats(Host), ejabberd_commands:unregister_commands(commands()), case whereis(?PROCNAME) of undefined -> ok; _ -> ?PROCNAME ! {stop, Host} end. pre_uninstall() -> [{code:purge(M), code:delete(M)} || M <- [mod_stats2file]]. depends(_Host, _Opts) -> []. mod_opt_type(hooks) -> econf:enum([false, true, traffic]); mod_opt_type(sessionlog) -> econf:string(). mod_options(_Host) -> [{hooks, false}, {sessionlog, "/tmp/ejabberd_logsession_@HOST@.log"}]. mod_doc() -> #{}. mod_status() -> "Pages 'Statistics Dx' available in WebAdmin, your Virtual Hosts and your Nodes". %%%================================== %%%% Stats Server %%% +++ TODO: why server and "server" table_name(server) -> gen_mod:get_module_proc(<<"server">>, mod_statsdx); table_name("server") -> gen_mod:get_module_proc(<<"server">>, mod_statsdx); table_name(Host) -> gen_mod:get_module_proc(tob(Host), mod_statsdx). tob(A) when is_atom(A) -> A; tob(B) when is_binary(B) -> B; tob(L) when is_list(L) -> list_to_binary(L). initialize_stats_server() -> register(?PROCNAME, spawn(?MODULE, loop, [[]])). loop(Hosts) -> receive {initialize_stats, Host, Hooks, CD} -> case Hosts of [] -> prepare_stats_server(CD); _ -> ok end, prepare_stats_host(Host, Hooks, CD), loop([Host | Hosts]); {stop, Host} -> case Hosts -- [Host] of [] -> finish_stats(); RemainingHosts -> loop(RemainingHosts) end end. %% Si no existe una tabla de stats del server, crearla. %% Deberia ser creada por un proceso que solo muera cuando se detenga el ultimo mod_statsdx del servidor prepare_stats_server(CD) -> Table = table_name(server), ets:new(Table, [named_table, public]), ets:insert(Table, {{user_login, server}, CD}), ets:insert(Table, {{user_logout, server}, CD}), ets:insert(Table, {{register_user, server}, CD}), ets:insert(Table, {{remove_user, server}, CD}), lists:foreach( fun(E) -> ets:insert(Table, {{client, server, E}, CD}) end, list_elem(clients, id) ), lists:foreach( fun(E) -> ets:insert(Table, {{conntype, server, E}, CD}) end, list_elem(conntypes, id) ), lists:foreach( fun(E) -> ets:insert(Table, {{os, server, E}, CD}) end, list_elem(oss, id) ), ejabberd_hooks:add(webadmin_menu_main, ?MODULE, web_menu_main, 50), ejabberd_hooks:add(webadmin_menu_node, ?MODULE, web_menu_node, 50), ejabberd_hooks:add(webadmin_page_main, ?MODULE, web_page_main, 50), ejabberd_hooks:add(webadmin_page_node, ?MODULE, web_page_node, 50). prepare_stats_host(Host, Hooks, CD) -> Table = table_name(Host), ets:new(Table, [named_table, public]), ets:insert(Table, {{user_login, Host}, CD}), ets:insert(Table, {{user_logout, Host}, CD}), ets:insert(Table, {{register_user, Host}, CD}), ets:insert(Table, {{remove_user, Host}, CD}), ets:insert(Table, {{send, Host, iq, in}, CD}), ets:insert(Table, {{send, Host, iq, out}, CD}), ets:insert(Table, {{send, Host, message, in}, CD}), ets:insert(Table, {{send, Host, message, out}, CD}), ets:insert(Table, {{send, Host, presence, in}, CD}), ets:insert(Table, {{send, Host, presence, out}, CD}), ets:insert(Table, {{recv, Host, iq, in}, CD}), ets:insert(Table, {{recv, Host, iq, out}, CD}), ets:insert(Table, {{recv, Host, message, in}, CD}), ets:insert(Table, {{recv, Host, message, out}, CD}), ets:insert(Table, {{recv, Host, presence, in}, CD}), ets:insert(Table, {{recv, Host, presence, out}, CD}), lists:foreach( fun(E) -> ets:insert(Table, {{client, Host, E}, CD}) end, list_elem(clients, id) ), lists:foreach( fun(E) -> ets:insert(Table, {{conntype, Host, E}, CD}) end, list_elem(conntypes, id) ), lists:foreach( fun(E) -> ets:insert(Table, {{os, Host, E}, CD}) end, list_elem(oss, id) ), case Hooks of true -> ejabberd_hooks:add(register_user, Host, ?MODULE, register_user, 90), ejabberd_hooks:add(remove_user, Host, ?MODULE, remove_user, 90), ejabberd_hooks:add(c2s_session_opened, Host, ?MODULE, user_login, 90), ejabberd_hooks:add(c2s_closed, Host, ?MODULE, user_logout, 40); %%ejabberd_hooks:add(sm_remove_connection_hook, Host, ?MODULE, user_logout_sm, 90), %ejabberd_hooks:add(user_send_packet, Host, ?MODULE, user_send_packet, 90); traffic -> ejabberd_hooks:add(user_receive_packet, Host, ?MODULE, user_receive_packet_traffic, 92), ejabberd_hooks:add(user_send_packet, Host, ?MODULE, user_send_packet_traffic, 92), ejabberd_hooks:add(register_user, Host, ?MODULE, register_user, 90), ejabberd_hooks:add(remove_user, Host, ?MODULE, remove_user, 90), ejabberd_hooks:add(c2s_session_opened, Host, ?MODULE, user_login, 90), ejabberd_hooks:add(c2s_closed, Host, ?MODULE, user_logout, 40); %%ejabberd_hooks:add(sm_remove_connection_hook, Host, ?MODULE, user_logout_sm, 90), %ejabberd_hooks:add(user_send_packet, Host, ?MODULE, user_send_packet, 90); false -> ok end, ejabberd_hooks:add(webadmin_user, Host, ?MODULE, web_user, 50), ejabberd_hooks:add(webadmin_menu_host, Host, ?MODULE, web_menu_host, 50), ejabberd_hooks:add(webadmin_page_host, Host, ?MODULE, web_page_host, 50). finish_stats() -> ejabberd_hooks:delete(webadmin_menu_main, ?MODULE, web_menu_main, 50), ejabberd_hooks:delete(webadmin_menu_node, ?MODULE, web_menu_node, 50), ejabberd_hooks:delete(webadmin_page_main, ?MODULE, web_page_main, 50), ejabberd_hooks:delete(webadmin_page_node, ?MODULE, web_page_node, 50), Table = table_name(server), catch ets:delete(Table). finish_stats(Host) -> ejabberd_hooks:delete(c2s_session_opened, Host, ?MODULE, user_login, 90), ejabberd_hooks:delete(c2s_closed, Host, ?MODULE, user_logout, 40), %%ejabberd_hooks:delete(sm_remove_connection_hook, Host, ?MODULE, user_logout_sm, 90), %ejabberd_hooks:delete(user_send_packet, Host, ?MODULE, user_send_packet, 90), ejabberd_hooks:delete(user_send_packet, Host, ?MODULE, user_send_packet_traffic, 92), ejabberd_hooks:delete(user_receive_packet, Host, ?MODULE, user_receive_packet_traffic, 92), ejabberd_hooks:delete(register_user, Host, ?MODULE, register_user, 90), ejabberd_hooks:delete(remove_user, Host, ?MODULE, remove_user, 90), ejabberd_hooks:delete(webadmin_user, Host, ?MODULE, web_user, 50), ejabberd_hooks:delete(webadmin_menu_host, Host, ?MODULE, web_menu_host, 50), ejabberd_hooks:delete(webadmin_page_host, Host, ?MODULE, web_page_host, 50), Table = table_name(Host), catch ets:delete(Table). %%%================================== %%%% Hooks Handlers register_user(_User, Host) -> TableHost = table_name(Host), TableServer = table_name(server), ets:update_counter(TableHost, {register_user, Host}, 1), ets:update_counter(TableServer, {register_user, server}, 1). remove_user(_User, Host) -> TableHost = table_name(Host), TableServer = table_name(server), ets:update_counter(TableHost, {remove_user, Host}, 1), ets:update_counter(TableServer, {remove_user, server}, 1). %%user_send_packet({NewEl, C2SState}) -> %% FromJID = xmpp:get_from(NewEl), %% ToJID = xmpp:get_from(NewEl), %% %% Registrarse para tramitar Host/mod_stats2file %% case catch binary_to_existing_atom(ToJID#jid.lresource, utf8) of %% ?MODULE -> %% ok; %received_response(FromJID, ToJID, NewEl); %% _ -> %% ok %% end, %% {NewEl, C2SState}. %% Only required for traffic stats user_send_packet_traffic({NewEl, _C2SState} = Acc) -> From = xmpp:get_from(NewEl), To = xmpp:get_to(NewEl), Host = From#jid.lserver, HostTo = To#jid.lserver, Type2 = case NewEl of #iq{} -> iq; #message{} -> message; #presence{} -> presence end, Dest = case is_host(HostTo, Host) of true -> in; false -> out end, Table = table_name(Host), ets:update_counter(Table, {send, tob(Host), Type2, Dest}, 1), Acc. %% Only required for traffic stats user_receive_packet_traffic({NewEl, _C2SState} = Acc) -> From = xmpp:get_from(NewEl), To = xmpp:get_to(NewEl), HostFrom = From#jid.lserver, Host = To#jid.lserver, Type2 = case NewEl of #iq{} -> iq; #message{} -> message; #presence{} -> presence end, Dest = case is_host(HostFrom, Host) of true -> in; false -> out end, Table = table_name(Host), ets:update_counter(Table, {recv, tob(Host), Type2, Dest}, 1), Acc. %%%================================== %%%% get(* %%gett(Arg) -> get(node(), [Arg, title]). getl(Args) -> get(node(), [Args]). getl(Args, Host) -> get(node(), [Args, Host]). %%get(_Node, ["", title]) -> ""; get_statistic(N, A) -> case catch get(N, A) of {'EXIT', R} -> ?ERROR_MSG("get_statistic error for N: ~p, A: ~p~n~p", [N, A, R]), unknown; Res -> Res end. get(global, A) -> get(node(), A); get(_, [{"reductions", _}, title]) -> "Reductions (per minute)"; get(_, [{"reductions", I}]) -> calc_avg(element(2, statistics(reductions)), I); %+++ get(_, ["cpu_avg1", title]) -> "Average system load (1 min)"; get(N, ["cpu_avg1"]) -> rpc:call(N, cpu_sup, avg1, [])/256; get(_, ["cpu_avg5", title]) -> "Average system load (5 min)"; get(N, ["cpu_avg5"]) -> rpc:call(N, cpu_sup, avg1, [])/256; get(_, ["cpu_avg15", title]) -> "Average system load (15 min)"; get(N, ["cpu_avg15"]) -> rpc:call(N, cpu_sup, avg15, [])/256; get(_, ["cpu_nprocs", title]) -> "Number of UNIX processes running on this machine"; get(N, ["cpu_nprocs"]) -> rpc:call(N, cpu_sup, nprocs, []); get(_, ["cpu_util", title]) -> "CPU utilization"; get(N, ["cpu_util"]) -> rpc:call(N, cpu_sup, util, []); get(_, [{"cpu_util_user", _}, title]) -> "CPU utilization - user"; get(_, [{"cpu_util_nice_user", _}, title]) -> "CPU utilization - nice_user"; get(_, [{"cpu_util_kernel", _}, title]) -> "CPU utilization - kernel"; get(_, [{"cpu_util_wait", _}, title]) -> "CPU utilization - wait"; get(_, [{"cpu_util_idle", _}, title]) -> "CPU utilization - idle"; get(_, [{"cpu_util_user", U}]) -> U; get(_, [{"cpu_util_nice_user", U}]) -> U; get(_, [{"cpu_util_kernel", U}]) -> U; get(_, [{"cpu_util_wait", U}]) -> U; get(_, [{"cpu_util_idle", U}]) -> U; get(_, [{"client", Id}, title]) -> atom_to_list(Id); get(_, [{"client", Id}, Host]) -> Table = table_name(Host), case ets:lookup(Table, {client, tob(Host), Id}) of [{_, C}] -> C; [] -> 0 end; get(_, ["client", title]) -> "Client"; get(N, ["client", Host]) -> lists:map( fun(Id) -> [Id_string] = io_lib:format("~p", [Id]), {Id_string, get(N, [{"client", Id}, Host])} end, lists:usort(list_elem(clients, id)) ); get(_, [{"os", Id}, title]) -> atom_to_list(Id); get(_, [{"os", _Id}, list]) -> lists:usort(list_elem(oss, id)); get(_, [{"os", Id}, Host]) -> [{_, C}] = ets:lookup(table_name(Host), {os, tob(Host), Id}), C; get(_, ["os", title]) -> "Operating System"; get(N, ["os", Host]) -> lists:map( fun(Id) -> [Id_string] = io_lib:format("~p", [Id]), {Id_string, get(N, [{"os", Id}, Host])} end, lists:usort(list_elem(oss, id)) ); get(_, [{"conntype", Id}, title]) -> atom_to_list(Id); get(_, [{"conntype", _Id}, list]) -> lists:usort(list_elem(conntypes, id)); get(_, [{"conntype", Id}, Host]) -> [{_, C}] = ets:lookup(table_name(Host), {conntype, Host, Id}), C; get(_, ["conntype", title]) -> "Connection Type"; get(N, ["conntype", Host]) -> lists:map( fun(Id) -> [Id_string] = io_lib:format("~p", [Id]), {Id_string, get(N, [{"conntype", Id}, Host])} end, lists:usort(list_elem(conntypes, id)) ); get(_, [{"memsup_system", _}, title]) -> "Memory physical (bytes)"; get(_, [{"memsup_system", M}]) -> proplists:get_value(system_total_memory, M, -1); get(_, [{"memsup_free", _}, title]) -> "Memory free (bytes)"; get(_, [{"memsup_free", M}]) -> proplists:get_value(free_memory, M, -1); get(_, [{"user_login", _}, title]) -> "Logins (per minute)"; get(_, [{"user_login", I}, Host]) -> get_stat({user_login, tob(Host)}, I); get(_, [{"user_logout", _}, title]) -> "Logouts (per minute)"; get(_, [{"user_logout", I}, Host]) -> get_stat({user_logout, tob(Host)}, I); get(_, [{"register_user", _}, title]) -> "Accounts registered (per minute)"; get(_, [{"register_user", I}, Host]) -> get_stat({register_user, tob(Host)}, I); get(_, [{"remove_user", _}, title]) -> "Accounts deleted (per minute)"; get(_, [{"remove_user", I}, Host]) -> get_stat({remove_user, tob(Host)}, I); get(_, [{Table, Type, Dest, _}, title]) -> filename:flatten([Table, Type, Dest]); get(_, [{Table, Type, Dest, I}, Host]) -> get_stat({Table, tob(Host), Type, Dest}, I); get(_, ["user_login", title]) -> "Logins"; get(_, ["user_login", Host]) -> get_stat({user_login, Host}); get(_, ["user_logout", title]) -> "Logouts"; get(_, ["user_logout", Host]) -> get_stat({user_logout, Host}); get(_, ["register_user", title]) -> "Accounts registered"; get(_, ["register_user", Host]) -> get_stat({register_user, Host}); get(_, ["remove_user", title]) -> "Accounts deleted"; get(_, ["remove_user", Host]) -> get_stat({remove_user, Host}); get(_, [{Table, Type, Dest}, title]) -> filename:flatten([Table, Type, Dest]); get(_, [{Table, Type, Dest}, Host]) -> get_stat({Table, tob(Host), Type, Dest}); get(_, ["localtime", title]) -> "Local time"; get(N, ["localtime"]) -> localtime_to_string(rpc:call(N, erlang, localtime, [])); get(_, ["memory_total", title]) -> "Memory total allocated: processes and system"; get(N, ["memory_total"]) -> rpc:call(N, erlang, memory, [total]); get(_, ["memory_processes", title]) -> "Memory allocated by Erlang processes"; get(N, ["memory_processes"]) -> rpc:call(N, erlang, memory, [processes]); get(_, ["memory_processes_used", title]) -> "Memory used by Erlang processes"; get(N, ["memory_processes_used"]) -> rpc:call(N, erlang, memory, [processes_used]); get(_, ["memory_system", title]) -> "Memory allocated by Erlang emulator but not associated to processes"; get(N, ["memory_system"]) -> rpc:call(N, erlang, memory, [system]); get(_, ["memory_atom", title]) -> "Memory allocated for atoms"; get(N, ["memory_atom"]) -> rpc:call(N, erlang, memory, [atom]); get(_, ["memory_atom_used", title]) -> "Memory used for atoms"; get(N, ["memory_atom_used"]) -> rpc:call(N, erlang, memory, [atom_used]); get(_, ["memory_binary", title]) -> "Memory allocated for binaries"; get(N, ["memory_binary"]) -> rpc:call(N, erlang, memory, [binary]); get(_, ["memory_code", title]) -> "Memory allocated for Erlang code"; get(N, ["memory_code"]) -> rpc:call(N, erlang, memory, [code]); get(_, ["memory_ets", title]) -> "Memory allocated for ETS tables"; get(N, ["memory_ets"]) -> rpc:call(N, erlang, memory, [ets]); get(_, ["vhost", title]) -> "Virtual host"; get(_, ["vhost", Host]) -> Host; get(_, ["ejabberdversion", title]) -> "ejabberd version"; get(N, ["ejabberdversion"]) -> element(2, rpc:call(N, application, get_key, [ejabberd, vsn])); get(_, ["totalerlproc", title]) -> "Total Erlang processes running"; get(N, ["totalerlproc"]) -> rpc:call(N, erlang, system_info, [process_count]); get(_, ["operatingsystem", title]) -> "Operating System"; get(N, ["operatingsystem"]) -> {rpc:call(N, os, type, []), rpc:call(N, os, version, [])}; get(_, ["erlangmachine", title]) -> "Erlang machine"; get(N, ["erlangmachine"]) -> rpc:call(N, erlang, system_info, [system_version]); get(_, ["erlangmachinetarget", title]) -> "Erlang machine target"; get(N, ["erlangmachinetarget"]) -> rpc:call(N, erlang, system_info, [system_architecture]); get(_, ["maxprocallowed", title]) -> "Maximum processes allowed"; get(N, ["maxprocallowed"]) -> rpc:call(N, erlang, system_info, [process_limit]); get(_, ["procqueue", title]) -> "Number of processes on the running queue"; get(N, ["procqueue"]) -> rpc:call(N, erlang, statistics, [run_queue]); get(_, ["uptimehuman", title]) -> "Uptime"; get(N, ["uptimehuman"]) -> io_lib:format("~w days ~w hours ~w minutes ~p seconds", ms_to_time(get(N, ["uptime"]))); get(_, ["lastrestart", title]) -> "Last restart"; get(N, ["lastrestart"]) -> Now = calendar:datetime_to_gregorian_seconds(rpc:call(N, erlang, localtime, [])), UptimeMS = get(N, ["uptime"]), Last_restartS = trunc(Now - (UptimeMS/1000)), Last_restart = calendar:gregorian_seconds_to_datetime(Last_restartS), localtime_to_string(Last_restart); get(_, ["plainusers", title]) -> "Plain users"; get(_, ["plainusers"]) -> {R, _, _} = get_connectiontype(), R; get(_, ["tlsusers", title]) -> "TLS users"; get(_, ["tlsusers"]) -> {_, R, _} = get_connectiontype(), R; get(_, ["sslusers", title]) -> "SSL users"; get(_, ["sslusers"]) -> {_, _, R} = get_connectiontype(), R; get(_, ["registeredusers", title]) -> "Registered users"; get(N, ["registeredusers"]) -> rpc:call(N, mnesia, table_info, [passwd, size]); get(_, ["registeredusers", Host]) -> ejabberd_auth:count_users(Host); get(_, ["onlineusers", title]) -> "Online users"; get(N, ["onlineusers"]) -> rpc:call(N, mnesia, table_info, [session, size]); get(_, ["onlineusers", Host]) -> length(ejabberd_sm:get_vh_session_list(Host)); get(_, ["httpbindusers", title]) -> "HTTP-Bind users (aprox)"; get(N, ["httpbindusers"]) -> rpc:call(N, mnesia, table_info, [http_bind, size]); get(_, ["s2sconnectionsoutgoing", title]) -> "Outgoing S2S connections"; get(_, ["s2sconnectionsoutgoing"]) -> ejabberd_s2s:outgoing_s2s_number(); get(_, ["s2sconnectionsincoming", title]) -> "Incoming S2S connections"; get(_, ["s2sconnectionsincoming"]) -> ejabberd_s2s:incoming_s2s_number(); get(_, ["s2sconnections", title]) -> "S2S connections"; get(_, ["s2sconnections"]) -> length(get_S2SConns()); get(_, ["s2sconnections", Host]) -> get_s2sconnections(Host); get(_, ["s2sservers", title]) -> "S2S servers"; get(_, ["s2sservers"]) -> length(lists:usort([element(2, C) || C <- get_S2SConns()])); get(_, ["offlinemsg", title]) -> "Offline messages"; get(N, ["offlinemsg"]) -> rpc:call(N, mnesia, table_info, [offline_msg, size]); get(_, ["offlinemsg", Host]) -> get_offlinemsg(Host); get(_, ["totalrosteritems", title]) -> "Total roster items"; get(N, ["totalrosteritems"]) -> rpc:call(N, mnesia, table_info, [roster, size]); get(_, ["totalrosteritems", Host]) -> get_totalrosteritems(Host); get(_, ["meanitemsinroster", title]) -> "Mean items in roster"; get(_, ["meanitemsinroster"]) -> get_meanitemsinroster(); get(_, ["meanitemsinroster", Host]) -> get_meanitemsinroster(Host); get(_, ["totalmucrooms", title]) -> "Total MUC rooms"; get(_, ["totalmucrooms"]) -> ets:info(muc_online_room, size); get(_, ["totalmucrooms", Host]) -> get_totalmucrooms(Host); get(_, ["permmucrooms", title]) -> "Permanent MUC rooms"; get(N, ["permmucrooms"]) -> rpc:call(N, mnesia, table_info, [muc_room, size]); get(_, ["permmucrooms", Host]) -> get_permmucrooms(Host); get(_, ["regmucrooms", title]) -> "Users registered at MUC service"; get(N, ["regmucrooms"]) -> rpc:call(N, mnesia, table_info, [muc_registered, size]); get(_, ["regmucrooms", Host]) -> get_regmucrooms(Host); get(_, ["regpubsubnodes", title]) -> "Registered nodes at Pub/Sub"; get(N, ["regpubsubnodes"]) -> rpc:call(N, mnesia, table_info, [pubsub_node, size]); get(_, ["vcards", title]) -> "Total vCards published"; get(N, ["vcards"]) -> rpc:call(N, mnesia, table_info, [vcard, size]); get(_, ["vcards", Host]) -> get_vcards(Host); %%get(_, ["ircconns", title]) -> "IRC connections"; %%get(_, ["ircconns"]) -> ets:info(irc_connection, size); %%get(_, ["ircconns", Host]) -> get_irccons(Host); % This seems to crash for some people get(_, ["uptime", title]) -> "Uptime"; get(N, ["uptime"]) -> element(1, rpc:call(N, erlang, statistics, [wall_clock])); get(_, ["cputime", title]) -> "CPU Time"; get(N, ["cputime"]) -> element(1, rpc:call(N, erlang, statistics, [runtime])); get(_, ["languages", title]) -> "Languages"; get(_, ["languages", Server]) -> get_languages(Server); get(_, ["client_os", title]) -> "Client/OS"; get(_, ["client_os", Server]) -> get_client_os(Server); get(_, ["client_conntype", title]) -> "Client/Connection Type"; get(_, ["client_conntype", Server]) -> get_client_conntype(Server); get(N, A) -> io:format(" ----- node: '~p', A: '~p'~n", [N, A]), "666". %%%================================== %%%% get_* get_S2SConns() -> ejabberd_s2s:dirty_get_connections(). get_tls_drv() -> R = lists:filter( fun(P) -> case erlang:port_info(P, name) of {name, "tls_drv"} -> true; _ -> false end end, erlang:ports()), length(R). get_connections(Port) -> R = lists:filter( fun(P) -> case inet:port(P) of {ok, Port} -> true; _ -> false end end, erlang:ports()), length(R). get_totalrosteritems(Host) -> F = fun() -> F2 = fun(R, {H, A}) -> {_LUser, LServer, _LJID} = R#roster.usj, A2 = case LServer of H -> A+1; _ -> A end, {H, A2} end, mnesia:foldl(F2, {Host, 0}, roster) end, {atomic, {Host, Res}} = mnesia:transaction(F), Res. %% Copied from ejabberd_sm.erl %%-record(session, {sid, usr, us, priority}). %%get_authusers(Host) -> %% F = fun() -> %% F2 = fun(R, {H, A}) -> %% {_LUser, LServer, _LResource} = R#session.usr, %% A2 = case LServer of %% H -> A+1; %% _ -> A %% end, %% {H, A2} %% end, %% mnesia:foldl(F2, {Host, 0}, session) %% end, %% {atomic, {Host, Res}} = mnesia:transaction(F), %% Res. -record(offline_msg, {us, timestamp, expire, from, to, packet}). get_offlinemsg(Host) -> F = fun() -> F2 = fun(R, {H, A}) -> {_LUser, LServer} = R#offline_msg.us, A2 = case LServer of H -> A+1; _ -> A end, {H, A2} end, mnesia:foldl(F2, {Host, 0}, offline_msg) end, {atomic, {Host, Res}} = mnesia:transaction(F), Res. -record(vcard, {us, vcard}). get_vcards(Host) -> F = fun() -> F2 = fun(R, {H, A}) -> {_LUser, LServer} = R#vcard.us, A2 = case LServer of H -> A+1; _ -> A end, {H, A2} end, mnesia:foldl(F2, {Host, 0}, vcard) end, {atomic, {Host, Res}} = mnesia:transaction(F), Res. get_s2sconnections(Host) -> F = fun() -> F2 = fun(R, {H, A}) -> {MyServer, _Server} = R#s2s.fromto, A2 = case MyServer of H -> A+1; _ -> A end, {H, A2} end, mnesia:foldl(F2, {Host, 0}, s2s) end, {atomic, {Host, Res}} = mnesia:transaction(F), Res. %%-record(irc_connection, {jid_server_host, pid}). %%get_irccons(Host) -> %% F2 = fun(R, {H, A}) -> %% {From, _Server, _Host} = R#irc_connection.jid_server_host, %% A2 = case From#jid.lserver of %% H -> A+1; %% _ -> A %% end, %% {H, A2} %% end, %% {Host, Res} = ets:foldl(F2, {Host, 0}, irc_connection), %% Res. is_host(HostBin, SubhostBin) -> case catch binary:split(HostBin, SubhostBin) of [_Sub, <<"">>] -> true; _ -> false end. -record(muc_online_room, {name_host, pid}). get_totalmucrooms(Host) -> F2 = fun(R, {H, A}) -> {_Name, MUCHost} = R#muc_online_room.name_host, A2 = case is_host(MUCHost, H) of true -> A+1; false -> A end, {H, A2} end, {Host, Res} = ets:foldl(F2, {Host, 0}, muc_online_room), Res. -record(muc_room, {name_host, opts}). get_permmucrooms(Host) -> F = fun() -> F2 = fun(R, {H, A}) -> {_Name, MUCHost} = R#muc_room.name_host, A2 = case is_host(MUCHost, H) of true -> A+1; false -> A end, {H, A2} end, mnesia:foldl(F2, {Host, 0}, muc_room) end, {atomic, {Host, Res}} = mnesia:transaction(F), Res. -record(muc_registered, {us_host, nick}). get_regmucrooms(Host) -> F = fun() -> F2 = fun(R, {H, A}) -> {_User, MUCHost} = R#muc_registered.us_host, A2 = case is_host(MUCHost, H) of true -> A+1; false -> A end, {H, A2} end, mnesia:foldl(F2, {Host, 0}, muc_registered) end, {atomic, {Host, Res}} = mnesia:transaction(F), Res. get_stat(Stat) -> Host = case Stat of {_, H} -> H; {_, H, _, _} -> H end, Table = table_name(Host), Res = ets:lookup(Table, Stat), [{_, C}] = Res, C. get_stat(Stat, Ims) -> Host = case Stat of {_, H} -> H; {_, H, _, _} -> H end, Table = table_name(Host), Res = ets:lookup(Table, Stat), ets:update_counter(Table, Stat, {2,1,0,0}), [{_, C}] = Res, calc_avg(C, Ims). %%C. calc_avg(Count, TimeMS) -> TimeMIN = TimeMS/(1000*60), Count/TimeMIN. %%%================================== %%%% utilities get_connectiontype() -> C2 = get_connections(5222) -1, C3 = get_connections(5223) -1, NUplain = C2 + C3 - get_tls_drv(), NUtls = C2 - NUplain, NUssl = C3, {NUplain, NUtls, NUssl}. ms_to_time(T) -> DMS = 24*60*60*1000, HMS = 60*60*1000, MMS = 60*1000, SMS = 1000, D = trunc(T/DMS), H = trunc((T - (D*DMS)) / HMS), M = trunc((T - (D*DMS) - (H*HMS)) / MMS), S = trunc((T - (D*DMS) - (H*HMS) - (M*MMS)) / SMS), [D, H, M, S]. %% Cuando un usuario conecta, pedirle iq:version a nombre de Host/mod_stats2file user_login(#{user := User, lserver := Host, resource := Resource, ip := IpPort} = State) -> ets:update_counter(table_name(server), {user_login, server}, 1), ets:update_counter(table_name(Host), {user_login, Host}, 1), timer:apply_after(timer:seconds(5), ?MODULE, request_iqversion, [User, Host, Resource, IpPort]), State. %%user_logout_sm(_, JID, _Data) -> %% user_logout(JID#jid.luser, JID#jid.lserver, JID#jid.lresource, no_status). %% cuando un usuario desconecta, buscar en la tabla su JID/USR y quitarlo user_logout(#{user := User, lserver := Host, resource := Resource} = State, _Reason) -> TableHost = table_name(Host), TableServer = table_name(server), ets:update_counter(TableServer, {user_logout, server}, 1), ets:update_counter(TableHost, {user_logout, Host}, 1), JID = jid:make(User, Host, Resource), case ets:lookup(TableHost, {session, JID}) of [{_, Client_id, OS_id, Lang, ConnType, _Client, _Version, _OS}] -> ets:delete(TableHost, {session, JID}), ets:update_counter(TableHost, {client, Host, Client_id}, -1), ets:update_counter(TableServer, {client, server, Client_id}, -1), ets:update_counter(TableHost, {os, Host, OS_id}, -1), ets:update_counter(TableServer, {os, server, OS_id}, -1), ets:update_counter(TableHost, {conntype, Host, ConnType}, -1), ets:update_counter(TableServer, {conntype, server, ConnType}, -1), update_counter_create(TableHost, {client_os, Host, Client_id, OS_id}, -1), update_counter_create(TableServer, {client_os, server, Client_id, OS_id}, -1), update_counter_create(TableHost, {client_conntype, Host, Client_id, ConnType}, -1), update_counter_create(TableServer, {client_conntype, server, Client_id, ConnType}, -1), update_counter_create(TableHost, {lang, Host, Lang}, -1), update_counter_create(TableServer, {lang, server, Lang}, -1); [] -> ok end, State. request_iqversion(User, Host, Resource, IpPort) -> case ejabberd_sm:get_user_ip(User, Host, Resource) of IpPort -> request_iqversion(User, Host, Resource); _ -> ok end. request_iqversion(User, Host, Resource) -> From = jid:make(<<"">>, Host, list_to_binary(atom_to_list(?MODULE))), To = jid:make(User, Host, Resource), Query = #xmlel{name = <<"query">>, attrs = [{<<"xmlns">>, ?NS_VERSION}]}, IQ = #iq{type = get, from = From, to = To, sub_els = [Query]}, HandleResponse = fun(#iq{type = Type} = IQr) when (Type == result) or (Type == error) -> spawn(?MODULE, received_response, [To, From, IQr]); (timeout) -> spawn(?MODULE, received_response, [To, unknown, unknown, <<"">>, "unknown", "unknown", "unknown"]); (R) -> ?INFO_MSG("Unexpected response: ~n~p", [{User, Host, Resource, R}]), ok % Hmm. end, ejabberd_router:route_iq(IQ, HandleResponse). %% cuando el virtualJID recibe una respuesta iqversion, %% almacenar su JID/USR + client + OS en una tabla received_response(From, _To, El) -> try received_response(From, El) catch _:_ -> ok end. received_response(From, #iq{type = error, lang = Lang1, sub_els = Elc} = Iq) when [{xmlel,<<"error">>, [{<<"type">>,<<"modify">>}], [{xmlel,<<"not-acceptable">>, [{<<"xmlns">>,<<"urn:ietf:params:xml:ns:xmpp-stanzas">>}], []}]}] == Elc -> Resource = From#jid.lresource, {Client_id, OS_id} = case binary:split(Resource, [<<"-">>, <<"_">>], [global]) of [<<"xabber">>, <<"android">>, _] -> {xabber, android}; [<<"Xabber">> | _] -> {xabber, unknown}; _ -> ?INFO_MSG("statsdx unknown client: ~n~p", [Iq]), {unknown, unknown} end, received_response(From, Client_id, OS_id, Lang1, "unknown", "unknown", "unknown"); received_response(From, #iq{type = result, lang = Lang1, sub_els = Elc}) -> [El] = fxml:remove_cdata(Elc), {xmlel, _, Attrs2, _Els2} = El, ?NS_VERSION = fxml:get_attr_s(<<"xmlns">>, Attrs2), Client = get_tag_cdata_subtag(El, <<"name">>), Version = get_tag_cdata_subtag(El, <<"version">>), OS = get_tag_cdata_subtag(El, <<"os">>), {Client_id, OS_id} = identify(Client, OS), received_response(From, Client_id, OS_id, Lang1, Client, Version, OS); received_response(From, #iq{type = error, lang = Lang1} = Iq) -> ?INFO_MSG("statsdx unknown client: ~n~p", [Iq]), received_response(From, unknown, unknown, Lang1, "unknown", "unknown", "unknown"). received_response(From, Client_id, OS_id, Lang1, Client, Version, OS) -> User = From#jid.luser, Host = From#jid.lserver, Resource = From#jid.lresource, ConnType = get_connection_type(User, Host, Resource), Lang = case Lang1 of <<"">> -> "unknown"; L -> binary_to_list(L) end, TableHost = table_name(Host), TableServer = table_name(server), ets:update_counter(TableHost, {client, Host, Client_id}, 1), ets:update_counter(TableServer, {client, server, Client_id}, 1), ets:update_counter(TableHost, {os, Host, OS_id}, 1), ets:update_counter(TableServer, {os, server, OS_id}, 1), ets:update_counter(TableHost, {conntype, Host, ConnType}, 1), ets:update_counter(TableServer, {conntype, server, ConnType}, 1), update_counter_create(TableHost, {lang, Host, Lang}, 1), update_counter_create(TableServer, {lang, server, Lang}, 1), update_counter_create(TableHost, {client_os, Host, Client_id, OS_id}, 1), update_counter_create(TableServer, {client_os, server, Client_id, OS_id}, 1), update_counter_create(TableHost, {client_conntype, Host, Client_id, ConnType}, 1), update_counter_create(TableServer, {client_conntype, server, Client_id, ConnType}, 1), ets:insert(TableHost, {{session, From}, Client_id, OS_id, Lang, ConnType, Client, Version, OS}). get_connection_type(User, Host, Resource) -> UserInfo = ejabberd_sm:get_user_info(User, Host, Resource), {conn, Conn} = lists:keyfind(conn, 1, UserInfo), Conn. update_counter_create(Table, Element, C) -> case ets:lookup(Table, Element) of [] -> ets:insert(Table, {Element, 1}); _ -> ets:update_counter(Table, Element, C) end. get_tag_cdata_subtag(E, T) -> E2 = fxml:get_subtag(E, T), case E2 of false -> "unknown"; _ -> binary_to_list(fxml:get_tag_cdata(E2)) end. list_elem(Type, id) -> {_, Ids} = lists:unzip(list_elem(Type, full)), Ids; list_elem(clients, full) -> [ {"adium", adium}, {"aqq", aqq}, {"atalk", atalk}, {"bitlbee", bitlbee}, {"blabber.im", blabber_im}, {"bruno", bruno}, {"centerim", centerim}, {"coccinella", coccinella}, {"conversations", conversations}, {"exodus", exodus}, {"gabber", gabber}, {"gaim", gaim}, {"gajim", gajim}, {"ichat", ichat}, {"imagent", messages}, {"instantbird", instantbird}, {"irssi-xmpp", irssi_xmpp}, {"jabber.el", jabber_el}, {"jajc", jajc}, {"jbother", jbother}, {"kopete", kopete}, {"libgaim", libgaim}, {"mcabber", mcabber}, {"miranda", miranda}, {"monal", monal}, {"pandion", pandion}, {"pidgin", pidgin}, {"poezio", poezio}, {"profanity", profanity}, {"psi", psi}, {"qip infium", qipinfium}, {"spark", spark}, {"swift", swift}, {"telepathy gabble", telepathy_gabble}, {"thunderbird", thunderbird}, {"tkabber", tkabber}, {"trillian", trillian}, {"vacuum-im", vacuum_im}, {"wtw", wtw}, {"xabber", xabber}, {"xmpp messenger", xmpp_messenger}, {"xmppjabberclient", xmpp_jabber_client}, {"yaxim", yaxim}, {"unknown", unknown} ]; list_elem(conntypes, full) -> [ {"c2s", c2s}, {"c2s_tls", c2s_tls}, {"c2s_compressed", c2s_compressed}, {"c2s_compressed_tls", c2s_compressed_tls}, {"http_bind", http_bind}, {"websocket", websocket}, {"unknown", unknown} ]; list_elem(oss, full) -> [ {"android", android}, {"bsd", bsd}, {"debian", linux}, {"gentoo", linux}, {"kde", linux}, {"linux", linux}, {"mac", mac}, {"mageia", linux}, {"opensuse", linux}, {"sunos", linux}, {"ubuntu", linux}, {"win", windows}, {"unknown", unknown} ]. identify(Client, OS) -> Res = {try_match(string:to_lower(Client), list_elem(clients, full)), try_match(string:to_lower(OS), list_elem(oss, full))}, case Res of {libgaim, mac} -> {adium, mac}; {adium, unknown} -> {adium, mac}; {qipinfium, unknown} -> {qipinfium, windows}; _ -> Res end. try_match(_E, []) -> unknown; try_match(E, [{Str, Id} | L]) -> case string:str(E, Str) of 0 -> try_match(E, L); _ -> Id end. get_client_os(Server) -> CO1 = ets:match(table_name(Server), {{client_os, Server, '$1', '$2'}, '$3'}), CO2 = lists:map( fun([Cl, Os, A3]) -> {lists:flatten([atom_to_list(Cl), "/", atom_to_list(Os)]), A3} end, CO1 ), lists:keysort(1, CO2). get_client_conntype(Server) -> CO1 = ets:match(table_name(Server), {{client_conntype, Server, '$1', '$2'}, '$3'}), CO2 = lists:map( fun([Cl, Os, A3]) -> {lists:flatten([atom_to_list(Cl), "/", atom_to_list(Os)]), A3} end, CO1 ), lists:keysort(1, CO2). get_languages(Server) -> L1 = ets:match(table_name(Server), {{lang, Server, '$1'}, '$2'}), L2 = lists:map( fun([La, C]) -> {La, C} end, L1 ), lists:keysort(1, L2). get_meanitemsinroster() -> get_meanitemsinroster2(getl("totalrosteritems"), getl("registeredusers")). get_meanitemsinroster(Host) -> get_meanitemsinroster2(getl("totalrosteritems", Host), getl("registeredusers", Host)). get_meanitemsinroster2(Items, Users) -> case Users of 0 -> 0; _ -> Items/Users end. localtime_to_string({{Y, Mo, D},{H, Mi, S}}) -> lists:concat([H, ":", Mi, ":", S, " ", D, "/", Mo, "/", Y]). %% cuando toque mostrar estadisticas %%get_iqversion() -> %% contar en la tabla cuantos tienen cliente: *psi* %%buscar en la tabla iqversion %%ok. %%%================================== %%%% Web Admin Menu web_menu_main(Acc, Lang) -> Acc ++ [{<<"statsdx">>, <<(translate:translate(Lang, ?T("Statistics")))/binary, " Dx">>}]. web_menu_node(Acc, _Node, Lang) -> Acc ++ [{<<"statsdx">>, <<(translate:translate(Lang, ?T("Statistics")))/binary, " Dx">>}]. web_menu_host(Acc, _Host, Lang) -> Acc ++ [{<<"statsdx">>, <<(translate:translate(Lang, ?T("Statistics")))/binary, " Dx">>}]. web_user(Acc, User, Host, Lang) -> Filter = [<<"username">>, User], Sort_query = {normal, 1}, Acc ++ [?XCT(<<"h3">>, <<(translate:translate(Lang, ?T("Statistics")))/binary, " Dx">>), ?XE(<<"table">>, [?XE(<<"thead">>, [?XE(<<"tr">>, make_sessions_table_tr(Lang, false) )]), ?XE(<<"tbody">>, do_sessions_table(global, Lang, Filter, Sort_query, Host)) ]) ]. %%%================================== %%%% Web Admin Page web_page_main(_, #request{path=[<<"statsdx">>], lang = Lang} = _Request) -> Res = [?XC(<<"h1">>, <<(translate:translate(Lang, ?T("Statistics")))/binary, " Dx">>), ?XC(<<"h3">>, <<"Accounts">>), ?XAE(<<"table">>, [], [?XE(<<"tbody">>, [ do_stat(global, Lang, "registeredusers") ]) ]), ?XC(<<"h3">>, <<"Roster">>), ?XAE(<<"table">>, [], [?XE(<<"tbody">>, [ do_stat(global, Lang, "totalrosteritems"), do_stat(global, Lang, "meanitemsinroster"), ?XE(<<"tr">>, [?XE(<<"td">>, [?CT(<<"Top rosters">>)]), ?XE(<<"td">>, [ ?ACT(<<"top/roster/30/">>, <<"30">>), ?C(<<", ">>), ?ACT(<<"top/roster/100/">>, <<"100">>), ?C(<<", ">>), ?ACT(<<"top/roster/500/">>, <<"500">>) ])] ) ]) ]), ?XC(<<"h3">>, <<"Users">>), ?XAE(<<"table">>, [], [?XE(<<"tbody">>, [ do_stat(global, Lang, "onlineusers"), do_stat(global, Lang, "offlinemsg"), ?XE(<<"tr">>, [?XE(<<"td">>, [?CT(<<"Top offline message queues">>) ]), ?XE(<<"td">>, [ ?ACT(<<"top/offlinemsg/30/">>, <<"30">>), ?C(<<", ">>), ?ACT(<<"top/offlinemsg/100/">>, <<"100">>), ?C(<<", ">>), ?ACT(<<"top/offlinemsg/500/">>, <<"500">>) ])] ), do_stat(global, Lang, "vcards"), ?XE(<<"tr">>, [?XE(<<"td">>, [?CT(<<"Top vCard sizes">>) ]), ?XE(<<"td">>, [ ?ACT(<<"top/vcard/5/">>, <<"5">>), ?C(<<", ">>), ?ACT(<<"top/vcard/30/">>, <<"30">>), ?C(<<", ">>), ?ACT(<<"top/vcard/100/">>, <<"100">>), ?C(<<", ">>), ?ACT(<<"top/vcard/500/">>, <<"500">>) ])] ) ]) ]), ?XC(<<"h3">>, <<"MUC">>), ?XAE(<<"table">>, [], [?XE(<<"tbody">>, [ do_stat(global, Lang, "totalmucrooms"), do_stat(global, Lang, "permmucrooms"), do_stat(global, Lang, "regmucrooms") ]) ]), ?XC(<<"h3">>, <<"Pub/Sub">>), ?XAE(<<"table">>, [], [?XE(<<"tbody">>, [ do_stat(global, Lang, "regpubsubnodes") ]) ]), %%?XC("h3", "IRC"), %%?XAE("table", [], %% [?XE("tbody", [ %% do_stat(global, Lang, "ircconns") %% ]) %%]), %%?XC("h3", "Ratios"), %%?XAE("table", [], %% [?XE("tbody", [ %% ]) %% ]), ?XC(<<"h3">>, <<"Sessions: ", (get_stat_n("client"))/binary>>), ?XAE(<<"table">>, [], [?XE(<<"tbody">>, do_stat_table(global, Lang, "client", server) ) ]), ?XC(<<"h3">>, <<"Sessions: ", (get_stat_n("os"))/binary>>), ?XAE(<<"table">>, [], [?XE(<<"tbody">>, do_stat_table(global, Lang, "os", server) ) ]), ?XC(<<"h3">>, <<"Sessions: ", (get_stat_n("client"))/binary, "/", (get_stat_n("os"))/binary>>), ?XAE(<<"table">>, [], [?XE(<<"tbody">>, do_stat_table(global, Lang, "client_os", server) ) ]), ?XC(<<"h3">>, <<"Sessions: ", (get_stat_n("conntype"))/binary>>), ?XAE(<<"table">>, [], [?XE(<<"tbody">>, do_stat_table(global, Lang, "conntype", server) ) ]), ?XC(<<"h3">>, <<"Sessions: ", (get_stat_n("client"))/binary, "/", (get_stat_n("conntype"))/binary>>), ?XAE(<<"table">>, [], [?XE(<<"tbody">>, do_stat_table(global, Lang, "client_conntype", server) ) ]), ?XC(<<"h3">>, <<"Sessions: ", (get_stat_n("languages"))/binary>>), ?XAE(<<"table">>, [], [?XE(<<"tbody">>, do_stat_table(global, Lang, "languages", server) ) ]) ], {stop, Res}; web_page_main(_, #request{path=[<<"statsdx">>, <<"top">>, Topic, Topnumber], q = _Q, lang = Lang} = _Request) -> Res = [?XC(<<"h1">>, <<(translate:translate(Lang, ?T("Statistics")))/binary, " Dx">>), case Topic of <<"offlinemsg">> -> ?XCT(<<"h2">>, <<"Top offline message queues">>); <<"vcard">> -> ?XCT(<<"h2">>, <<"Top vCard sizes">>); <<"roster">> -> ?XCT(<<"h2">>, <<"Top rosters">>) end, ?XE(<<"table">>, [?XE(<<"thead">>, [?XE(<<"tr">>, [?XE(<<"td">>, [?CT(<<"#">>)]), ?XE(<<"td">>, [?CT(<<"Jabber ID">>)]), ?XE(<<"td">>, [?CT(<<"Value">>)])] )]), ?XE(<<"tbody">>, do_top_table(global, Lang, Topic, Topnumber, server)) ]) ], {stop, Res}; web_page_main(_, #request{path=[<<"statsdx">> | Filter], q = Q, lang = Lang} = _Request) -> Sort_query = get_sort_query(Q), FilterS = io_lib:format("~p", [Filter]), Res = [?XC(<<"h1">>, <<(translate:translate(Lang, ?T("Statistics")))/binary, " Dx">>), ?XC(<<"h2">>, list_to_binary("Sessions with: " ++ FilterS)), ?XE(<<"table">>, [ ?XE(<<"thead">>, [?XE(<<"tr">>, make_sessions_table_tr(Lang) )]), ?XE(<<"tbody">>, do_sessions_table(global, Lang, Filter, Sort_query, server)) ]) ], {stop, Res}; web_page_main(Acc, _) -> Acc. do_top_table(_Node, Lang, Topic, TopnumberBin, Host) -> List = get_top_users(Host, binary_to_integer(TopnumberBin), Topic), %% get_top_users(Topnumber, "roster") {List2, _} = lists:mapfoldl( fun({Value, UserB, ServerB}, Counter) -> User = binary_to_list(UserB), Server = binary_to_list(ServerB), UserJID = User++"@"++Server, Level = case Host of server -> 4; _ -> 6 end, UserJIDUrl = lists:duplicate(Level, "../") ++ "server/" ++ Server ++ "/user/" ++ User ++ "/", ValueString = integer_to_list(Value), ValueEl = case Topic of <<"offlinemsg">> -> {url, UserJIDUrl++"queue/", ValueString}; <<"vcard">> -> {url, UserJIDUrl++"vcard/", ValueString}; <<"roster">> -> {url, UserJIDUrl++"roster/", ValueString}; _ -> ValueString end, {do_table_element(Counter, Lang, UserJID, {fixed_url, UserJIDUrl}, ValueEl), Counter+1} end, 1, List ), List2. %% Code copied from mod_muc_admin.erl %% Returns: {normal | reverse, Integer} get_sort_query(Q) -> case catch get_sort_query2(Q) of {ok, Res} -> Res; _ -> {normal, 1} end. get_sort_query2(Q) -> {value, {_, Binary}} = lists:keysearch(<<"sort">>, 1, Q), Integer = binary_to_integer(lists:nth(1, binary:split(Binary, <<"/">>))), case Integer >= 0 of true -> {ok, {normal, Integer}}; false -> {ok, {reverse, abs(Integer)}} end. make_sessions_table_tr(Lang) -> make_sessions_table_tr(Lang, true). make_sessions_table_tr(Lang, Sorting) -> Titles = [<<"Jabber ID">>, <<"Client ID">>, <<"OS ID">>, <<"Lang">>, <<"Connection">>, <<"Client">>, <<"Version">>, <<"OS">>], {Titles_TR, _} = lists:mapfoldl( fun(Title, Num_column) -> NCS = list_to_binary(integer_to_list(Num_column)), SortingEls = case Sorting of false -> []; true -> [?BR, ?ACT(<<"?sort=", NCS/binary>>, <<"<">>), ?C(<<" ">>), ?ACT(<<"?sort=-", NCS/binary>>, <<">">>)] end, TD = ?XE(<<"td">>, [?CT(Title)] ++ SortingEls), {TD, Num_column+1} end, 1, Titles), Titles_TR. web_page_node(_, Node, [<<"statsdx">>], _Query, Lang) -> TransactionsCommited = rpc:call(Node, mnesia, system_info, [transaction_commits]), TransactionsAborted = rpc:call(Node, mnesia, system_info, [transaction_failures]), TransactionsRestarted = rpc:call(Node, mnesia, system_info, [transaction_restarts]), TransactionsLogged = rpc:call(Node, mnesia, system_info, [transaction_log_writes]), Res = [?XC(<<"h1">>, list_to_binary(io_lib:format(translate:translate(Lang, ?T("~p statistics")), [Node]))), ?XC(<<"h3">>, <<"Connections">>), ?XAE(<<"table">>, [], [?XE(<<"tbody">>, [ do_stat(global, Lang, "onlineusers"), do_stat(Node, Lang, "httpbindusers"), do_stat(Node, Lang, "s2sconnections"), do_stat(Node, Lang, "s2sservers") ]) ]), ?XC(<<"h3">>, <<"ejabberd">>), ?XAE(<<"table">>, [], [?XE(<<"tbody">>, [ do_stat(Node, Lang, "ejabberdversion") ]) ]), ?XC(<<"h3">>, <<"Erlang">>), ?XAE(<<"table">>, [], [?XE(<<"tbody">>, [ do_stat(Node, Lang, "operatingsystem"), do_stat(Node, Lang, "erlangmachine"), do_stat(Node, Lang, "erlangmachinetarget"), do_stat(Node, Lang, "maxprocallowed"), do_stat(Node, Lang, "procqueue"), do_stat(Node, Lang, "totalerlproc") ]) ]), ?XC(<<"h3">>, <<"Times">>), ?XAE(<<"table">>, [], [?XE(<<"tbody">>, [ do_stat(Node, Lang, "uptime"), do_stat(Node, Lang, "uptimehuman"), do_stat(Node, Lang, "lastrestart"), do_stat(Node, Lang, "cputime") ]) ]), ?XC(<<"h3">>, <<"CPU">>), ?XAE(<<"table">>, [], [?XE(<<"tbody">>, [ do_stat(Node, Lang, "cpu_avg1"), do_stat(Node, Lang, "cpu_avg5"), do_stat(Node, Lang, "cpu_avg15"), do_stat(Node, Lang, "cpu_nprocs")%, %%do_stat(Node, Lang, "cpu_util_user"), %%do_stat(Node, Lang, "cpu_nice_user"), %%do_stat(Node, Lang, "cpu_kernel"), %%do_stat(Node, Lang, "cpu_idle"), %%do_stat(Node, Lang, "cpu_wait") ]) ]), %%?XC("h3", "RAM"), %%?XAE("table", [], %% [?XE("tbody", [ %% do_stat(Node, Lang, "memsup_system"), %% do_stat(Node, Lang, "memsup_free"), %% do_stat(Node, Lang, "reductions") %%]) %%]), ?XC(<<"h3">>, <<"Memory (bytes)">>), ?XAE(<<"table">>, [], [?XE(<<"tbody">>, [ do_stat(Node, Lang, "memory_total"), do_stat(Node, Lang, "memory_processes"), do_stat(Node, Lang, "memory_processes_used"), do_stat(Node, Lang, "memory_system"), do_stat(Node, Lang, "memory_atom"), do_stat(Node, Lang, "memory_atom_used"), do_stat(Node, Lang, "memory_binary"), do_stat(Node, Lang, "memory_code"), do_stat(Node, Lang, "memory_ets") ]) ]), ?XC(<<"h3">>, <<"Database">>), ?XAE(<<"table">>, [], [?XE(<<"tbody">>, [ ?XE(<<"tr">>, [?XCT(<<"td">>, <<"Transactions commited">>), ?XAC(<<"td">>, [{<<"class">>, <<"alignright">>}], list_to_binary(integer_to_list(TransactionsCommited)))]), ?XE(<<"tr">>, [?XCT(<<"td">>, <<"Transactions aborted">>), ?XAC(<<"td">>, [{<<"class">>, <<"alignright">>}], list_to_binary(integer_to_list(TransactionsAborted)))]), ?XE(<<"tr">>, [?XCT(<<"td">>, <<"Transactions restarted">>), ?XAC(<<"td">>, [{<<"class">>, <<"alignright">>}], list_to_binary(integer_to_list(TransactionsRestarted)))]), ?XE(<<"tr">>, [?XCT(<<"td">>, <<"Transactions logged">>), ?XAC(<<"td">>, [{<<"class">>, <<"alignright">>}], list_to_binary(integer_to_list(TransactionsLogged)))]) ]) ])], {stop, Res}; web_page_node(Acc, _, _, _, _) -> Acc. web_page_host(_, Host, #request{path = [<<"statsdx">>], lang = Lang} = _Request) -> Res = [?XC(<<"h1">>, <<(translate:translate(Lang, ?T("Statistics")))/binary, " Dx">>), ?XC(<<"h2">>, Host), ?XC(<<"h3">>, <<"Accounts">>), ?XAE(<<"table">>, [], [?XE(<<"tbody">>, [ do_stat(global, Lang, "registeredusers", Host) ]) ]), ?XC(<<"h3">>, <<"Roster">>), ?XAE(<<"table">>, [], [?XE(<<"tbody">>, [ do_stat(global, Lang, "totalrosteritems", Host), %%get_meanitemsinroster2(TotalRosterItems, RegisteredUsers) ?XE(<<"tr">>, [?XE(<<"td">>, [?C(<<"Top rosters">>) ]), ?XE(<<"td">>, [ ?ACT(<<"top/roster/30/">>, <<"30">>), ?C(<<", ">>), ?ACT(<<"top/roster/100/">>, <<"100">>), ?C(<<", ">>), ?ACT(<<"top/roster/500/">>, <<"500">>) ])] ) ]) ]), ?XC(<<"h3">>, <<"Users">>), ?XAE(<<"table">>, [], [?XE(<<"tbody">>, [ do_stat(global, Lang, "onlineusers", Host), %%do_stat(global, Lang, "offlinemsg", Host), %% This make take a lot of time %%do_stat(global, Lang, "vcards", Host) %% This make take a lot of time ?XE(<<"tr">>, [?XE(<<"td">>, [?C(<<"Top offline message queues">>)]), ?XE(<<"td">>, [ ?ACT(<<"top/offlinemsg/30/">>, <<"30">>), ?C(<<", ">>), ?ACT(<<"top/offlinemsg/100/">>, <<"100">>), ?C(<<", ">>), ?ACT(<<"top/offlinemsg/500/">>, <<"500">>) ])] ), ?XE(<<"tr">>, [?XE(<<"td">>, [?C(<<"Top vCard sizes">>) ]), ?XE(<<"td">>, [ ?ACT(<<"top/vcard/5/">>, <<"5">>), ?C(<<", ">>), ?ACT(<<"top/vcard/30/">>, <<"30">>), ?C(<<", ">>), ?ACT(<<"top/vcard/100/">>, <<"100">>), ?C(<<", ">>), ?ACT(<<"top/vcard/500/">>, <<"500">>) ])] ) ]) ]), ?XC(<<"h3">>, <<"Connections">>), ?XAE(<<"table">>, [], [?XE(<<"tbody">>, [ do_stat(global, Lang, "s2sconnections", Host) ]) ]), ?XC(<<"h3">>, <<"MUC">>), ?XAE(<<"table">>, [], [?XE(<<"tbody">>, [ do_stat(global, Lang, "totalmucrooms", Host), do_stat(global, Lang, "permmucrooms", Host), do_stat(global, Lang, "regmucrooms", Host) ]) ]), %%?XC("h3", "IRC"), %%?XAE("table", [], %% [?XE("tbody", [ %% do_stat(global, Lang, "ircconns", Host) %% ]) %%]), %%?XC("h3", "Pub/Sub"), %%?XAE("table", [], %% [?XE("tbody", [ %% do_stat(global, Lang, "regpubsubnodes", Host) %% ]) %%]), ?XC(<<"h3">>, <<"Sessions: ", (get_stat_n("client"))/binary>>), ?XAE(<<"table">>, [], [?XE(<<"tbody">>, do_stat_table(global, Lang, "client", Host) ) ]), ?XC(<<"h3">>, <<"Sessions: ", (get_stat_n("os"))/binary>>), ?XAE(<<"table">>, [], [?XE(<<"tbody">>, do_stat_table(global, Lang, "os", Host) ) ]), ?XC(<<"h3">>, <<"Sessions: ", (get_stat_n("client"))/binary, "/", (get_stat_n("os"))/binary>>), ?XAE(<<"table">>, [], [?XE(<<"tbody">>, do_stat_table(global, Lang, "client_os", Host) ) ]), ?XC(<<"h3">>, <<"Sessions: ", (get_stat_n("conntype"))/binary>>), ?XAE(<<"table">>, [], [?XE(<<"tbody">>, do_stat_table(global, Lang, "conntype", Host) ) ]), ?XC(<<"h3">>, <<"Sessions: ", (get_stat_n("client"))/binary, "/", (get_stat_n("conntype"))/binary>>), ?XAE(<<"table">>, [], [?XE(<<"tbody">>, do_stat_table(global, Lang, "client_conntype", Host) ) ]), ?XC(<<"h3">>, <<"Sessions: ", (get_stat_n("languages"))/binary>>), ?XAE(<<"table">>, [], [?XE(<<"tbody">>, do_stat_table(global, Lang, "languages", Host) ) ]), ?XC(<<"h3">>, <<"Ratios">>), ?XAE(<<"table">>, [], [?XE(<<"tbody">>, [ do_stat(global, Lang, "user_login", Host), do_stat(global, Lang, "user_logout", Host), do_stat(global, Lang, "register_user", Host), do_stat(global, Lang, "remove_user", Host), do_stat(global, Lang, {send, iq, in}, Host), do_stat(global, Lang, {send, iq, out}, Host), do_stat(global, Lang, {send, message, in}, Host), do_stat(global, Lang, {send, message, out}, Host), do_stat(global, Lang, {send, presence, in}, Host), do_stat(global, Lang, {send, presence, out}, Host), do_stat(global, Lang, {recv, iq, in}, Host), do_stat(global, Lang, {recv, iq, out}, Host), do_stat(global, Lang, {recv, message, in}, Host), do_stat(global, Lang, {recv, message, out}, Host), do_stat(global, Lang, {recv, presence, in}, Host), do_stat(global, Lang, {recv, presence, out}, Host) ]) ]) ], {stop, Res}; web_page_host(_, Host, #request{path=[<<"statsdx">>, <<"top">>, Topic, Topnumber], q = _Q, lang = Lang} = _Request) -> Res = [?XC(<<"h1">>, <<(translate:translate(Lang, ?T("Statistics")))/binary, " Dx">>), case Topic of <<"offlinemsg">> -> ?XCT(<<"h2">>, <<"Top offline message queues">>); <<"vcard">> -> ?XCT(<<"h2">>, <<"Top vCard sizes">>); <<"roster">> -> ?XCT(<<"h2">>, <<"Top rosters">>) end, ?XE(<<"table">>, [?XE(<<"thead">>, [?XE(<<"tr">>, [?XE(<<"td">>, [?CT(<<"#">>)]), ?XE(<<"td">>, [?CT(<<"Jabber ID">>)]), ?XE(<<"td">>, [?CT(<<"Value">>)])] )]), ?XE(<<"tbody">>, do_top_table(global, Lang, Topic, Topnumber, Host)) ]) ], {stop, Res}; web_page_host(_, Host, #request{path=[<<"statsdx">> | Filter], q = Q, lang = Lang} = _Request) -> Sort_query = get_sort_query(Q), Res = [?XC(<<"h1">>, <<(translate:translate(Lang, ?T("Statistics")))/binary, " Dx">>), ?XC(<<"h2">>, list_to_binary("Sessions with: "++io_lib:format("~p", [Filter]))), ?XAE(<<"table">>, [], [ ?XE(<<"thead">>, [?XE(<<"tr">>, make_sessions_table_tr(Lang) )]), ?XE(<<"tbody">>, do_sessions_table(global, Lang, Filter, Sort_query, Host)) ]) ], {stop, Res}; web_page_host(Acc, _, _) -> Acc. %%%================================== %%%% Web Admin Utils do_table_element(Lang, L, StatLink, N) -> do_table_element(no_counter, Lang, L, StatLink, N). do_table_element(Counter, Lang, L, StatLink, N) -> ?XE(<<"tr">>, [ case Counter of no_counter -> ?C(<<"">>); _ -> ?XE(<<"td">>, [?C(list_to_binary(integer_to_list(Counter)))]) end, case StatLink of no_link -> ?XCT(<<"td">>, L); {fixed_url, Fixedurl} -> ?XE(<<"td">>, [?AC(list_to_binary(Fixedurl), list_to_binary(L))]); _ -> ?XE(<<"td">>, [?AC(list_to_binary(make_url(StatLink, L)), list_to_binary(L))]) end, case N of {url, NUrl, NName} -> ?XAE(<<"td">>, [{<<"class">>, <<"alignright">>}], [?AC(list_to_binary(NUrl), list_to_binary(NName))]); N when is_list(N) -> ?XAC(<<"td">>, [{<<"class">>, <<"alignright">>}], list_to_binary(N)); _ -> ?XAC(<<"td">>, [{<<"class">>, <<"alignright">>}], N) end ]). make_url(StatLink, L) -> List = case string:tokens(StatLink, "_") of [Stat] -> [Stat, L]; [Stat1, Stat2] -> [L1, L2] = string:tokens(L, "/"), [Stat1, L1, Stat2, L2] end, string:join(List, "/")++["/"]. do_stat_table(global, Lang, Stat, Host) -> Os = mod_statsdx:get_statistic(global, [Stat, Host]), lists:map( fun({_L, 0}) when Stat == "client" -> ?C(<<"">>); ({L, N}) -> do_table_element(Lang, L, Stat, io_lib:format("~p", [N])) end, lists:reverse(lists:keysort(2, Os)) ). do_sessions_table(_Node, _Lang, Filter, {Sort_direction, Sort_column}, Host) -> Sessions = get_sessions_filtered(Filter, Host), SessionsSorted = sort_sessions(Sort_direction, Sort_column, Sessions), lists:map( fun( {{session, JID}, Client_id, OS_id, LangS, ConnType, Client, Version, OS} ) -> Lang = list_to_binary(LangS), User = binary_to_list(JID#jid.luser), Server = binary_to_list(JID#jid.lserver), Level = case Host of server -> 1 + length(Filter); _ -> 3 + length(Filter) end, UserURL = lists:duplicate(Level, "../") ++ "server/" ++ Server ++ "/user/" ++ User ++ "/", {UpInt, UserEl} = case Filter of [<<"username">>, _] -> {0, ?XCT(<<"td">>, jid:encode(JID))}; _ -> {1, ?XE(<<"td">>, [?AC(list_to_binary(UserURL), jid:encode(JID))])} end, UpStr = list_to_binary(lists:duplicate(length(Filter) + UpInt, "../")), ClientIdBin = misc:atom_to_binary(Client_id), OsIdBin = misc:atom_to_binary(OS_id), ConnTypeBin = misc:atom_to_binary(ConnType), ?XE(<<"tr">>, [ UserEl, ?XE(<<"td">>, [?AC(<>, ClientIdBin)]), ?XE(<<"td">>, [?AC(<>, OsIdBin)]), ?XE(<<"td">>, [?AC(<>, Lang)]), ?XE(<<"td">>, [?AC(<>, ConnTypeBin)]), ?XCTB("td", Client), ?XCTB("td", Version), ?XCTB("td", OS) ]) end, SessionsSorted ). %% Code copied from mod_muc_admin.erl sort_sessions(Direction, Column, Rooms) -> Rooms2 = lists:keysort(Column, Rooms), case Direction of normal -> Rooms2; reverse -> lists:reverse(Rooms2) end. get_sessions_filtered(Filter, server) -> lists:foldl( fun(Host, Res) -> try get_sessions_filtered(Filter, Host) of List when is_list(List) -> List ++ Res catch _:_ -> Res end end, [], ejabberd_config:get_option(hosts)); get_sessions_filtered(Filter, Host) -> Match = case Filter of [<<"username">>, Username] -> {{session, {jid, Username, Host, '$1', Username, Host, '$1'}}, '$2', '$3', '$4', '$5', '$6', '$7', '$8'}; [<<"client">>, Client] -> {{session, '$1'}, misc:binary_to_atom(Client), '$2', '$3', '$4', '$5', '$6', '$7'}; [<<"os">>, OS] -> {{session, '$1'}, '$2', misc:binary_to_atom(OS), '$3', '$4', '$5', '$6', '$7'}; [<<"conntype">>, ConnType] -> {{session, '$1'}, '$2', '$3', '$4', misc:binary_to_atom(ConnType), '$5', '$6', '$7'}; [<<"languages">>, Lang] -> {{session, '$1'}, '$2', '$3', binary_to_list(Lang), '$4', '$5', '$6', '$7'}; [<<"client">>, Client, <<"os">>, OS] -> {{session, '$1'}, misc:binary_to_atom(Client), misc:binary_to_atom(OS), '$3', '$4', '$5', '$6', '$7'}; [<<"client">>, Client, <<"conntype">>, ConnType] -> {{session, '$1'}, misc:binary_to_atom(Client), '$2', '$3', misc:binary_to_atom(ConnType), '$5', '$6', '$7'}; _ -> {{session, '$1'}, '$2', '$3', '$4', '$5'} end, ets:match_object(table_name(Host), Match). do_stat(Node, Lang, Stat) -> ?XE(<<"tr">>, [ ?XCT(<<"td">>, get_stat_n(Stat)), ?XAC(<<"td">>, [{<<"class">>, <<"alignright">>}], get_stat_v(Node, [Stat]))]). do_stat(Node, Lang, Stat, Host) -> %%[Res] = get_stat_v(Node, [Stat, Host]), %%do_table_element(Lang, get_stat_n(Stat), Res). do_table_element(Lang, get_stat_n(Stat), no_link, get_stat_v(Node, [Stat, Host])). %% Get a stat name get_stat_n(Stat) -> list_to_binary(mod_statsdx:get_statistic(foo, [Stat, title])). %% Get a stat value get_stat_v(Node, Stat) -> list_to_binary(get_stat_v2(mod_statsdx:get_statistic(Node, Stat))). get_stat_v2(Value) when is_list(Value) -> Value; get_stat_v2(Value) when is_float(Value) -> io_lib:format("~.4f", [Value]); get_stat_v2(Value) when is_integer(Value) -> [Str] = io_lib:format("~p", [Value]), pretty_string_int(Str); get_stat_v2(Value) -> io_lib:format("~p", [Value]). %% Transform "1234567890" into "1,234,567,890" pretty_string_int(String) -> {_, Result} = lists:foldl( fun(NewNumber, {3, Result}) -> {1, [NewNumber, $, | Result]}; (NewNumber, {CountAcc, Result}) -> {CountAcc+1, [NewNumber | Result]} end, {0, ""}, lists:reverse(String)), Result. %%%================================== %%%% Commands commands() -> [ #ejabberd_commands{name = get_top_users, tags = [stats], desc = "Get top X users with larger offlinemsg, vcard or roster.", policy = admin, module = ?MODULE, function = get_top_users, args = [{topnumber, integer}, {topic, string}], result = {top, {list, {user, {tuple, [ {value, integer}, {user, string}, {server, string} ]}} }}}, #ejabberd_commands{name = getstatsdx, tags = [stats], desc = "Get statistical value.", policy = admin, module = ?MODULE, function = getstatsdx, args = [{name, string}], result = {stat, integer}}, #ejabberd_commands{name = getstatsdx_host, tags = [stats], desc = "Get statistical value for this host.", policy = admin, module = ?MODULE, function = getstatsdx, args = [{name, string}, {host, string}], result = {stat, integer}} ]. getstatsdx(Name) -> get_statistic(global, [Name]). getstatsdx(Name, Host) -> get_statistic(global, [Name, Host]). get_top_users(Number, Topic) -> get_top_users(server, Number, Topic). %% Returns: [{Integer, User, Server}] get_top_users(Host, Number, <<"vcard">>) -> get_top_users_vcard(Host, Number); get_top_users(Host, Number, <<"offlinemsg">>) -> get_top_users(Host, Number, offline_msg, #offline_msg.us); get_top_users(Host, Number, <<"roster">>) -> get_top_users(Host, Number, roster, #roster.us). get_top_users(Host, TopX, Table, RecordUserPos) -> F = fun() -> F2 = fun(R, {H, Dict}) -> {LUser, LServer} = element(RecordUserPos, R), case H of server -> {Host, dict:update_counter({LUser, LServer}, 1, Dict)}; LServer -> {Host, dict:update_counter({LUser, LServer}, 1, Dict)}; _ -> {Host, Dict} end end, mnesia:foldl(F2, {Host, dict:new()}, Table) end, {atomic, {Host, DictRes}} = mnesia:transaction(F), {_, _, Result} = dict:fold( fun({User, Server}, Num, {EntryNumber, Size, TopList}) -> case {Num > EntryNumber, Size < TopX} of {false, true} -> {Num, Size+1, lists:keymerge(1, TopList, [{Num, User, Server}])}; {true, true} -> {EntryNumber, Size+1, lists:keymerge(1, TopList, [{Num, User, Server}])}; {true, false} -> [{NewEntryNumber, _, _} | _] = TopList2 = lists:keydelete(EntryNumber, 1, TopList), {NewEntryNumber, Size, lists:keymerge(1, TopList2, [{Num, User, Server}])}; {false, false} -> {EntryNumber, Size, TopList} end end, {10000000000000000, 0, []}, DictRes), lists:reverse(Result). get_top_users_vcard(Host, Number) -> F = fun() -> B = fun get_users_vcard_fun/2, {_Host, _NumSelects, _MinSize, _Sizes, Selects} = mnesia:foldl(B, {Host, Number, -1, [], []}, vcard), %+++ Selects end, {atomic, Result} = mnesia:transaction(F), lists:reverse(Result). %% Selects = [{Size, Vcard}] sorted from smaller to larger get_users_vcard_fun(#vcard{us = {_, Host1}}, {HostReq, NumRemaining, MinSize, Sizes, Selects}) when (Host1 /= HostReq) and (HostReq /= server) -> {HostReq, NumRemaining, MinSize, Sizes, Selects}; get_users_vcard_fun(Vcard, {HostReq, NumRemaining, MinSize, Sizes, Selects}) -> Binary = fxml:element_to_binary(Vcard#vcard.vcard), Size = byte_size(Binary), case {Size > MinSize, NumRemaining > 0} of {true, true} -> {User, Host} = Vcard#vcard.us, Selects2 = lists:umerge(Selects, [{Size, User, Host}]), Sizes2 = lists:umerge(Sizes, [Size]), MinSize2 = lists:min(Sizes2), {HostReq, NumRemaining-1, MinSize2, Sizes2, Selects2}; {true, false} -> [_ | SelectsReduced] = Selects, [_ | SizesReduced] = Sizes, Sizes2 = lists:umerge(SizesReduced, [Size]), MinSize2 = lists:min(Sizes2), {User, Host} = Vcard#vcard.us, Selects2 = lists:umerge(SelectsReduced, [{Size, User, Host}]), {HostReq, NumRemaining, MinSize2, Sizes2, Selects2}; {false, _} -> {HostReq, NumRemaining, MinSize, Sizes, Selects} end. %%%================================== %%% vim: set foldmethod=marker foldmarker=%%%%,%%%=: tmpcma5cyg4/mod_statsdx/src/mod_stats2file.erl0000644000232200023220000002332314516675355022350 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : mod_stats2file.erl %%% Author : Badlop %%% Purpose : Generates files with all kind of statistics %%% Created : %%% Id : $Id: mod_stats2file.erl 440 2007-12-06 22:36:21Z badlop $ %%%---------------------------------------------------------------------- -module(mod_stats2file). -author('badlop@ono.com'). -behaviour(gen_mod). -export([start/2, stop/1, depends/2, mod_opt_type/1, mod_options/1, mod_doc/0]). -export([loop/5]). -include_lib("xmpp/include/xmpp.hrl"). -include("mod_roster.hrl"). -define(PROCNAME, ejabberd_mod_stats2file). -define(T(Text), translate:translate("Lang", Text)). %% ------------------- %% Module control %% ------------------- start(_Host, Opts) -> case whereis(?PROCNAME) of undefined -> Interval = gen_mod:get_opt(interval, Opts), I = Interval*60*1000, %I = 9000, %+++ Type = gen_mod:get_opt(type, Opts), Split = gen_mod:get_opt(split, Opts), BaseFilename = gen_mod:get_opt(basefilename, Opts), Hosts = gen_mod:get_opt(hosts, Opts), register(?PROCNAME, spawn(?MODULE, loop, [I, Hosts, BaseFilename, Type, Split])); _ -> ok end, ok. loop(I, Hs, O, T, Split) -> write_statsfiles(Split, I, Hs, O, T), timer:send_after(I, stats), receive stats -> ?MODULE:loop(I, Hs, O, T, Split); stop -> ok end. stop(_Host) -> case whereis(?PROCNAME) of undefined -> ok; _ -> ?PROCNAME ! stop end. depends(_Host, _Opts) -> [{mod_statsdx, hard}]. mod_opt_type(interval) -> econf:pos_int(); mod_opt_type(type) -> econf:enum([html, txt, dat]); mod_opt_type(split) -> econf:bool(); mod_opt_type(basefilename) -> econf:string(); mod_opt_type(hosts) -> econf:list(econf:domain()). mod_options(_Host) -> [{interval, 5}, {type, html}, {split, false}, {basefilename, "/tmp/ejasta"}, {hosts, ejabberd_config:get_option(hosts)}]. mod_doc() -> #{}. %% ------------------- %% write_stat* %% ------------------- write_statsfiles(false, I, Hs, O, T) -> Fn = filename:flatten([O, ".", T]), {ok, F} = file:open(Fn, [write]), fwini(F, T), write_stats(I, server, "", F, T), fwbr(F, T), fwbr(F, T), Node = node(), write_stats(I, node, Node, F, T), lists:foreach( fun(H) -> fwbr(F, T), fwbr(F, T), write_stats(I, vhost, H, F, T) end, Hs), fwend(F, T), file:close(F); write_statsfiles(true, I, Hs, O, T) -> write_statsfile(I, server, "", O, T), Node = node(), write_statsfile(I, node, Node, O, T), lists:foreach( fun(H) -> write_statsfile(I, vhost, H, O, T) end, Hs). write_statsfile(I, Class, Name, O, T) -> Fn = filename:flatten([O, "-", Class, "-", to_string(Name), ".", T]), {ok, F} = file:open(Fn, [write]), fwini(F, T), write_stats(I, Class, Name, F, T), fwend(F, T), file:close(F). to_string(B) when is_binary(B) -> binary_to_list(B); to_string(S) -> S. write_stats(I, server, _Name, F, T) -> fwh(F, "Server statistics", 1, T), fwbl1(F, T), fwtstl(F, "localtime", T), fwh(F, "Accounts", 2, T), fwbl1(F, T), fwttl(F, "registeredusers", T), fwbl2(F, T), fwh(F, "Roster", 2, T), fwbl1(F, T), fwttl(F, "totalrosteritems", T), fwttl(F, "meanitemsinroster", T), fwbl2(F, T), fwh(F, "Users", 2, T), fwbl1(F, T), fwttl(F, "onlineusers", T), fwttl(F, "offlinemsg", T), fwttl(F, "vcards", T), fwbl2(F, T), fwh(F, "MUC", 2, T), fwbl1(F, T), fwttl(F, "totalmucrooms", T), fwttl(F, "permmucrooms", T), fwttl(F, "regmucrooms", T), fwbl2(F, T), fwh(F, "Pub/Sub", 2, T), fwbl1(F, T), fwttl(F, "regpubsubnodes", T), fwbl2(F, T), %fwh(F, "IRC", 2, T), %fwbl1(F, T), %fwttl(F, "ircconns", T), %fwbl2(F, T), fwh(F, "Ratios", 2, T), fwbl1(F, T), fwttl(F, {"user_login", I}, server, T), fwttl(F, {"user_logout", I}, server, T), fwttl(F, {"remove_user", I}, server, T), fwbl2(F, T), fwh(F, "Sessions", 2, T), fwbl1(F, T), fwh(F, "Clients", 3, T), fwbl1(F, T), do_stat_table(F, "client", server, T), fwbl2(F, T), fwh(F, "OS", 3, T), fwbl1(F, T), do_stat_table(F, "os", server, T), fwbl2(F, T), case T of html -> fwh(F, "Client/OS", 3, T), fwbl1(F, T), do_stat_table(F, "client_os", server, T), fwbl2(F, T), fwh(F, "Languages", 3, T), fwbl1(F, T), do_stat_table(F, "languages", server, T), fwbl2(F, T), fwbl2(F, T); _ -> ok end, fwbl2(F, T); write_stats(I, node, Node, F, T) -> fwh(F, "Node statistics", 1, T), fwbl1(F, T), fwt(F, "Node", Node, T), fwh(F, "Connections", 2, T), fwbl1(F, T), %fwttl(F, "plainusers", T), %fwttl(F, "sslusers", T), %fwttl(F, "tlsusers", T), fwttl(F, "httpbindusers", T), fwttl(F, "s2sconnections", T), fwttl(F, "s2sservers", T), fwbl2(F, T), fwh(F, "Erlang", 2, T), fwbl1(F, T), fwttl(F, "operatingsystem", T), fwttl(F, "erlangmachine", T), fwttl(F, "erlangmachinetarget", T), fwttl(F, "maxprocallowed", T), fwttl(F, "totalerlproc", T), fwttl(F, "procqueue", T), fwbl2(F, T), fwh(F, "Times", 2, T), fwbl1(F, T), %fwttl(F, "uptimehuman", T), %fwttl(F, "lastrestart", T), fwbr(F, T), CPUTime = element(1, rpc:call(Node, erlang, statistics, [runtime])), fw(F, "~s (ms): ~w",["CPUtime", CPUTime]), fwbr(F, T), MT = trunc(erlang:memory(total)/1024), fwt(F, "Memory VM (KB)", MT, T), fwbl2(F, T), fwh(F, "CPU", 2, T), fwbl1(F, T), fwttl(F, "cpu_avg1", T), fwttl(F, "cpu_avg5", T), fwttl(F, "cpu_avg15", T), fwttl(F, "cpu_nprocs", T), U = cpu_sup:util([detailed]), fwttl(F, {"cpu_util_user", U}, T), fwttl(F, {"cpu_util_nice_user", U}, T), fwttl(F, {"cpu_util_kernel", U}, T), fwttl(F, {"cpu_util_idle", U}, T), fwttl(F, {"cpu_util_wait", U}, T), fwbl2(F, T), fwh(F, "RAM", 2, T), fwbl1(F, T), M = memsup:get_system_memory_data(), fwttl(F, {"memsup_system", M}, T), fwttl(F, {"memsup_free", M}, T), fwttl(F, {"reductions", I}, T), fwbl2(F, T), fwbl2(F, T); write_stats(I, vhost, Host, F, T) -> fwh(F, "Host statistics", 1, T), fwbl1(F, T), fwtstl(F, "vhost", Host, T), fwh(F, "Accounts", 2, T), fwbl1(F, T), fwttl(F, "registeredusers", Host, T), fwbl2(F, T), fwh(F, "Roster", 2, T), fwbl1(F, T), fwttl(F, "totalrosteritems", Host, T), fwttl(F, "meanitemsinroster", Host, T), fwbl2(F, T), fwh(F, "Users", 2, T), fwbl1(F, T), fwttl(F, "onlineusers", Host, T), fwttl(F, "offlinemsg", Host, T), fwttl(F, "vcards", Host, T), fwbl2(F, T), fwh(F, "Connections", 2, T), fwbl1(F, T), fwttl(F, "s2sconnections", Host, T), fwbl2(F, T), fwh(F, "MUC", 2, T), fwbl1(F, T), fwttl(F, "totalmucrooms", Host, T), fwttl(F, "permmucrooms", Host, T), fwttl(F, "regmucrooms", Host, T), fwbl2(F, T), %fwh(F, "IRC", 2, T), %fwbl1(F, T), %fwttl(F, "ircconns", Host, T), %fwbl2(F, T), fwh(F, "Sessions", 2, T), fwbl1(F, T), fwh(F, "Clients", 3, T), fwbl1(F, T), do_stat_table(F, "client", Host, T), fwbl2(F, T), fwh(F, "OS", 3, T), fwbl1(F, T), do_stat_table(F, "os", Host, T), fwbl2(F, T), case T of html -> fwh(F, "Client/OS", 3, T), fwbl1(F, T), do_stat_table(F, "client_os", Host, T), fwbl2(F, T), fwh(F, "Languages", 3, T), fwbl1(F, T), do_stat_table(F, "languages", Host, T), fwbl2(F, T), fwbl2(F, T); _ -> ok end, fwh(F, "Ratios", 2, T), fwbl1(F, T), fwttl(F, {"user_login", I}, Host, T), fwttl(F, {"user_logout", I}, Host, T), fwttl(F, {"remove_user", I}, Host, T), fwttl(F, {send, iq, in, I}, Host, T), fwttl(F, {send, iq, out, I}, Host, T), fwttl(F, {send, message, in, I}, Host, T), fwttl(F, {send, message, out, I}, Host, T), fwttl(F, {send, presence, in, I}, Host, T), fwttl(F, {send, presence, out, I}, Host, T), fwttl(F, {recv, iq, in, I}, Host, T), fwttl(F, {recv, iq, out, I}, Host, T), fwttl(F, {recv, message, in, I}, Host, T), fwttl(F, {recv, message, out, I}, Host, T), fwttl(F, {recv, presence, in, I}, Host, T), fwttl(F, {recv, presence, out, I}, Host, T), fwbl2(F, T), fwbl2(F, T). %% ------------------- %% get(* %% ------------------- fwttl(F, Arg, T) -> fwt(F, gett(Arg), getl(Arg), T). fwttl(F, Arg, Host, T) -> fwt(F, gett(Arg), getl(Arg, Host), T). fwtstl(F, Arg, T) -> fwts(F, gett(Arg), getl(Arg), T). fwtstl(F, Arg, Host, T) -> fwts(F, gett(Arg), getl(Arg, Host), T). gett(Arg) -> get(node(), [Arg, title]). getl(Args) -> get(node(), [Args]). getl(Args, Host) -> get(node(), [Args, Host]). get(Node, A) -> mod_statsdx:get_statistic(Node, A). %% ------------------- %% utilities %% ------------------- fw(F, S) -> file:write(F, S). fw(F, S, O) -> file:write(F, io_lib:format(S, O)). fwt(F, S, O, html) -> fw(F, "~s: ~p
~n",[S, O]); fwt(F, S, O, txt) -> fw(F, "~s: ~p~n",[S, O]); fwt(F, _, O, dat) -> fw(F, "~p~n",[O]). fwts(F, S, O, html) -> fw(F, "~s: ~s
~n",[S, O]); fwts(F, S, O, txt) -> fw(F, "~s: ~s~n",[S, O]); fwts(F, _, O, dat) -> fw(F, "~s~n",[O]). %fwtsn(F, S, O, html) -> fw(F, "~s: ~s
",[?T(S), O]); %fwtsn(F, S, O, txt) -> fw(F, "~s: ~s",[?T(S), O]); %fwtsn(F, _, O, dat) -> fw(F, "~s",[O]). fwh(F, S, N, html) -> fw(F, "~s~n",[N, S, N]); fwh(F, S, 1, txt) -> fw(F, " ===== ~s =====~n",[S]); fwh(F, S, 2, txt) -> fw(F, "~n --- ~s ---~n",[S]); fwh(F, S, 3, txt) -> fw(F, "~n + ~s +~n",[S]); fwh(_, _, _, dat) -> ok. fwbr(F, html) -> fw(F, "
\n"); fwbr(F, txt) -> fw(F, "\n"); fwbr(_, dat) -> ok. fwini(F, html) -> fw(F, "\n"); fwini(_, txt) -> ok; fwini(_, dat) -> ok. fwend(F, html) -> fw(F, "\n"); fwend(_, txt) -> ok; fwend(_, dat) -> ok. fwbl1(F, html) -> fw(F, "
\n"); fwbl1(_, txt) -> ok; fwbl1(_, dat) -> ok. fwbl2(F, html) -> fw(F, "
\n"); fwbl2(_, txt) -> ok; fwbl2(_, dat) -> ok. do_stat_table(F, Stat, Host, T) -> do_stat_table(F, Stat, Host, T, unknown). do_stat_table(F, Stat, Host, T, _Lang) -> lists:map( fun({Name, Value}) -> fwts(F, Name, io_lib:format("~p", [Value]), T) end, mod_statsdx:get_statistic(global, [Stat, Host]) ). tmpcma5cyg4/mod_statsdx/COPYING0000644000232200023220000004332414516675355017174 0ustar debalancedebalanceAs a special exception, the authors give permission to link this program with the OpenSSL library and distribute the resulting binary. GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. tmpcma5cyg4/mod_filter/0000755000232200023220000000000014516675355015726 5ustar debalancedebalancetmpcma5cyg4/mod_filter/README.md0000644000232200023220000001013114516675355017201 0ustar debalancedebalancemod_filter - Flexible Filtering by Server Policy ================================================ * Author: Magnus Henoch * Copyright (C) 2005 Magnus Henoch This module allows the admin to specify packet filtering rules using ACL and ACCESS. ejabberd Patch -------------- Since ejabberd 19.08, it is necessary to apply a small patch to ejabberd source code in order to use complex `access_rules` configurations, like the ones shown in examples 1, 2, 3, 4... So, apply this patch your ejabberd source code. As you can see, it only adds a line. Then recompile ejabberd, reinstall and restart it: ```diff diff --git a/src/acl.erl b/src/acl.erl index d13c05601..c2a72fd9f 100644 --- a/src/acl.erl +++ b/src/acl.erl @@ -310,6 +310,7 @@ access_rules_validator() -> econf:non_empty( econf:options( #{allow => access_validator(), + '_' => access_validator(), deny => access_validator()}, []))). -- ``` Configuration ------------- You can modify the default module configuration file like this: To enable the module: ```yaml modules: mod_filter: {} ``` And you must also add the default access rules: ```yaml access_rules: mod_filter: - allow: all mod_filter_presence: - allow: all mod_filter_message: - allow: all mod_filter_iq: - allow: all ``` The configuration of rules is done using ejabberd's ACL and ACCESS, so you should also study the corresponding section on ejabberd guide. You can find here several examples that may help you to understand how it works. Example 1 --------- ```yaml access_rules: mod_filter_presence: - allow: all mod_filter_message: - allow: all mod_filter_iq: - allow: all ## Admins can send anything. Others are restricted in various ways. mod_filter: - allow: admin - restrict_local: local - restrict_foreign: all ## Local non-admin users can only send messages to other local users. restrict_local: - allow: local - deny: all ## Foreign users can only send messages to admins. restrict_foreign: - allow: admin - deny: all ``` Example 2 --------- On this example, the users of a private vhost (`example3.org`) can only chat with themselves, so that particular vhost will have no connection to the exterior. The other vhosts on the server are completely unrestricted. The administrators are also unrestricted. ```yaml ## This ejabberd server has three virtual hosts hosts: - "localhost" - "example1.org" - "example2.org" - "example3.org" ## This ACL will match any user or service (MUC, PubSub...) hosted on example3.org acl: ex3server: server_glob: - "*example3.org" access_rules: mod_filter_presence: - allow: all mod_filter_message: - allow: all mod_filter_iq: - allow: all ## The main mod_filter rule allows any admin, but restricts example3 and the rest of packets mod_filter: - allow: admin - restrict_ex3: ex3server - restrict_nonex3: all ## This rule, which applies to packets sent from Ex3 non-admin users, ## allows packets sent to Ex3 server (packets internal to the vhost) and denies anything else. restrict_ex3: - allow: ex3server - deny: all ## This rule, which applies to the rest of packets (the ones that are not sent from Ex3), ## allows all packets to admins (allowing replies to stanzas from Ex3 admins), ## denies all other access to Ex3, and allows access to anything else. restrict_nonex3: - allow: admin - deny: ex3server - allow: all ``` Example 4 --------- This server has two virtual hosts, one with anonymous users. The anonymous users cannot send or receive presence stanzas from outside their vhost. ```yaml hosts: - "localhost" - "anon.localhost.org" acl: anon_user: server_glob: - "*anon.localhost" access_rules: mod_filter: - allow: all mod_filter_presence: - allow: admin - restrict_anon: anon_user - restrict_non_anon: all restrict_anon: - allow: anon_user - deny: all restrict_non_anon: - allow: admin - deny: anon_user - allow: all mod_filter_message: - allow: all mod_filter_iq: - allow: all ``` tmpcma5cyg4/mod_filter/mod_filter.spec0000644000232200023220000000035414516675355020730 0ustar debalancedebalanceauthor: "Magnus Henoch " category: "data" summary: "Flexible filtering by server policy" home: "https://github.com/processone/ejabberd-contrib/tree/master/" url: "git@github.com:processone/ejabberd-contrib.git" tmpcma5cyg4/mod_filter/conf/0000755000232200023220000000000014516675355016653 5ustar debalancedebalancetmpcma5cyg4/mod_filter/conf/mod_filter.yml0000644000232200023220000000030414516675355021517 0ustar debalancedebalance#modules: # mod_filter: {} #access_rules: # mod_filter: # - allow: all # mod_filter_presence: # - allow: all # mod_filter_message: # - allow: all # mod_filter_iq: # - allow: all tmpcma5cyg4/mod_filter/src/0000755000232200023220000000000014516675355016515 5ustar debalancedebalancetmpcma5cyg4/mod_filter/src/mod_filter.erl0000644000232200023220000000576714516675355021364 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : mod_filter.erl %%% Author : Magnus Henoch %%% Purpose : flexible filtering by server policy %%% Created : 21 Sep 2005 by Magnus Henoch %%%---------------------------------------------------------------------- -module(mod_filter). -author('henoch@dtek.chalmers.se'). -behaviour(gen_mod). -export([start/2, stop/1, depends/2, mod_options/1, filter_packet/1, mod_doc/0]). -include("logger.hrl"). -include_lib("xmpp/include/xmpp.hrl"). -dialyzer({no_match, [check_stanza_type/2, check_access/1]}). start(_Host, _Opts) -> ejabberd_hooks:add(filter_packet, global, ?MODULE, filter_packet, 100). stop(_Host) -> ejabberd_hooks:delete(filter_packet, global, ?MODULE, filter_packet, 100). %% Return drop to drop the packet, or the original input to let it through. %% From and To are jid records. filter_packet(drop) -> drop; filter_packet(Packet) -> From = xmpp:get_from(Packet), To = xmpp:get_to(Packet), %% It probably doesn't make any sense to block packets to oneself. R = if From#jid.luser == To#jid.luser, From#jid.lserver == To#jid.lserver -> Packet; true -> check_stanza(Packet) end, ?DEBUG("filtering packet...~nFrom: ~p~nTo: ~p~nPacket: ~p~nResult: ~p", [From, To, Packet, R]), case R of {drop, _} -> drop; {drop, _, _} -> drop; _ -> R end. check_stanza(Packet) -> AccessRule = case element(1, Packet) of presence -> mod_filter_presence; message -> mod_filter_message; iq -> mod_filter_iq end, check_stanza_type(AccessRule, Packet). check_stanza_type(AccessRule, Packet) -> FromAccess = acl:match_rule(global, AccessRule, xmpp:get_from(Packet)), case FromAccess of allow -> check_access(Packet); deny -> {drop, AccessRule, sender}; ToAccessRule -> ToAccess = acl:match_rule(global, ToAccessRule, xmpp:get_to(Packet)), case ToAccess of allow -> check_access(Packet); deny -> {drop, AccessRule, receiver} end end. check_access(Packet) -> %% Beginning of a complicated ACL matching procedure. %% The access option given to the module applies to senders. %% XXX: there are no "global" module options, and we don't know %% anymore what "host" we are on. Thus hardcoding access rule. %%AccessRule = gen_mod:get_module_opt(global, ?MODULE, access, all), AccessRule = mod_filter, FromAccess = acl:match_rule(global, AccessRule, xmpp:get_from(Packet)), %% If the rule results in 'allow' or 'deny', treat that as the %% result. Else it is a rule to be applied to the receiver. case FromAccess of allow -> Packet; deny -> {drop, sender}; ToAccessRule -> ToAccess = acl:match_rule(global, ToAccessRule, xmpp:get_to(Packet)), case ToAccess of allow -> Packet; deny -> {drop, receiver} end end. depends(_Host, _Opts) -> []. mod_options(_) -> []. mod_doc() -> #{}. tmpcma5cyg4/mod_message_log/0000755000232200023220000000000014516675355016726 5ustar debalancedebalancetmpcma5cyg4/mod_message_log/README.md0000644000232200023220000000215014516675355020203 0ustar debalancedebalancemod_message_log - Log one line per message transmission ======================================================= * Author: Holger Weiss Description ----------- This module writes a line for each sent or received message to a log file. Each line mentions the sender's JID and the recipient's JID, and also the message type (e.g., `"normal"`, `"chat"`, or `"groupchat"`). Carbon copies are marked as such. The log lines look similar to this one: ``` 2014-05-25 11:55:04 [outgoing, normal] dan@example.com/Foo -> eve@example.net/Bar ``` After log rotation, you can execute the following command in order to tell `mod_message_log` to reopen the log file: ``` ejabberdctl reopen_log ``` Configuration ------------- - `filename` Define the filename and path to store the log. If the filename option is set to `auto`, it will be set to the default ejabberd log path, with the file name `"message.log"`. The filename option takes as default value `auto`. Example Configuration --------------------- ```yaml modules: mod_message_log: filename: "/path/to/ejabberd-message.log" ``` tmpcma5cyg4/mod_message_log/conf/0000755000232200023220000000000014516675355017653 5ustar debalancedebalancetmpcma5cyg4/mod_message_log/conf/mod_message_log.yml0000644000232200023220000000013614516675355023522 0ustar debalancedebalancemodules: mod_message_log: filename: auto # filename: "/var/log/ejabberd/message.log" tmpcma5cyg4/mod_message_log/src/0000755000232200023220000000000014516675355017515 5ustar debalancedebalancetmpcma5cyg4/mod_message_log/src/mod_message_log.erl0000644000232200023220000002024014516675355023343 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : mod_message_log.erl %%% Author : Holger Weiss %%% Purpose : Log one line per message transmission %%% Created : 27 May 2014 by Holger Weiss %%% %%% %%% ejabberd, Copyright (C) 2018-2020 ProcessOne %%% %%% 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. %%% %%%---------------------------------------------------------------------- -module(mod_message_log). -author('holger@zedat.fu-berlin.de'). -behaviour(gen_mod). -behaviour(gen_server). %% gen_mod callbacks. -export([start/2, stop/1, mod_opt_type/1, mod_options/1, depends/2, mod_status/0, mod_doc/0]). %% gen_server callbacks. -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). %% ejabberd_hooks callbacks. -export([log_packet_send/1, log_packet_receive/1, log_packet_offline/1, reopen_log/0]). -include_lib("xmpp/include/xmpp.hrl"). -define(FILE_MODES, [append, raw]). -record(state, {filename :: binary(), iodevice :: io:device()}). -type direction() :: incoming | outgoing | offline. -type state() :: #state{}. -type c2s_state() :: ejabberd_c2s:state(). -type c2s_hook_acc() :: {stanza() | drop, c2s_state()}. %% ------------------------------------------------------------------- %% gen_mod callbacks. %% ------------------------------------------------------------------- -spec start(binary(), gen_mod:opts()) -> ok | {ok, pid()} | {error, term()}. start(Host, Opts) -> ejabberd_hooks:add(user_send_packet, Host, ?MODULE, log_packet_send, 42), ejabberd_hooks:add(user_receive_packet, Host, ?MODULE, log_packet_receive, 42), ejabberd_hooks:add(offline_message_hook, Host, ?MODULE, log_packet_offline, 42), case gen_mod:start_child(?MODULE, <<"global">>, Opts) of {ok, Ref} -> {ok, Ref}; {error, {already_started, Ref}} -> {ok, Ref}; {error, Reason} -> {error, Reason} end. -spec stop(binary()) -> ok. stop(Host) -> ejabberd_hooks:delete(user_send_packet, Host, ?MODULE, log_packet_send, 42), ejabberd_hooks:delete(user_receive_packet, Host, ?MODULE, log_packet_receive, 42), ejabberd_hooks:delete(offline_message_hook, Host, ?MODULE, log_packet_offline, 42), gen_mod:stop_child(gen_mod:get_module_proc(global, ?MODULE)), ok. -spec mod_opt_type(atom()) -> econf:validator(). mod_opt_type(filename) -> econf:either(auto, econf:file(write)). -spec mod_options(binary()) -> [{atom(), any()}]. mod_options(_Host) -> [{filename, auto}]. -spec depends(binary(), gen_mod:opts()) -> [{module(), hard | soft}]. depends(_Host, _Opts) -> []. mod_doc() -> #{}. mod_status() -> Proc = gen_mod:get_module_proc(global, ?MODULE), {filename, Filename} = gen_server:call(Proc, get_filename, timer:seconds(15)), io_lib:format("Logging to: ~s", [Filename]). %% ------------------------------------------------------------------- %% gen_server callbacks. %% ------------------------------------------------------------------- -spec init(list()) -> {ok, state()}. init([_Host, Opts]) -> process_flag(trap_exit, true), ejabberd_hooks:add(reopen_log_hook, ?MODULE, reopen_log, 42), Filename = case gen_mod:get_opt(filename, Opts) of auto -> filename:join(filename:dirname(ejabberd_logger:get_log_path()), "message.log"); FN -> FN end, {ok, IoDevice} = file:open(Filename, ?FILE_MODES), {ok, #state{filename = Filename, iodevice = IoDevice}}. -spec handle_call(_, {pid(), _}, state()) -> {noreply, state()}. handle_call(get_filename, _From, State) -> {reply, {filename, State#state.filename}, State}; handle_call(_Request, _From, State) -> {noreply, State}. -spec handle_cast(_, state()) -> {noreply, state()}. handle_cast({message, Direction, From, To, Type}, #state{iodevice = IoDevice} = State) -> write_log(IoDevice, Direction, From, To, Type), {noreply, State}; handle_cast(reopen_log, #state{filename = Filename, iodevice = IoDevice} = State) -> ok = file:close(IoDevice), {ok, NewIoDevice} = file:open(Filename, ?FILE_MODES), {noreply, State#state{iodevice = NewIoDevice}}; handle_cast(_Request, State) -> {noreply, State}. -spec handle_info(timeout | _, state()) -> {noreply, state()}. handle_info(_Info, State) -> {noreply, State}. -spec terminate(normal | shutdown | {shutdown, _} | _, _) -> any(). terminate(_Reason, State) -> ejabberd_hooks:delete(reopen_log_hook, ?MODULE, reopen_log, 42), ok = file:close(State#state.iodevice). -spec code_change({down, _} | _, state(), _) -> {ok, state()}. code_change(_OldVsn, State, _Extra) -> {ok, State}. %% ------------------------------------------------------------------- %% ejabberd_hooks callbacks. %% ------------------------------------------------------------------- -spec log_packet_send(c2s_hook_acc()) -> c2s_hook_acc(). log_packet_send({#message{} = Msg, _C2SState} = Acc) -> log_packet(outgoing, Msg), Acc; log_packet_send({_Stanza, _C2SState} = Acc) -> Acc. -spec log_packet_receive(c2s_hook_acc()) -> c2s_hook_acc(). log_packet_receive({#message{} = Msg, _C2SState} = Acc) -> log_packet(incoming, Msg), Acc; log_packet_receive({_Stanza, _C2SState} = Acc) -> Acc. -spec log_packet_offline({any(), message()}) -> {any(), message()}. log_packet_offline({_Action, Msg} = Acc) -> log_packet(offline, Msg), Acc. -spec reopen_log() -> any(). reopen_log() -> Proc = gen_mod:get_module_proc(global, ?MODULE), gen_server:cast(Proc, reopen_log). %% ------------------------------------------------------------------- %% Internal functions. %% ------------------------------------------------------------------- -spec log_packet(direction(), message()) -> any(). log_packet(Direction, #message{from = From, to = To, type = Type} = Msg) -> case should_log(Msg) of true -> {Type1, Direction1} = case is_carbon(Msg) of {true, Direction0} -> {carbon, Direction0}; false -> {Type, Direction} end, Proc = gen_mod:get_module_proc(global, ?MODULE), gen_server:cast(Proc, {message, Direction1, From, To, Type1}); false -> ok end. -spec is_carbon(message()) -> {true, direction()} | false. is_carbon(#message{meta = #{carbon_copy := true}} = Msg) -> case xmpp:has_subtag(Msg, #carbons_sent{forwarded = #forwarded{}}) of true -> {true, outgoing}; false -> {true, incoming} end; is_carbon(_Msg) -> false. -spec should_log(message()) -> boolean(). should_log(#message{meta = #{carbon_copy := true}} = Msg) -> should_log(misc:unwrap_carbon(Msg)); should_log(#message{type = error}) -> false; should_log(#message{body = Body, sub_els = SubEls}) -> xmpp:get_text(Body) /= <<>> orelse lists:any(fun(#xmlel{name = <<"encrypted">>}) -> true; (_) -> false end, SubEls). -spec write_log(io:device(), direction(), jid(), jid(), message_type() | offline | carbon) -> ok. write_log(IoDevice, Direction, From, To, Type) -> Date = format_date(calendar:local_time()), Record = io_lib:format("~s [~s, ~s] ~s -> ~s~n", [Date, Direction, Type, jid:encode(From), jid:encode(To)]), ok = file:write(IoDevice, [Record]). -spec format_date(calendar:datetime()) -> io_lib:chars(). format_date({{Year, Month, Day}, {Hour, Minute, Second}}) -> Format = "~B-~2..0B-~2..0B ~2..0B:~2..0B:~2..0B", io_lib:format(Format, [Year, Month, Day, Hour, Minute, Second]). tmpcma5cyg4/mod_message_log/mod_message_log.spec0000644000232200023220000000037614516675355022734 0ustar debalancedebalanceauthor: "Holger Weiss " category: "log" summary: "Log one line per message transmission in text file" home: "https://github.com/processone/ejabberd-contrib/tree/master/" url: "git@github.com:processone/ejabberd-contrib.git" tmpcma5cyg4/mod_message_log/COPYING0000644000232200023220000004346414516675355017774 0ustar debalancedebalanceAs a special exception, the authors give permission to link this program with the OpenSSL library and distribute the resulting binary. 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. tmpcma5cyg4/mod_default_rooms/0000755000232200023220000000000014516675355017304 5ustar debalancedebalancetmpcma5cyg4/mod_default_rooms/README.md0000644000232200023220000000163014516675355020563 0ustar debalancedebalancemod_default_rooms - Add MUC bookmark(s) on registration ======================================================= * Author: Holger Weiss Description ----------- This module allows for specifying one or more rooms that should be bookmarked automatically on successful user registration (via `mod_register`, or, for example, `ejabberdctl register`). Configuration ------------- In order to use this module, add a configuration snippet such as the following: ```yaml modules: mod_default_rooms: rooms: - foo@conference.example.net - bar@conference.example.org ``` The configurable `mod_default_rooms` options are: - `rooms` (default: `[]`) The list of rooms users that should be auto-bookmarked on account registration. - `auto_join` (default: `true`) This option specifies whether the auto-join flag should be set for the bookmarks created on registration. tmpcma5cyg4/mod_default_rooms/mod_default_rooms.spec0000644000232200023220000000035714516675355023667 0ustar debalancedebalanceauthor: "Holger Weiss " category: "muc" summary: "Auto-bookmark rooms on registration" home: "https://github.com/processone/ejabberd-contrib/tree/master/" url: "git@github.com:processone/ejabberd-contrib.git" tmpcma5cyg4/mod_default_rooms/conf/0000755000232200023220000000000014516675355020231 5ustar debalancedebalancetmpcma5cyg4/mod_default_rooms/conf/mod_default_rooms.yml0000644000232200023220000000005714516675355024460 0ustar debalancedebalance#modules: # mod_default_rooms: # rooms: [] tmpcma5cyg4/mod_default_rooms/src/0000755000232200023220000000000014516675355020073 5ustar debalancedebalancetmpcma5cyg4/mod_default_rooms/src/mod_default_rooms.erl0000644000232200023220000000771314516675355024311 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : mod_default_rooms.erl %%% Author : Holger Weiss %%% Purpose : Auto-bookmark rooms on registration %%% Created : 27 Feb 2019 by Holger Weiss %%% %%% %%% ejabberd, Copyright (C) 2019-2020 ProcessOne %%% %%% 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. %%% %%%---------------------------------------------------------------------- -module(mod_default_rooms). -author('holger@zedat.fu-berlin.de'). -behavior(gen_mod). %% gen_mod callbacks. -export([start/2, stop/1, reload/3, mod_opt_type/1, depends/2, mod_options/1, mod_doc/0]). %% ejabberd_hooks callbacks. -export([register_user/2, set_presence/4]). -include("logger.hrl"). -include_lib("xmpp/include/xmpp.hrl"). %%-------------------------------------------------------------------- %% gen_mod callbacks. %%-------------------------------------------------------------------- -spec start(binary(), gen_mod:opts()) -> ok. start(Host, _Opts) -> ejabberd_hooks:add(set_presence_hook, Host, ?MODULE, set_presence, 50), ejabberd_hooks:add(register_user, Host, ?MODULE, register_user, 50). -spec stop(binary()) -> ok. stop(Host) -> ejabberd_hooks:delete(set_presence_hook, Host, ?MODULE, set_presence, 50), ejabberd_hooks:delete(register_user, Host, ?MODULE, register_user, 50). -spec reload(binary(), gen_mod:opts(), gen_mod:opts()) -> ok. reload(_Host, _NewOpts, _OldOpts) -> ok. -spec mod_opt_type(atom()) -> econf:validator(). mod_opt_type(auto_join) -> econf:bool(); mod_opt_type(rooms) -> econf:list(econf:jid(), [unique]). -spec mod_options(binary()) -> [{atom(), any()}]. mod_options(_Host) -> [{auto_join, true}, {rooms, []}]. -spec depends(binary(), gen_mod:opts()) -> [{module(), hard | soft}]. depends(_Host, _Opts) -> [{mod_private, hard}]. mod_doc() -> #{}. %%-------------------------------------------------------------------- %% ejabberd_hooks callbacks. %%-------------------------------------------------------------------- -spec set_presence(binary(), binary(), binary(), binary()) -> ok | {error, _}. set_presence(LUser, LServer, _Resource, _Presence) -> case ejabberd_auth:store_type(LServer) of external -> case mod_private:get_data(LUser, LServer) of [] -> register_user(LUser, LServer); _ -> ok end; _ -> ok end. -spec register_user(binary(), binary()) -> ok | {error, _}. register_user(LUser, LServer) -> JID = jid:make(LUser, LServer), Rooms = gen_mod:get_module_opt(LServer, ?MODULE, rooms), AutoJoin = gen_mod:get_module_opt(LServer, ?MODULE, auto_join), Bookmarks = [build_bookmark(Room, AutoJoin) || Room <- Rooms], BookmarkStorage = #bookmark_storage{conference = Bookmarks}, Data = [{?NS_STORAGE_BOOKMARKS, xmpp:encode(BookmarkStorage)}], ?DEBUG("Auto-creating bookmarks for ~s@~s", [LUser, LServer]), mod_private:set_data(JID, Data). %%-------------------------------------------------------------------- %% Internal functions. %%-------------------------------------------------------------------- -spec build_bookmark(jid(), boolean()) -> bookmark_conference(). build_bookmark(Room, AutoJoin) -> #bookmark_conference{jid = Room, autojoin = AutoJoin}. tmpcma5cyg4/mod_default_rooms/COPYING0000644000232200023220000004346414516675355020352 0ustar debalancedebalanceAs a special exception, the authors give permission to link this program with the OpenSSL library and distribute the resulting binary. 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. tmpcma5cyg4/mod_push_offline/0000755000232200023220000000000014516675355017122 5ustar debalancedebalancetmpcma5cyg4/mod_push_offline/README.md0000644000232200023220000001133714516675355020406 0ustar debalancedebalancemod_push_offline - Send offline messages to a component ======================================================= * Requires: ejabberd 22.05 or higher * Author: Mujtaba Roohani * Copyright (C) 2022 Mujtaba Roohani This is an ejabberd module that sends all messages sent to an offline entity to the specified [component](https://xmpp.org/extensions/xep-0114.html). It is a small modification of `mod_push`, customized for development of advanced push notification services. This module can be used as a substitute to [mod_http_offline](https://github.com/raelmax/mod_http_offline/tree/master/) and mod_push if one wants to receive the complete stanza sent to offline entity instead of only the sender and body of the message. Configuration ------------- Configurable options: - `host`: This option defines the host to receive offline messages from the service. If the 'host' option is not specified, the host will be the hostname of the virtual host with the prefix "push.". Example Configuration --------------------- You can modify the default module configuration file like this: To enable the module: ```yaml modules: mod_push_offline: host: "push.localhost" ``` To enable the HTTP request handler in the listen section: ```yaml listen: - port: 5347 module: ejabberd_service access: all shaper_rule: fast ip: "::" hosts: "push.localhost": password: "Secret" ``` With that configuration, you can connect a [component](https://xmpp.org/extensions/xep-0114.html) to ejabberd with following credentials to receive offline messages: - domain: `push.localhost` - password: `Secret` Example Flow ----------------- When juliet sends a message to romeo who is unavailable: ``` Wherefore art thou, Romeo? ``` ejabberd.log shows those messages: ``` 2022-10-10 12:40:25.261336+05:00 [debug] <0.559.0>@ejabberd_hooks:safe_apply/4:315 Running hook offline_message_hook: mod_push_modified:offline_message/1 2022-10-10 12:40:25.261496+05:00 [debug] <0.559.0>@mod_push_modified:offline_message/1:79 Notifying romeo@localhost of offline message 2022-10-10 12:40:25.263651+05:00 [debug] <0.559.0>@ejabberd_router:do_route/1:384 Route: #message{ id = <<"9202008986926435556">>,type = normal,lang = <<>>, from = #jid{ user = <<"romeo">>,server = <<"localhost">>,resource = <<>>, luser = <<"romeo">>,lserver = <<"localhost">>, lresource = <<>>}, to = #jid{ user = <<>>,server = <<"push.localhost">>,resource = <<>>, luser = <<>>,lserver = <<"push.localhost">>,lresource = <<>>}, subject = [],body = [],thread = undefined, sub_els = [#ps_event{ items = #ps_items{ xmlns = <<>>,node = <<"urn:xmpp:push:nodes:messages">>, items = [#ps_item{ xmlns = <<>>,id = <<"9202008986926435556">>, sub_els = [#message{ id = <<"98b12ff6-f196-487d-99f3-08c9406474db">>,type = chat, lang = <<"en">>, from = #jid{ user = <<"juliet">>,server = <<"localhost">>, resource = <<"balcony">>,luser = <<"juliet">>, lserver = <<"localhost">>,lresource = <<"balcony">>}, to = #jid{ user = <<"romeo">>,server = <<"localhost">>, resource = <<>>,luser = <<"romeo">>, lserver = <<"localhost">>,lresource = <<>>}, subject = [], body = [#text{lang = <<>>,data = <<"Wherefore art thou, Romeo?">>}], thread = undefined, sub_els = [], meta = #{ip => {0,0,0,0,0,0,0,1}}}], node = <<>>,publisher = <<>>}], max_items = undefined,subid = <<>>,retract = undefined}, purge = undefined,subscription = undefined,delete = undefined, create = undefined,configuration = undefined}], meta = #{}} 2022-10-10 12:40:25.263991+05:00 [notice] <0.552.0> (tcp|<0.552.0>) Send XML on stream = <<"Wherefore art thou, Romeo?">> ``` If the component push.localhost is connected, it will receive this message: ``` Wherefore art thou, Romeo? ``` tmpcma5cyg4/mod_push_offline/mod_push_offline.spec0000644000232200023220000000036414516675355023321 0ustar debalancedebalanceauthor: "Mujtaba Roohani " category: "data" summary: "Send offline messages to a component" home: "https://github.com/processone/ejabberd-contrib/tree/master/" url: "git@github.com:processone/ejabberd-contrib.git" tmpcma5cyg4/mod_push_offline/conf/0000755000232200023220000000000014516675355020047 5ustar debalancedebalancetmpcma5cyg4/mod_push_offline/conf/mod_push_offline.yml0000644000232200023220000000003714516675355024112 0ustar debalancedebalancemodules: mod_push_offline: {}tmpcma5cyg4/mod_push_offline/src/0000755000232200023220000000000014516675355017711 5ustar debalancedebalancetmpcma5cyg4/mod_push_offline/src/mod_push_offline_opt.erl0000644000232200023220000000037114516675355024620 0ustar debalancedebalance-module(mod_push_offline_opt). -export([host/1]). -spec host(gen_mod:opts() | global | binary()) -> binary(). host(Opts) when is_map(Opts) -> gen_mod:get_opt(host, Opts); host(Host) -> gen_mod:get_module_opt(Host, mod_push_offline, host). tmpcma5cyg4/mod_push_offline/src/mod_push_offline.erl0000644000232200023220000001220314516675355023733 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : mod_push_offline.erl %%% Author : Mujtaba Roohani %%% Purpose : Send offline messages to a component %%% %%% Copyright (C) 2022 Mujtaba Roohani %%% %%% 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 3 of the License, or %%% (at your option) any later version. %%% %%% This program is distributed in the hope that it will be useful, %%% but WITHOUT ANY WARRANTY; without even the implied warranty of %%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the %%% GNU General Public License for more details. %%% %%% You should have received a copy of the GNU General Public License %%% along with this program. If not, see %%%---------------------------------------------------------------------- -module(mod_push_offline). -author('mujtaba.roohani@gmail.com'). -behaviour(gen_mod). %% gen_mod callbacks. -export([start/2, stop/1, reload/3, mod_opt_type/1, mod_options/1, depends/2]). -export([mod_doc/0]). %% ejabberd_hooks callbacks. -export([offline_message/1]). -include("logger.hrl"). -include_lib("xmpp/include/xmpp.hrl"). -include("translate.hrl"). %%-------------------------------------------------------------------- %% gen_mod callbacks. %%-------------------------------------------------------------------- -spec start(binary(), gen_mod:opts()) -> ok. start(Host, _) -> register_hooks(Host). -spec stop(binary()) -> ok. stop(Host) -> unregister_hooks(Host). -spec reload(binary(), gen_mod:opts(), gen_mod:opts()) -> ok. reload(_, _, _) -> ok. -spec depends(binary(), gen_mod:opts()) -> [{module(), hard | soft}]. depends(_Host, _Opts) -> []. -spec mod_opt_type(atom()) -> econf:validator(). mod_opt_type(host) -> econf:host(). -spec mod_options(binary()) -> [{atom(), any()}]. mod_options(Host) -> [{host, <<"push.", Host/binary>>}]. mod_doc() -> #{desc => ?T("This is an ejabberd module that sends all messages sent to an unavailable entity to the" "specified component. It is a small modification of `mod_push`, customized" "for development of advanced push notification services."), opts => [{host, #{value => "Host", desc => ?T("This option defines the host to receive offline messages from the service. " "If the 'host' option is not specified, the host will be " "the hostname of the virtual host with the prefix \"push.\". ")}}]}. %%-------------------------------------------------------------------- %% Register/unregister hooks. %%-------------------------------------------------------------------- -spec register_hooks(binary()) -> ok. register_hooks(Host) -> ejabberd_hooks:add(offline_message_hook, Host, ?MODULE, offline_message, 55). -spec unregister_hooks(binary()) -> ok. unregister_hooks(Host) -> ejabberd_hooks:delete(offline_message_hook, Host, ?MODULE, offline_message, 55). %%-------------------------------------------------------------------- %% Hook callbacks. %%-------------------------------------------------------------------- -spec offline_message({any(), message()}) -> {any(), message()}. offline_message({offlined, #message{to = To} = Pkt} = Acc) -> ?DEBUG("Notifying ~ts of offline message", [jid:encode(To)]), notify(To, Pkt), Acc; offline_message(Acc) -> Acc. %%-------------------------------------------------------------------- %% Generate push notifications. %%-------------------------------------------------------------------- -spec notify(jid(), xmpp_element() | xmlel() | none) -> ok. notify(#jid{lserver = LServer} = To, Pkt) -> UnWrappedPkt = unwrap_message(Pkt), DelayedPkt = add_delay_info(UnWrappedPkt, LServer), Id = p1_rand:get_string(), PushServer = mod_push_offline_opt:host(LServer), WrappedPacket = wrap(DelayedPkt, <<"urn:xmpp:push:nodes:messages">>, Id), ejabberd_router:route(xmpp:set_from_to(WrappedPacket, To, jid:make(PushServer))). %%-------------------------------------------------------------------- %% Internal functions. %%-------------------------------------------------------------------- -spec unwrap_message(Stanza) -> Stanza when Stanza :: stanza() | none. unwrap_message(#message{meta = #{carbon_copy := true}} = Msg) -> misc:unwrap_carbon(Msg); unwrap_message(#message{type = normal} = Msg) -> case misc:unwrap_mucsub_message(Msg) of #message{} = InnerMsg -> InnerMsg; false -> Msg end; unwrap_message(Stanza) -> Stanza. -spec wrap(stanza(), binary(), binary()) -> message(). wrap(Packet, Node, Id) -> #message{ id = Id, sub_els = [#ps_event{ items = #ps_items{ node = Node, items = [#ps_item{ id = Id, sub_els = [Packet]}]}}]}. -spec add_delay_info(message(), binary()) -> message(). add_delay_info(Packet, LServer) -> Packet1 = xmpp:put_meta(Packet, from_offline, true), misc:add_delay_info(Packet1, jid:make(LServer), erlang:timestamp(), <<"Offline storage">>).tmpcma5cyg4/mod_push_offline/COPYING0000644000232200023220000010451514516675355020163 0ustar debalancedebalance GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. 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 them 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 prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. 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. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey 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; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If 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 convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU 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 that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. 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. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 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. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. 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 state 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 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program 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, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU 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. But first, please read . tmpcma5cyg4/mod_webpresence/0000755000232200023220000000000014516675355016743 5ustar debalancedebalancetmpcma5cyg4/mod_webpresence/README.md0000644000232200023220000001766514516675355020241 0ustar debalancedebalancemod_webpresence - Presence on the Web ===================================== * Requires: ejabberd 19.08 or higher * Authors: Igor Goryachev, Badlop, runcom * http://www.ejabberd.im/mod_webpresence Description ----------- This module allows any local user of the ejabberd server to publish his presence information in the web. This module is the succesor of Igor Goryachev's `mod_presence`. Allowed output methods are * Icons (various themes available) * Status text * Raw XML * Avatar, stored in the user's vCard No web server, database, additional libraries or programs are required. Configuration ------------- - `host` Define the hostname of the service. You can use the keyword `@HOST@`. Default value: `"webpresence.@HOST@"` - `access` Specify who can register in the webpresence service. Don't bother to specify `all` because this module can only show presence of local users. Default value: `local` - `pixmaps_path` Take special care with commas and dots: if this module does not seem to work correctly, the problem may be that the configuration file has syntax errors. Remember to put the correct path to the pixmaps directory, and make sure the user than runs ejabberd has read access to that directory. Default value: `"./pixmaps"` - `baseurl` This informational option is used only when sending a message to the user and when building the JavaScript code. It is the base part of the URL of the webpresence HTTP content. You can use the keyword `@HOST@`. If the option is not specified, it takes as default value: `http://host:52080/presence/` Example Configuration --------------------- ```yaml listen: - port: 5280 module: ejabberd_http request_handlers: "/presence": mod_webpresence modules: mod_webpresence: pixmaps_path: "/path/to/pixmaps" ``` If problems appear, remember to always look first the ejabberd log files `ejabberd.log` and `sasl.log` since they may provide some valuable information. Automatic Enable ---------------- If you want certain Jabber accounts to be automatically accepted, without requiring the user to register in the service, you can user ACL+ACCESS. The ACCESSNAME `webpresence_auto` is available for that purpose. In that case, all the output methods are enabled, the icon theme is `jsf-jabber-text` and RandomID is disabled. The default behaviour is to not have automatic webpresence: ```yaml access: webpresence_auto: all: deny ``` For example, if you want all the local users to be automatically enabled in the service: ```yaml access: webpresence_auto: local: allow ``` Note that this ACCESS rule is only checked if the user is not registered. So, if the user registers and disables all output methods, his registration prevails over your setup. If you want to ensure the users do not register and disable output methods, you can use the Access configurable parameter. Example Configuration --------------------- ## Example 1 ```yaml listen: - port: 5280 module: ejabberd_http request_handlers: "/presence": mod_webpresence modules: mod_webpresence: pixmaps_path: "/path/to/pixmaps" ``` ## Example 2 ```yaml listen: - port: 80 module: ejabberd_http request_handlers: "/status": mod_webpresence modules: mod_webpresence: host: "webstatus.@HOST@" access: local pixmaps_path: "/path/to/pixmaps" baseurl: "http://www.example.org/status/" ``` Usage ----- The web-presence feature by default is switched off for every user. If user wants to use it, he should register on service `webpresence.example.org`, which is accessible from Service Discovery. There are several switches for web-presence, but right now are all enabled and can't be disabled at all: * Jabber ID: publish the presence in URIs that use the user's Jabber ID. * Random ID: publish the presence in URIs that use a Random ID. * XML: allow XML output. * Icon: allow icon output. * Avatar: allow Avatar output. Login to an account on your ejabberd server using a powerful Jabber client. Open the Service Discovery on your Jabber client, and you should see a new service called `webpresence.example.org`. Try to register on it. A formulary appears allowing the user to allow image publishing, and XML publishing. Once you enabled some of those options, on a web browser open the corresponding URI: * for XML output: `http://example.org:5280/presence/jid///xml/` * for image output: `http://example.org:5280/presence/jid///image/` * for image output with theme: `http://example.org:5280/presence/jid///image/theme//` * for avatar output: `http://example.org:5280/presence/jid///avatar/` If you want to show the image or text outputs of a specific resource, add `/res/` to the URI: ``` http://example.org:5280/presence/jid///text/res/ http://example.org:5280/presence/jid///image/res/ http://example.org:5280/presence/jid///image/theme//res/ ``` For output types image and avatar, you can append any string to a valid URI. For example, you can use this URI: ``` http://example.org:5280/presence/jid///image/theme//myimage.jpeg ``` The response is exactly the same than the regular `image/theme//` If you don't want to reveal your Jabber ID, you can enable Random ID URI. After the registration the user gets a message with his a pseudo-random ID. The URI can be formed this way: ``` http://example.org:5280/presence/rid//image/ ``` If the user forgets his Random ID, he can get another message by just registering again, there is no need to change the values. If the user wants to get a new Random ID, he must disable Random ID in the registration form, and later enable Random ID again. A new Random ID will be generated for him. Example PHP Code ---------------- This PHP script generates HTML code. Thanks to Tobias Markmann and NoAlWin. It assumes that the URI of the presence is: ``` http://example.org:5280/presence/jid/tom/example.org ``` ```php load('http://example.org:5280/presence/jid/tom/example.org/xml'); $presences = $doc->getElementsByTagName("presence"); foreach ($presences as $presence) { echo "

"; echo ""; echo "getAttribute('server')."'>"; echo "Tobias Markmann
"; $resources = $presence->getElementsByTagName("resource"); if($resources->length == 0){ echo 'Unavailable'; }else{ foreach ($resources as $resource) { echo "getAttribute('server').'/'.$resource->getAttribute('name')."'>".$resource->getAttribute('name')." > "; switch($resource->getAttribute('show')){ case 'chat': echo 'Free for chat'; break; case 'xa': echo 'Extended away'; break; case 'dnd': echo 'Do not disturb'; break; default: echo ucfirst($resource->getAttribute('show')); } if($resource->nodeValue){ echo ": ".$resource->nodeValue; } echo "
"; } } echo "

"; } ?> ``` JavaScript Callback ------------------- The JavaScript output supports cross-site AJAX calls. Basically, it allows to tack on a callback parameter to presence requests like so: ``` http://example.org:5280/presence/jid///js?cb=doStuff ``` Which then gets fed back in the result as: ``` var jabber_resources = [...]; doStuff(); ``` The motivation for this is to work around browser restrictions in cross-site scripting. You can use it by adding a new `