tmpogm5kjkl/0000700000175000017500000000000014751665141013700 5ustar debalancedebalancetmpogm5kjkl/mod_mam_mnesia/0000775000175000017500000000000014751665140016660 5ustar debalancedebalancetmpogm5kjkl/mod_mam_mnesia/import-mam-archives0000775000175000017500000000647114751665140022502 0ustar debalancedebalance#!/usr/bin/env escript %%! -sname import@localhost % NOTE: If the node name of your server is *not* 'ejabberd@localhost' (see the % "ejabberdctl status" output), you must change the @localhost part of the node % names above and below. -define(NODE, 'ejabberd@localhost'). % Copyright (c) 2016 Holger Weiss . % % 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. -record(archive_msg, {us, id, timestamp, peer, bare_peer, packet, nick, type}). -record(mam_msg, {key, time, route, from, to, stanza}). usage(IoDevice, ExitStatus) -> ok = io:put_chars(IoDevice, "Usage: import-mam-archives [days]"), ok = io:nl(IoDevice), halt(ExitStatus). get_timestamp() -> calendar:datetime_to_gregorian_seconds(calendar:universal_time()). import(MinTS) -> TabDef = [{disc_only_copies, [?NODE]}, {type, bag}, {attributes, record_info(fields, archive_msg)}], rpc:call(?NODE, mnesia, create_table, [archive_msg, TabDef]), ImportMsg = fun(#mam_msg{key = {{U, S}, ID}, time = TS, route = Direction, from = {FromU, FromS, FromR}, to = {ToU, ToS, ToR}, stanza = Msg}, {ok, N}) when MinTS =:= undefined; TS > MinTS -> {PeerU, PeerS, PeerR} = case Direction of incoming -> {FromU, FromS, FromR}; outgoing -> {ToU, ToS, ToR} end, Record = #archive_msg{us = {U, S}, id = integer_to_binary(ID), timestamp = TS, peer = {PeerU, PeerS, PeerR}, bare_peer = {PeerU, PeerS, <<>>}, type = chat, nick = <<>>, packet = Msg}, case N rem 100 of 0 -> io:put_chars("."); _ -> ok end, {mnesia:write(Record), N + 1}; (#mam_msg{}, {ok, N}) -> {ok, N} end, ImportTab = fun() -> mnesia:foldl(ImportMsg, {ok, 0}, mam_msg) end, Start = get_timestamp(), io:put_chars("Please wait "), {ok, N} = rpc:call(?NODE, mnesia, activity, [sync_dirty, ImportTab, [], mnesia_frag]), {atomic, ok} = rpc:call(?NODE, mnesia, delete_table, [mam_msg]), {atomic, ok} = rpc:call(?NODE, mnesia, delete_table, [mam_meta]), End = get_timestamp(), io:fwrite("~nImported ~B messages in ~.1f minutes.~n", [N, (End - Start) / 60]). main(["-h"]) -> usage(standard_io, 0); main([]) -> import(undefined); main([Days]) -> Secs = try D = list_to_integer(Days), true = D > 0, true = D < 10000, D * 86400 catch _:_ -> usage(standard_error, 2) end, {MS, S, US} = os:timestamp(), CurS = MS * 1000000 + S, MinS = CurS - Secs, import({MinS div 1000000, MinS rem 1000000, US}); main(_Junk) -> usage(standard_error, 2). tmpogm5kjkl/mod_mam_mnesia/README.md0000664000175000017500000000447314751665140020147 0ustar debalancedebalancemod_mam_mnesia ============== Current Status -------------- _This module is deprecated._ ejabberd 15.06 and newer ships a `mod_mam` module which supports Mnesia and SQL/ODBC storage. It is recommended to use that module, as `mod_mam_mnesia` is no longer supported. Existing `mod_mam_mnesia` tables can be imported into `mod_mam` using the `import-mam-archives` script, as described below. Migrating to mod_mam -------------------- You might want to log off your users during the migration. However, note that importing the MAM archives might take up to a few hours. Also note that with `mod_mam`, the total size of all MAM archives cannot exceed 2 GB. The `delete_old_mam_messages` command could be run periodically to make sure the Mnesia data won't grow beyond that limit. To support larger archives, SQL/ODBC storage must be used. 1. In your ejabberd.yml file, replace `mod_mam_mnesia` with `mod_mam`, and adjust the configuration of that module. `mod_mam` supports a different set of options, so you should check [the documentation][1]. Since ejabberd 16.02, `mod_mam` supports the `request_activates_archiving` option, but it's not enabled by default. To mimic `mod_mam_mnesia`'s default behavior, you could configure `mod_mam` like this: modules: mod_mam: default: always request_activates_archiving: true 2. Check the node name of your server by running `ejabberdctl status`. If the name is _not_ `ejabberd@localhost`, you must replace the `localhost` part of the two node names at the top of the script with the host name part of your ejabberd node. 3. The `import-mam-archives` script _removes_ the `mod_mam_mnesia` tables after importing them into `mod_mam`. Therefore, **you should take a backup of your MAM archives** (and the other Mnesia data) by running a command such as: ejabberdctl dump $HOME/ejabberd-backup.dat 4. [Download][2] and run the import script: chmod +x import-mam-archives ./import-mam-archives If only the messages stored during the last `N` days should be imported, run `./import-mam-archives N` instead. 5. Restart ejabberd. [1]: https://docs.ejabberd.im/admin/guide/configuration/#modmam [2]: https://raw.githubusercontent.com/processone/ejabberd-contrib/master/mod_mam_mnesia/import-mam-archives tmpogm5kjkl/mod_log_chat/0000775000175000017500000000000014751665140016332 5ustar debalancedebalancetmpogm5kjkl/mod_log_chat/src/0000775000175000017500000000000014751665140017121 5ustar debalancedebalancetmpogm5kjkl/mod_log_chat/src/mod_log_chat.erl0000664000175000017500000002426014751665140022250 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]). tmpogm5kjkl/mod_log_chat/mod_log_chat.spec0000664000175000017500000000037014751665140021625 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" tmpogm5kjkl/mod_log_chat/TODO0000664000175000017500000000010214751665140017013 0ustar debalancedebalance - Custom templates and CSS in the configuration file - XML formattmpogm5kjkl/mod_log_chat/README.md0000664000175000017500000000062514751665140017614 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. tmpogm5kjkl/mod_log_chat/COPYING0000664000175000017500000006364214751665140017400 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! tmpogm5kjkl/mod_log_chat/conf/0000775000175000017500000000000014751665140017257 5ustar debalancedebalancetmpogm5kjkl/mod_log_chat/conf/mod_log_chat.yml0000664000175000017500000000126114751665140022421 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 tmpogm5kjkl/mod_libcluster/0000775000175000017500000000000014751665140016722 5ustar debalancedebalancetmpogm5kjkl/mod_libcluster/rebar.config0000664000175000017500000000033514751665140021205 0ustar debalancedebalance{deps, [ {jason, "1.5.0-alpha.2", {git, "https://github.com/michalmuskala/jason", {branch, "master"}}}, {libcluster, "3.3.3", {git, "https://github.com/bitwalker/libcluster", {branch, "main"}}} ]}. tmpogm5kjkl/mod_libcluster/README.md0000664000175000017500000000243214751665140020202 0ustar debalancedebalancemod_libcluster - Join nodes into cluster ======================================== Requires: - ejabberd 24.07 or higher compiled with Elixir support This small module connects this ejabberd node to other nodes using [libcluster](https://github.com/bitwalker/libcluster). Options ------- This module supports several configurable options. There are some example configuration files in the `test/` directory. Options supported by this module: * `strategy` Sets the clustering strategy to use. Supported values are: - `local_epmd`: connect to all nodes managed by the local epmd program - `epmd`: connect to the nodes you specify in the `config: hosts` option - `kubernetes` Default value: `local_epmd`. * `hosts` List of erlang node names to connect. This is required, and only useful, when using the `epmd` strategy. Default value: `[]`. * `timeut` Timeout to connect to a node, expressed in milliseconds. This is only useful when using the `epmd` strategy. Default value: `infinity`. For details of options supported please check the [libcluster documentation](https://hexdocs.pm/libcluster). Test ---- There's a test script in `test/test.sh` that you can run. It compiles ejabberd, installs in `/tmp/` several nodes, and builds a cluster using the desired strategy. tmpogm5kjkl/mod_libcluster/test/0000775000175000017500000000000014751665140017701 5ustar debalancedebalancetmpogm5kjkl/mod_libcluster/test/test.sh0000775000175000017500000000711314751665140021221 0ustar debalancedebalance#!/bin/bash COLOUR="\e[1;49;33m" NEUTRAL="\033[00m" log() { echo "" echo -e $COLOUR"==> $1"$NEUTRAL } MOD=$(pwd) TOOL=$1 STR=$2 SRC=$3 if [ -n "$TOOL" ] && [ -n "$STR" ] && [ -n "$SRC" ] ; then log "Using tool: $TOOL" log "Using strategy: $STR" log "Using ejabberd source code from: $SRC" else echo "Usage: $0 " echo " = mix | rebar3" echo " = local_epmd | epmd" echo " = path to the ejabberd source code" echo "For example: $0 mix local_epmd /home/user1/git/ejabberd/" exit 1 fi cd "$SRC" || exit 1 log "Compile ejabberd release..." compile() { ./autogen.sh ./configure \ --with-rebar=$TOOL \ --enable-all make rm _build/prod/*.tar.gz make rel } compile log "Preparing ejabberd nodes..." case "$TOOL" in mix) echo "Setting up 'mix' tool..." FILE=$(ls -1 _build/prod/*.tar.gz) ;; rebar3) echo "Setting up 'rebar3' tool..." FILE=$(ls -1 _build/prod/rel/ejabberd/*.tar.gz) ;; esac create_node() { N=$1 log "Preparing node $N using file $FILE..." rm -rf /tmp/libcluster/"$N" mkdir -p /tmp/libcluster/"$N" tar -xzf "$FILE" -C /tmp/libcluster/"$N" sed -i "s|#' POLL|EJABBERD_BYPASS_WARNINGS=true\n\n#' POLL|g" /tmp/libcluster/"$N"/conf/ejabberdctl.cfg sed -i "s|#ERLANG_NODE=.*|ERLANG_NODE=ejabberd$N@127.0.0.1|" /tmp/libcluster/"$N"/conf/ejabberdctl.cfg sed -i "s| port: \([0-9]*\)| port: \1$N|g" /tmp/libcluster/"$N"/conf/ejabberd.yml sed -i "s|mod_proxy65:|mod_proxy65:\n port: 777$N|" /tmp/libcluster/"$N"/conf/ejabberd.yml node[N]=/tmp/libcluster/"$N"/bin/ejabberdctl } create_node 1 create_node 2 create_node 3 FIRST=${node[1]} SECOND=${node[2]} THIRD=${node[3]} log "Let's start the first node..." echo "first: $FIRST" $FIRST start $FIRST started $FIRST set_master self log "Uninstall and install mod_libcluster:" $FIRST module_uninstall mod_libcluster rm -rf $MOD/deps/ rm -rf $MOD/ebin/ $FIRST module_install mod_libcluster || exit 1 log "Configure mod_libcluster:" case "$STR" in local_epmd) echo "Setting up 'local_epmd' config..." cp "$MOD"/test/local_epmd.yml \ "$HOME"/.ejabberd-modules/mod_libcluster/conf/mod_libcluster.yml ;; epmd) echo "Setting up 'epmd' config..." cp "$MOD"/test/epmd.yml \ "$HOME"/.ejabberd-modules/mod_libcluster/conf/mod_libcluster.yml ;; esac log "Initial cluster of first node (should be just this node):" $FIRST list_cluster log "Let's start the second node, it should connect automatically to the first node..." $SECOND start $SECOND started sleep 5 # wait a few seconds to let the second node join the cluster properly $SECOND set_master ejabberd1@127.0.0.1 log "Let's start the third node, it should connect automatically to the first node..." $THIRD start $THIRD started sleep 5 # wait a few seconds to let the second node join the cluster properly log "Cluster as seen by first node:" $FIRST list_cluster log "Cluster as seen by second node:" $SECOND list_cluster log "Cluster as seen by third node:" $THIRD list_cluster log "Stop first node, and check cluster as seen by second node:" $FIRST stop $FIRST stopped $SECOND list_cluster log "... as seen by third node:" $THIRD list_cluster log "Start again first node, and check cluster as seen by all the nodes:" $FIRST start $FIRST started sleep 5 echo "First: " $FIRST list_cluster echo "Second: " $SECOND list_cluster echo "Third: " $THIRD list_cluster log "Stopping all nodes..." $FIRST stop $SECOND stop $THIRD stop tmpogm5kjkl/mod_libcluster/test/local_epmd.yml0000664000175000017500000000015214751665140022521 0ustar debalancedebalancemodules: 'Ejabberd.Module.Libcluster': # Connect with any other local node strategy: local_epmd tmpogm5kjkl/mod_libcluster/test/epmd.yml0000664000175000017500000000033014751665140021345 0ustar debalancedebalancemodules: 'Ejabberd.Module.Libcluster': # Connect only to those specific nodes strategy: epmd timeout: 5000 hosts: - ejabberd1@127.0.0.1 - ejabberd2@127.0.0.1 - ejabberd3@127.0.0.1 tmpogm5kjkl/mod_libcluster/mod_libcluster.spec0000664000175000017500000000033614751665140022607 0ustar debalancedebalanceauthor: "Badlop " category: "cluster" summary: "Join nodes into cluster" home: "https://github.com/processone/ejabberd-contrib/tree/master/" url: "git@github.com:processone/ejabberd-contrib.git" tmpogm5kjkl/mod_libcluster/COPYING0000664000175000017500000004346414751665140017770 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. tmpogm5kjkl/mod_libcluster/lib/0000775000175000017500000000000014751665140017470 5ustar debalancedebalancetmpogm5kjkl/mod_libcluster/lib/mod_libcluster.ex0000664000175000017500000000317514751665140023043 0ustar debalancedebalancedefmodule Ejabberd.Module.Libcluster do @behaviour :gen_mod import Ejabberd.Logger def start(_host, opts) do strategy = case opts[:strategy] do :local_epmd -> :"Elixir.Cluster.Strategy.LocalEpmd" :epmd -> :"Elixir.Cluster.Strategy.Epmd" :kubernetes -> :"Elixir.Cluster.Strategy.Kubernetes" other_strategy -> other_strategy end info("Starting ejabberd module Libcluster with stategy #{inspect(strategy)}") config = [ hosts: opts[:hosts], timeout: opts[:timeout] ] info("Starting ejabberd module Libcluster with config #{inspect(config)}") topologies = [ ejabberd_cluster: [ strategy: strategy, config: config, connect: {:ejabberd_admin, :join_cluster, []}, disconnect: {:ejabberd_admin, :leave_cluster, []} ] ] children = [ {Cluster.Supervisor, [topologies, [name: Ejabberd.ClusterSupervisor]]}, ] Supervisor.start_link(children, strategy: :one_for_one, name: Ejabberd.Supervisor) info("Started ejabberd module Libcluster Demo") :ok end def stop(_host) do info("Stopping ejabberd module Libcluster Demo") :ok end def depends(_host, _opts) do [] end def mod_opt_type(:hosts) do :econf.list(:econf.atom) end def mod_opt_type(:strategy) do :econf.atom end def mod_opt_type(:timeout) do :econf.either(:infinity, :econf.int()); end def mod_options(_host) do [ {:hosts, []}, {:strategy, :local_epmd}, {:timeout, :infinity} ] end def mod_doc() do %{:desc => "This is just an empty string."} end end tmpogm5kjkl/mod_libcluster/conf/0000775000175000017500000000000014751665140017647 5ustar debalancedebalancetmpogm5kjkl/mod_libcluster/conf/mod_libcluster.yml0000664000175000017500000000113614751665140023402 0ustar debalancedebalance#modules: # 'Ejabberd.Module.Libcluster': # Connect with any other local node #strategy: local_epmd # Connect only to those specific nodes #strategy: epmd #config: # hosts: # - ejabberd1@127.0.0.1 # - ejabberd2@127.0.0.1 # - ejabberd3@127.0.0.1 #strategy: kubernetes #config: # mode: hostname # kubernetes_ip_lookup_mode: pods # kubernetes_namespace: "ejabberd" # kubernetes_selector: "app=ejabberd" # kubernetes_node_basename: "ejabberd" # kubernetes_service_name: "ejabberd-headless" # polling_interval: 10000 tmpogm5kjkl/mod_shcommands/0000775000175000017500000000000014751665140016706 5ustar debalancedebalancetmpogm5kjkl/mod_shcommands/src/0000775000175000017500000000000014751665140017475 5ustar debalancedebalancetmpogm5kjkl/mod_shcommands/src/mod_shcommands.erl0000664000175000017500000001726514751665140023207 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/3, web_page_node/5 % ejabberd 24.02 or older ]). -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 %%------------------- %% ejabberd 24.02 or older web_page_node(Acc, Node, Path, Query, Lang) -> web_page_node(Acc, Node, #request{method = 'GET', raw_path = <<"">>, ip = {{127,0,0,1}, 0}, sockmod = 'gen_tcp', socket = hd(erlang:ports()), path = Path, q = Query, lang = Lang}). web_page_node(_, Node, #request{path = [<<"shcommands">>], q = Query, lang = 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}. tmpogm5kjkl/mod_shcommands/README.md0000664000175000017500000000317614751665140020174 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: {} ``` tmpogm5kjkl/mod_shcommands/COPYING0000664000175000017500000004332414751665140017747 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. tmpogm5kjkl/mod_shcommands/mod_shcommands.spec0000664000175000017500000000033314751665140022554 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" tmpogm5kjkl/mod_shcommands/ChangeLog0000664000175000017500000000050414751665140020457 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. tmpogm5kjkl/mod_shcommands/conf/0000775000175000017500000000000014751665140017633 5ustar debalancedebalancetmpogm5kjkl/mod_shcommands/conf/mod_shcommands.yml0000664000175000017500000000003614751665140023350 0ustar debalancedebalancemodules: mod_shcommands: {} tmpogm5kjkl/mod_filter/0000775000175000017500000000000014751665140016037 5ustar debalancedebalancetmpogm5kjkl/mod_filter/src/0000775000175000017500000000000014751665140016626 5ustar debalancedebalancetmpogm5kjkl/mod_filter/src/mod_filter.erl0000664000175000017500000000576714751665140021475 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() -> #{}. tmpogm5kjkl/mod_filter/README.md0000664000175000017500000001013114751665140017312 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 ``` tmpogm5kjkl/mod_filter/mod_filter.spec0000664000175000017500000000035414751665140021041 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" tmpogm5kjkl/mod_filter/conf/0000775000175000017500000000000014751665140016764 5ustar debalancedebalancetmpogm5kjkl/mod_filter/conf/mod_filter.yml0000664000175000017500000000030414751665140021630 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 tmpogm5kjkl/mod_logsession/0000775000175000017500000000000014751665140016737 5ustar debalancedebalancetmpogm5kjkl/mod_logsession/src/0000775000175000017500000000000014751665140017526 5ustar debalancedebalancetmpogm5kjkl/mod_logsession/src/failed_auth.patch0000664000175000017500000000466014751665140023022 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 tmpogm5kjkl/mod_logsession/src/mod_logsession.erl0000664000175000017500000001350214751665140023257 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)]). tmpogm5kjkl/mod_logsession/README.md0000664000175000017500000000365114751665140020223 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 ``` tmpogm5kjkl/mod_logsession/mod_logsession.spec0000664000175000017500000000034214751665140022636 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" tmpogm5kjkl/mod_logsession/COPYING0000664000175000017500000004332414751665140020000 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. tmpogm5kjkl/mod_logsession/ChangeLog0000664000175000017500000000050214751665140020506 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 tmpogm5kjkl/mod_logsession/conf/0000775000175000017500000000000014751665140017664 5ustar debalancedebalancetmpogm5kjkl/mod_logsession/conf/mod_logsession.yml0000664000175000017500000000015014751665140023427 0ustar debalancedebalancemodules: mod_logsession: sessionlog: auto # sessionlog: "/var/log/ejabberd/session_@HOST@.log" tmpogm5kjkl/mod_post_log/0000775000175000017500000000000014751665140016400 5ustar debalancedebalancetmpogm5kjkl/mod_post_log/mod_post_log.spec0000664000175000017500000000033214751665140021737 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" tmpogm5kjkl/mod_post_log/src/0000775000175000017500000000000014751665140017167 5ustar debalancedebalancetmpogm5kjkl/mod_post_log/src/mod_post_log.erl0000664000175000017500000001123314751665140022360 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])). tmpogm5kjkl/mod_post_log/README.md0000664000175000017500000000210014751665140017650 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! ``` tmpogm5kjkl/mod_post_log/COPYING0000664000175000017500000000204214751665140017431 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. tmpogm5kjkl/mod_post_log/conf/0000775000175000017500000000000014751665140017325 5ustar debalancedebalancetmpogm5kjkl/mod_post_log/conf/mod_post_log.yml0000664000175000017500000000010314751665140022527 0ustar debalancedebalance#modules: # mod_post_log: # url: "http://foo.bar.com/messages" tmpogm5kjkl/mod_s3_upload/0000775000175000017500000000000014751665140016443 5ustar debalancedebalancetmpogm5kjkl/mod_s3_upload/src/0000775000175000017500000000000014751665140017232 5ustar debalancedebalancetmpogm5kjkl/mod_s3_upload/src/aws_util.erl0000664000175000017500000002143014751665140021565 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : aws_util.erl %%% Usage : AWS URL Signing %%% Author : Roman Hargrave %%% Purpose : Signing AWS Requests. Intended for S3-CS use. %%% Created : 24 Aug 2022 by Roman Hargrave %%% %%% %%% 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. %%%---------------------------------------------------------------------- %% URL Signing. Documented at %% https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html -module(aws_util). -author("roman@hargrave.info"). -include("aws.hrl"). -type verb() :: get | put | post | delete. -type headers() :: [{unicode:chardata(), unicode:chardata()}]. -type query_list() :: [{unicode:chardata(), unicode:chardata() | true}]. -type ttl() :: 1..604800. -define(AWS_SIGN_ALGO, <<"AWS4-HMAC-SHA256">>). -import(crypto, [mac/4]). -import(uri_string, [compose_query/1, dissect_query/1]). -import(misc, [crypto_hmac/3]). -export([signed_url/7]). %%------------------------------------------------------------------------ %% API %%------------------------------------------------------------------------ -spec signed_url( Auth :: #aws_auth{}, Verb :: verb(), Service :: binary(), Url :: binary(), ExtraHeaders :: headers(), Time :: calendar:datetime(), TTL :: ttl() ) -> SignedUrl :: binary(). % sign a URL given headers, a verb, authentication details, and a time signed_url(Auth, Verb, Service, URL, ExtraHeaders, Time, TTL) -> #{host := Host} = UnauthenticatedUriMap = uri_string:parse(URL), Headers = [{<<"host">>, Host} | ExtraHeaders], % insert authentication params. QueryList = sorted_query_list(uri_query_list(UnauthenticatedUriMap) ++ base_query_params(Auth, Time, Service, Headers, TTL)), UriMap = UnauthenticatedUriMap#{query => compose_query(QueryList)}, % generate and sign the message StringToSign = string_to_sign(Auth, Time, Service, Verb, UriMap, Headers), SigningKey = signing_key(Auth, Time, Service), Signature = encode_hex(crypto_hmac(sha256, SigningKey, StringToSign)), % add signature to the query list and compose URI SignedQueryString = compose_query([{<<"X-Amz-Signature">>, Signature}|QueryList]), uri_string:recompose(UriMap#{query => SignedQueryString}). %%------------------------------------------------------------------------ %% Internal %%------------------------------------------------------------------------ -spec sorted_query_list( QueryList :: query_list() ) -> SortedQueryList :: query_list(). % sort a query paramater list by parameter name, ascending sorted_query_list(QueryList) -> lists:sort(fun ({L, _}, {R, _}) -> L =< R end, QueryList). -spec uri_query_list( UriMap :: uri_string:uri_map() ) -> QueryList :: query_list(). % extract a query list from a uri_map(). uri_query_list(#{query := QueryString}) -> dissect_query(QueryString); uri_query_list(_) -> []. -spec verb( Verb :: verb() ) -> binary(). % convert a verb atom to a binary list verb(get) -> <<"GET">>; verb(put) -> <<"PUT">>; verb(post) -> <<"POST">>; verb(delete) -> <<"DELETE">>. -spec encode_hex( Data :: binary() ) -> EncodedData :: binary(). % lowercase binary:encode_hex encode_hex(Data) -> str:to_lower(str:to_hexlist(Data)). -spec iso8601_timestamp_utc( DateTime :: calendar:datetime() ) -> Timestamp :: binary(). % Generate an ISO8601-like YmdTHMSZ timestamp for X-Amz-Date. Only % produces UTC ('Z') timestamps. No separators. iso8601_timestamp_utc({{Y, Mo, D}, {H, M, S}}) -> str:format("~B~2..0B~2..0BT~2..0B~2..0B~2..0BZ", [Y, Mo, D, H, M, S]). -spec iso8601_date( DateTime :: calendar:datetime() ) -> DateStr :: binary(). % ISO8601 formatted date, no separators. iso8601_date({{Y, M, D}, _}) -> str:format("~B~2..0B~2..0B", [Y, M, D]). -spec scope( Auth :: #aws_auth{}, Time :: calendar:datetime(), Service :: binary() ) -> Scope :: binary(). % Generate the request scope used in the credential field and signature message scope(#aws_auth{region = Region}, Time, Service) -> str:format("~ts/~ts/~ts/aws4_request", [iso8601_date(Time), Region, Service]). -spec credential( Auth :: #aws_auth{}, Time :: calendar:datetime(), Service :: binary() ) -> Auth :: binary(). % Generate the value used for X-Amz-Credential credential(#aws_auth{access_key_id = KeyID} = Auth, Time, Service) -> str:format("~ts/~ts", [KeyID, scope(Auth, Time, Service)]). -spec base_query_params( Auth :: #aws_auth{}, Time :: calendar:datetime(), Service :: binary(), Headers :: headers(), TTL :: ttl() ) -> BaseQueryParams :: [{unicode:chardata(), unicode:chardata()}]. % Return the minimum required set of query parameters needed for % authenticated signed requests. base_query_params(Auth, Time, Service, Headers, TTL) -> [{<<"X-Amz-Algorithm">>, ?AWS_SIGN_ALGO}, {<<"X-Amz-Credential">>, credential(Auth, Time, Service)}, {<<"X-Amz-Date">>, iso8601_timestamp_utc(Time)}, {<<"X-Amz-Expires">>, erlang:integer_to_binary(TTL)}, {<<"X-Amz-SignedHeaders">>, signed_headers(Headers)}]. -spec canonical_headers( Headers :: headers() ) -> CanonicalHeaders :: unicode:chardata(). % generate the header list for canonical_request canonical_headers(Headers) -> str:join(lists:map(fun ({Name, Value}) -> str:format("~ts:~ts~n", [Name, Value]) end, Headers), <<>>). -spec signed_headers( SignedHeaders :: headers() ) -> SignedHeaders :: unicode:chardata(). % generate a semicolon-delimited list of headers, used to enumerate % signed headers in the AWSv4 canonical request signed_headers(SignedHeaders) -> str:join(lists:map(fun ({Name, _}) -> Name end, SignedHeaders), <<";">>). -spec canonical_request( Verb :: verb(), UriMap :: uri_string:uri_map(), Headers :: headers() ) -> CanonicalRequest :: unicode:chardata(). % Generate the canonical request used to compute the signature canonical_request(Verb, #{query := Query, path := Path}, Headers) -> <<(verb(Verb))/binary, "\n", Path/binary, "\n", Query/binary, "\n", (canonical_headers(Headers))/binary, "\n", (signed_headers(Headers))/binary, "\n", "UNSIGNED-PAYLOAD">>. -spec string_to_sign( Auth :: #aws_auth{}, Time :: calendar:datetime(), Service :: binary(), Verb :: verb(), UriMap :: uri_string:uri_map(), Headers :: headers() ) -> StringToSign :: unicode:chardata(). % generate the "string to sign", as per AWS specs string_to_sign(Auth, Time, Service, Verb, UriMap, Headers) -> RequestHash = crypto:hash(sha256, canonical_request(Verb, UriMap, Headers)), <>. -spec signing_key( Auth :: #aws_auth{}, Time :: calendar:datetime(), Service :: binary() ) -> SigningKey :: binary(). % generate the signing key used in the final HMAC-SHA256 round for % request signing. signing_key(#aws_auth{access_key = AccessKey, region = Region}, Time, Service) -> DateKey = crypto_hmac(sha256, <<"AWS4", AccessKey/binary>>, iso8601_date(Time)), DateRegionKey = crypto_hmac(sha256, DateKey, Region), DateRegionServiceKey = crypto_hmac(sha256, DateRegionKey, Service), crypto_hmac(sha256, DateRegionServiceKey, <<"aws4_request">>). tmpogm5kjkl/mod_s3_upload/src/mod_s3_upload.erl0000664000175000017500000004273614751665140022502 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : mod_s3_upload.erl %%% Author : Roman Hargrave %%% Purpose : An XEP-0363 Implementation using S3-compatible storage %%% Created : 24 Aug 2022 by Roman Hargrave %%% %%% %%% 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_s3_upload). -author('roman@hargrave.info'). -behaviour(gen_mod). -behaviour(gen_server). -protocol({xep, 363, '1.1.0'}). -include("logger.hrl"). -include("translate.hrl"). -include("aws.hrl"). -include_lib("xmpp/include/xmpp.hrl"). % gen_mod callbacks -export([start/2, stop/1, reload/3, depends/2, mod_opt_type/1, mod_options/1, mod_doc/0]). % gen_server callbacks -export([init/1, handle_info/2, handle_call/3, handle_cast/2]). -import(gen_mod, [get_opt/2]). -import(crypto, [strong_rand_bytes/1]). %%----------------------------------------------------------------------- %% gen_mod callbacks and related machinery %%----------------------------------------------------------------------- -spec start( ServerHost :: binary(), Opts :: gen_mod:opts() ) -> Result :: {ok, pid()} | {error, term()}. % start(ServerHost, Opts) -> gen_mod:start_child(?MODULE, ServerHost, Opts). -spec stop( ServerHost :: binary() ) -> Result :: any(). % stop(ServerHost) -> gen_mod:stop_child(?MODULE, ServerHost). -spec reload( ServerHost :: binary(), NewOpts :: gen_mod:opts(), OldOpts :: gen_mod:opts() ) -> Result :: ok. % reload(ServerHost, NewOpts, _OldOpts) -> ServerRef = gen_mod:get_module_proc(ServerHost, ?MODULE), % cast a message to the server with the new options gen_server:cast(ServerRef, {reload, ServerHost, build_service_params(ServerHost, NewOpts)}). %%------------------------------------------------------------------------ %% Options %%------------------------------------------------------------------------ -spec mod_opt_type( OptionName :: atom() ) -> OptionType :: econf:validator(). % mod_opt_type(access_key_id) -> econf:binary(); mod_opt_type(access_key_secret) -> econf:binary(); mod_opt_type(region) -> econf:binary(); mod_opt_type(bucket_url) -> econf:url([http, https]); mod_opt_type(download_url) -> econf:binary(); mod_opt_type(max_size) -> econf:pos_int(infinity); mod_opt_type(set_public) -> econf:bool(); mod_opt_type(put_ttl) -> econf:pos_int(infinity); mod_opt_type(service_name) -> econf:binary(); mod_opt_type(hosts) -> econf:hosts(); mod_opt_type(access) -> econf:acl(). -spec mod_options( Host :: binary() ) -> Options :: [{atom(), term()} | atom()]. % mod_options(Host) -> [{access_key_id, undefined}, {access_key_secret, undefined}, {region, undefined}, {bucket_url, undefined}, {download_url, undefined}, {max_size, 1073741824}, {set_public, true}, {put_ttl, 600}, {service_name, <<"S3 Upload">>}, {hosts, [<<"upload.", Host/binary>>]}, {access, local}]. -spec mod_doc() -> Doc :: #{desc => binary() | [binary()], opts => [{atom(), #{value := binary(), desc := binary()}}]}. % mod_doc() -> #{desc => [?T("This module implements XEP-0363 using an S3 bucket " "instead of an internal web server. This simplifies " "clustered deployments by removing the need to maintain " "shared storage, and is in many cases less expensive " "byte-for-byte than block storage. It is mutually " "incompatible with mod_http_upload.")], opts => [{access_key_id, #{value => ?T("AccessKeyId"), desc => ?T("AWS Access Key ID.")}}, {access_key_secret, #{value => ?T("AccessKeySecret"), desc => ?T("AWS Access Key Secret.")}}, {region, #{value => ?T("Region"), desc => ?T("AWS Region")}}, {bucket_url, #{value => ?T("BucketUrl"), desc => ?T("S3 Bucket URL.")}}, {download_url, #{value => ?T("DownloadUrl"), desc => ?T("Host for GET/Download requests.")}}, {max_size, #{value => ?T("MaxSize"), desc => ?T("Maximum file size, in bytes. 0 is unlimited.")}}, {set_public, #{value => ?T("SetPublic"), desc => ?T("Set x-amz-acl to public-read.")}}, {put_ttl, #{value => ?T("PutTtl"), desc => ?T("How long the PUT URL will be valid for.")}}, {service_name, #{value => ?T("ServiceName"), desc => ?T("Name given in discovery requests.")}}, {hosts, % named for consistency with other modules #{value => ?T("ServiceJids"), desc => ?T("JIDs used when communicating with the service")}}, {access, #{value => ?T("UploadAccess"), desc => ?T("Access rule for JIDs that may request new URLs")}}]}. depends(_Host, _Opts) -> []. %%------------------------------------------------------------------------ %% gen_server callbacks. %%------------------------------------------------------------------------ -record(params, {service_name :: binary(), % name given for the service in discovery. service_jids :: [binary()], % stanzas destined for these JIDs will be routed to the service. max_size :: integer() | infinity, % maximum upload size. sort of the honor system in this case. bucket_url :: binary(), % S3 bucket URL or subdomain download_url :: binary() | undefined, set_public :: boolean(), % set the public-read ACL on the object? ttl :: integer(), % TTL of the signed PUT URL server_host :: binary(), % XMPP vhost the service belongs to auth :: #aws_auth{}, access :: atom()}). -spec init( Params :: list() ) -> Result :: {ok, #params{}}. % init([ServerHost, Opts]) -> Params = build_service_params(ServerHost, Opts), update_routes(ServerHost, [], Params#params.service_jids), {ok, Params}. -spec handle_info( Message :: any(), State :: #params{} ) -> Result :: {noreply, #params{}}. % receive non-standard (gen_server) messages handle_info({route, #iq{lang = Lang} = Packet}, Opts) -> try xmpp:decode_els(Packet) of IQ -> ejabberd_router:route(handle_iq(IQ, Opts)), {noreply, Opts} catch _:{xmpp_codec, Why} -> Message = xmpp:io_format_error(Why), Error = xmpp:err_bad_request(Message, Lang), ejabberd_router:route_error(Packet, Error), {noreply, Opts} end; handle_info(Request, Opts) -> ?WARNING_MSG("Unexpected info: ~p", [Request]), {noreply, Opts}. -spec handle_call( Request:: any(), Sender :: gen_server:from(), State :: #params{} ) -> Result :: {noreply, #params{}}. % respond to $gen_call messages handle_call(Request, Sender, Opts) -> ?WARNING_MSG("Unexpected call from ~p: ~p", [Sender, Request]), {noreply, Opts}. -spec handle_cast( Request :: any(), State :: #params{} ) -> Result :: {noreply, #params{}}. % receive $gen_cast messages handle_cast({reload, ServerHost, NewOpts}, OldOpts) -> update_routes(ServerHost, OldOpts#params.service_jids, NewOpts#params.service_jids), {noreply, NewOpts}; handle_cast(Request, Opts) -> ?WARNING_MSG("Unexpected cast: ~p", [Request]), {noreply, Opts}. %%------------------------------------------------------------------------ %% Internal Stanza Processing %%----------------------------------------------------------------------- -spec update_routes( ServerHost :: binary(), OldJIDs :: [binary()], NewJIDs :: [binary()] ) -> Result :: _. % maintain routing rules for JIDs owned by this service. update_routes(ServerHost, OldJIDs, NewJIDs) -> lists:foreach(fun (Domain) -> ejabberd_router:register_route(Domain, ServerHost) end, NewJIDs), lists:foreach(fun ejabberd_router:unregister_route/1, OldJIDs -- NewJIDs). -spec handle_iq( IQ :: iq(), Params :: gen_mod:opts() ) -> Response :: iq(). % Handle discovery requests. Produces a document such as depicted in % XEP-0363 v1.1.0 Ex. 4. handle_iq(#iq{type = get, lang = Lang, to = HostJID, sub_els = [#disco_info{}]} = IQ, #params{max_size = MaxSize, service_name = ServiceName}) -> Host = jid:encode(HostJID), % collect additional discovery entries, if any. Advice = ejabberd_hooks:run_fold(disco_info, Host, [], [Host, ?MODULE, <<"">>, Lang]), % if a maximum size was specified, append xdata with the limit XData = case MaxSize of infinity -> Advice; _ -> [#xdata{type = result, fields = http_upload:encode( [{'max-file-size', MaxSize}], ?NS_HTTP_UPLOAD_0, Lang )} | Advice] end, % build disco iq Query = #disco_info{identities = [#identity{category = <<"store">>, type = <<"file">>, name = translate:translate(Lang, ServiceName)}], features = [?NS_HTTP_UPLOAD_0], xdata = XData}, xmpp:make_iq_result(IQ, Query); % this swaps parties for us % handle slot request with FileSize > MaxSize handle_iq(#iq{type = get, from = From, lang = Lang, sub_els = [#upload_request_0{size = FileSize, filename = Filename}]} = IQ, #params{max_size = MaxSize}) when FileSize > MaxSize -> ?WARNING_MSG("~ts tried to upload an oversize file (~ts, ~B bytes)", [jid:encode(From), Filename, FileSize]), ErrorMessage = {?T("File larger than ~B bytes"), [MaxSize]}, Error = xmpp:err_not_acceptable(ErrorMessage, Lang), Els = [#upload_file_too_large{'max-file-size' = MaxSize, xmlns = ?NS_HTTP_UPLOAD_0} | xmpp:get_els(Error)], xmpp:make_error(IQ, xmpp:set_els(Error, Els)); % Handle slot request handle_iq(#iq{type = get, from = Requester, lang = Lang, sub_els = [#upload_request_0{filename = Filename, size = FileSize} = UploadRequest]} = IQ, #params{server_host = ServerHost, access = Access} = Params) -> case acl:match_rule(ServerHost, Access, Requester) of allow -> ?INFO_MSG("Generating S3 Object URL Pair for ~ts to upload file ~ts (~B bytes)", [jid:encode(Requester), Filename, FileSize]), {PutURL, GetURL} = put_get_url(Params, UploadRequest, Filename, Requester), xmpp:make_iq_result(IQ, #upload_slot_0{get = GetURL, put = PutURL, xmlns = ?NS_HTTP_UPLOAD_0}); deny -> ?INFO_MSG("Denied upload request from ~ts for file ~ts (~B bytes)", [jid:encode(Requester), Filename, FileSize]), xmpp:make_error(IQ, xmpp:err_forbidden(?T("Access denied"), Lang)) end; % handle unexpected IQ handle_iq(IQ, _Params) -> xmpp:make_error(IQ, xmpp:err_bad_request()). %%------------------------------------------------------------------------ %% Internal Helpers %%------------------------------------------------------------------------ -spec expanded_jids( ServiceHost :: binary(), JIDs :: [binary()] ) -> ExpandedJIDs :: [binary()]. % expand @HOST@ in JIDs expanded_jids(ServerHost, JIDs) -> lists:map(fun (JID) -> misc:expand_keyword(<<"@HOST@">>, JID, ServerHost) end, JIDs). -spec build_service_params( ServerHost :: binary(), Opts :: gen_mod:opts() ) -> Params :: #params{}. % create a service params record from module config build_service_params(ServerHost, Opts) -> Auth = #aws_auth{access_key_id = get_opt(access_key_id, Opts), access_key = get_opt(access_key_secret, Opts), region = get_opt(region, Opts)}, #params{service_name = get_opt(service_name, Opts), service_jids = expanded_jids(ServerHost, get_opt(hosts, Opts)), max_size = get_opt(max_size, Opts), bucket_url = get_opt(bucket_url, Opts), download_url = get_opt(download_url, Opts), set_public = get_opt(set_public, Opts), ttl = get_opt(put_ttl, Opts), server_host = ServerHost, auth = Auth, access = get_opt(access, Opts)}. -spec put_get_url( Params :: #params{}, UploadRequest :: #upload_request_0{}, Filename :: binary(), JID :: jid() ) -> {binary(), binary()}. % produce a list of {put_url, get_url}, where put_url is signed and % get_url may use the optional download_url override put_get_url(#params{bucket_url = BucketURL, download_url = undefined} = Params, UploadRequest, Filename, JID) -> put_get_url(Params#params{download_url = BucketURL}, UploadRequest, Filename, JID); put_get_url(#params{bucket_url = BucketURL, download_url = DownloadURL, auth = Auth, ttl = TTL} = Params, UploadRequest, Filename, JID) -> ObjectName = object_name(Filename, JID), UnsignedPutURL = decorated_put_url(UploadRequest, Params, BucketURL, ObjectName), {aws_util:signed_url(Auth, put, ?AWS_SERVICE_S3, UnsignedPutURL, [], calendar:universal_time(), TTL), object_url(DownloadURL, ObjectName)}. -spec url_service_parameters( Params :: #params{} ) -> ServiceParameters :: [{binary(), binary() | true}]. % additional URL parameters from module config url_service_parameters(#params{set_public = true}) -> [{<<"X-Amz-Acl">>, <<"public-read">>}]; url_service_parameters(_) -> []. -spec upload_parameters( UploadRequest :: #upload_request_0{}, Params :: #params{} ) -> UploadParameters :: [{binary(), binary() | true}]. % headers to be included with the PUT request upload_parameters(#upload_request_0{size = FileSize, 'content-type' = ContentType}, ServiceParams) -> [{<<"Content-Type">>, <>}, {<<"Content-Length">>, erlang:integer_to_binary(FileSize)} | url_service_parameters(ServiceParams)]. -spec decorated_put_url( UploadRequest :: #upload_request_0{}, Params :: #params{}, BucketURL :: binary(), ObjectName :: binary() ) -> PutURL :: binary(). % attach additional query parameters (to the PUT URL), specifically canned ACL. decorated_put_url(UploadRequest, ServiceParams, BucketURL, ObjectName) -> UriMap = uri_string:parse(uri_string:resolve(ObjectName, BucketURL)), QueryList = case UriMap of #{query := QueryString} -> uri_string:dissect_query(QueryString); _ -> [] end, Params = upload_parameters(UploadRequest, ServiceParams), WithOpts = uri_string:compose_query(Params ++ QueryList), uri_string:recompose(UriMap#{query => WithOpts}). -spec object_url( BucketURL :: binary(), Filename :: binary() ) -> ObjectURL :: binary(). % generate a unique random object URL for the given filename object_url(BucketURL, ObjectName) -> uri_string:resolve(ObjectName, BucketURL). -spec object_name( Filename :: binary(), JID :: jid() ) -> ObjectName :: binary(). % generate a unique random object name for the given filename object_name(Filename, #jid{luser = User, lserver = Server}) -> UserStr = str:sha(<>), RandStr = p1_rand:get_alphanum_string(20), FileStr = uri_string:quote(Filename), str:format("~s/~s/~s", [UserStr, RandStr, FileStr]). tmpogm5kjkl/mod_s3_upload/README.md0000664000175000017500000000630614751665140017727 0ustar debalancedebalancemod\_s3\_upload: XEP-0363 with S3-compatible storage ==================================================== * Author: Roman Hargrave Implements HTTP Upload using any S3-compatible storage service. # OTP Compatibility This module requires Erlang/OTP 25.0 or higher, as it depends heavily on the `uri_string` module to implement URL signing. # How it works The S3 API is highly compatible with XEP-0363 because it uses PUT and GET for object placement and retrieval. What's more, a client may be provided with a URL that may be used to upload a specific file without having to expose API credentials. This makes for an extremely desirable XEP-0363 storage backend. An outline of an XEP-0363 transaction using this module follows: 1. A client sends a slot-request IQ to the upload service 2. The server verifies that the client may upload files, and that the proposed file size is acceptable 3. The server generates an object URL, which will be used by clients to download the file once it has been uploaded 3. The server then constructs an additional URL based upon the object URL, including information about the object size and type. A TTL is added to the URL, such that it will expire. The URL is then signed. 4. The server returns the object URL and the signed URL 5. The client submits a PUT request to the signed URL with the file contents. 6. If the PUT request succeeds, the client sends message stanza containing the link and additional metadata to whatever entity. # Operator considerations This module includes a `Content-Length` parameter in the upload URL; however, it is the responsibility of the storage service to validate this. Different storage services may behave differently or not respond at all when a file is uploaded and the size does not exactly match. If you intend to enforce a file size limit, make sure that your storage service checks upload size against this parameter. Furthermore, it is not the responsibility of this module to manage the lifecycle of objects once uploaded. Not all services implement lifecycle management or advanced features like tagging. To this end, you might wish to configure an object lifecycle policy to control costs, otherwise you might end up paying to store very old objects. To this end, bear in mind that moving objects to a colder storage class (if your service supports this) as part of a lifecycle policy could generate considerable retrieval expenses - particularly when combined combined with large MUCs. # Known Working Services This has been tested with the following services: - **Wasabi** - which works very well. It is extremely cheap, but **does not support lifecycle management** or custom DNS. It almost certainly works with Amazon S3. # Configuration The module expects a bucket URL, access key ID, secret, and region. Furthermore, ```yaml modules: mod_s3_upload: # Required, characteristic values shown access_key_id: ABCDEF1234567890 access_key_secret: whatever region: us-east-2 bucket_url: https://my-bucket.whatever-service.com # Optional, defaults shown max_size: 1073741824 put_ttl: 600 set_public: true service_name: 'S3 Upload' access: local hosts: - upload.@HOST@ ``` tmpogm5kjkl/mod_s3_upload/mod_s3_upload.spec0000664000175000017500000000040614751665140022047 0ustar debalancedebalance# -*- mode:yaml; -*- author: "Roman Hargrave " category: "service" summary: "Upload files to S3-compatible storage" home: "https://github.com/processone/ejabberd-contrib/tree/master/" url: "git@github.com:processone/ejabberd-contrib.git" tmpogm5kjkl/mod_s3_upload/COPYING0000664000175000017500000004325414751665140017506 0ustar debalancedebalance 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. tmpogm5kjkl/mod_s3_upload/conf/0000775000175000017500000000000014751665140017370 5ustar debalancedebalancetmpogm5kjkl/mod_s3_upload/conf/mod_s3_upload.yml0000664000175000017500000000147114751665140022646 0ustar debalancedebalancemodules: mod_s3_upload: region: us-west-1 bucket_url: https://example.s3.us-west-1.wasabisys.com ## Set this if you wish to use a different base URL for downloads # download_url: https://my-super-cdn.com access_key_id: WBPXK3YWS457RV9P access_key_secret: N2UC4RSLPU6VH6FYGNJ9BRNMC74XM6G9MP74RNH7D4ZG9UBZY9Z5G4ZR8T782KR7 ## Maximum permitted object size, in bytes # max_size: 1073741824 ## How long, in seconds from generation, an upload URL is valid # put_ttl: 600 ## Whether to apply the special public-read ACL to the object # set_public: true ## Advertised service name # service_name: 'S3 Upload' ## ACL containing users permitted to request slots # access: local ## Hostnames that this module will receive IQs at # hosts: # - upload.@HOST@ tmpogm5kjkl/mod_s3_upload/include/0000775000175000017500000000000014751665140020066 5ustar debalancedebalancetmpogm5kjkl/mod_s3_upload/include/aws.hrl0000664000175000017500000000244314751665140021372 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : s3_util.erl %%% Usage : S3 URL Generation and Signing %%% Author : Roman Hargrave %%% Purpose : Signing AWS Requests. Intended for S3-CS use. %%% Created : 24 Aug 2022 by Roman Hargrave %%% %%% %%% 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. %%%---------------------------------------------------------------------- -record(aws_auth, {access_key_id :: binary(), access_key :: binary(), region :: binary()}). -define(AWS_SERVICE_S3, <<"s3">>). tmpogm5kjkl/mod_message_log/0000775000175000017500000000000014751665140017037 5ustar debalancedebalancetmpogm5kjkl/mod_message_log/src/0000775000175000017500000000000014751665140017626 5ustar debalancedebalancetmpogm5kjkl/mod_message_log/src/mod_message_log.erl0000664000175000017500000002024014751665140023454 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]). tmpogm5kjkl/mod_message_log/README.md0000664000175000017500000000215014751665140020314 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" ``` tmpogm5kjkl/mod_message_log/mod_message_log.spec0000664000175000017500000000037614751665140023045 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" tmpogm5kjkl/mod_message_log/COPYING0000664000175000017500000004346414751665140020105 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. tmpogm5kjkl/mod_message_log/conf/0000775000175000017500000000000014751665140017764 5ustar debalancedebalancetmpogm5kjkl/mod_message_log/conf/mod_message_log.yml0000664000175000017500000000013614751665140023633 0ustar debalancedebalancemodules: mod_message_log: filename: auto # filename: "/var/log/ejabberd/message.log" tmpogm5kjkl/mod_ecaptcha/0000775000175000017500000000000014751665140016322 5ustar debalancedebalancetmpogm5kjkl/mod_ecaptcha/rebar.config0000664000175000017500000000050014751665140020577 0ustar debalancedebalance % There's a bug in ecaptcha 0.2.0 that breaks compilation with % Erlang/OTP 26, and 0.2.0 is the latest version published in hex right now. % Consequently, let's use the latest ecaptcha from git repository. {deps, [ {ecaptcha, ".*", {git, "https://github.com/seriyps/ecaptcha", {branch, "master"}}} ]}. tmpogm5kjkl/mod_ecaptcha/src/0000775000175000017500000000000014751665140017111 5ustar debalancedebalancetmpogm5kjkl/mod_ecaptcha/src/mod_ecaptcha.erl0000664000175000017500000000521314751665140022225 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). tmpogm5kjkl/mod_ecaptcha/README.md0000664000175000017500000000735614751665140017614 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 ``` tmpogm5kjkl/mod_ecaptcha/mod_ecaptcha.spec0000664000175000017500000000034714751665140021611 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" tmpogm5kjkl/mod_ecaptcha/COPYING0000664000175000017500000004346414751665140017370 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. tmpogm5kjkl/mod_ecaptcha/conf/0000775000175000017500000000000014751665140017247 5ustar debalancedebalancetmpogm5kjkl/mod_ecaptcha/conf/mod_ecaptcha.yml0000664000175000017500000000032114751665140022375 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: {} tmpogm5kjkl/README.md0000664000175000017500000000605414751665140015177 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." - mod_promethus_exporter: There is brand new module that adds Prometheus support, see mod_prometheus tmpogm5kjkl/mod_prometheus/0000775000175000017500000000000014751665140016745 5ustar debalancedebalancetmpogm5kjkl/mod_prometheus/rebar.config0000664000175000017500000000037214751665140021231 0ustar debalancedebalance{deps, [ {quantile_estimator, "0.2.1", {git, "https://github.com/deadtrickster/quantile_estimator", {branch, "master"}}}, {prometheus, "4.11.0", {git, "https://github.com/deadtrickster/prometheus.erl", {branch, "master"}}} ]}. tmpogm5kjkl/mod_prometheus/src/0000775000175000017500000000000014751665140017534 5ustar debalancedebalancetmpogm5kjkl/mod_prometheus/src/mod_prometheus.erl0000664000175000017500000003504514751665140023301 0ustar debalancedebalance-module(mod_prometheus). -author('pouriya.jahanbakhsh@gmail.com'). -behaviour(gen_mod). -export([start/2, stop/1, reload/3, mod_doc/0, mod_opt_type/1, mod_options/1, depends/2]). -export([process_histogram/5, process_counter/5]). -export([process/2]). -include("logger.hrl"). -include_lib("xmpp/include/xmpp.hrl"). -include("mod_roster.hrl"). -include("ejabberd_http.hrl"). -include("ejabberd_web_admin.hrl"). -include("ejabberd_stacktrace.hrl"). -include("translate.hrl"). start(Host, Opts) -> case lists:member({subscribe, 5}, ejabberd_hooks:module_info(exports)) of true -> application:set_env(prometheus, collectors, []), ejabberd:start_app(prometheus), update_mnesia(get_opt(mnesia, Opts)), update_vm(get_opt(vm, Opts)), handle_hooks(get_opt(hooks, Opts), Host, subscribe, []), ok; _ -> Error = "Hook subscriber is not supported. Please Upgrade Ejabberd.", ?ERROR_MSG(Error, []), {error, Error} end. stop(Host) -> handle_hooks(get_opt(hooks, Host), Host, unsubscribe, []), ok. reload(Host, NewOpts, OldOpts) -> prometheus_registry:clear(), handle_hooks(get_opt(hooks, OldOpts), Host, unsubscribe, []), handle_hooks(get_opt(hooks, NewOpts), Host, subscribe, []), update_mnesia(get_opt(mnesia, NewOpts)), update_vm(get_opt(vm, NewOpts)), ok. depends(_Host, _Opts) -> []. mod_opt_type(vm) -> econf:options( #{ distribution => econf:bool(), memory => econf:bool(), microstate_accounting => econf:bool(), statistics => econf:bool(), system_info => econf:bool() }, [{return, map}] ); mod_opt_type(mnesia) -> econf:bool(); mod_opt_type(hooks) -> econf:list( econf:options( #{ hook => econf:atom(), type => econf:enum([histogram, counter]), buckets => econf:list(econf:int(0, 150000)), labels => econf:list(econf:enum([host, stanza, module])), help => econf:string(), collect => econf:either( all, econf:list( econf:options( #{ module => econf:atom(), function => econf:atom(), type => econf:enum([histogram, counter]), buckets => econf:list(econf:int(0, 150000)), labels => econf:list(econf:enum([host, stanza])), help => econf:string() }, [{required, [module, function]}, {return, map}] ) ) ) }, [{required, [hook]}, {return, map}, unique] ), [unique] ). mod_options(_Host) -> [{vm, #{}}, {mnesia, false}, {hooks, []}]. mod_doc() -> #{desc => [<<"TODO">>], opts => []}. get_opt(Key, #{}=Opts) -> gen_mod:get_opt(Key, Opts); get_opt(Key, Host) -> gen_mod:get_module_opt(Host, mod_prometheus, Key). process(_Path, #request{}=_Request) -> {200, [{<<"Content-Type">>, <<"text/plain; version=0.0.4; charset=utf-8; escaping=values">>}], prometheus_text_format:format()}. update_mnesia(Enable) -> application:set_env( prometheus, mnesia_collector_metrics, if Enable -> prometheus_registry:register_collector(prometheus_mnesia_collector), ?INFO_MSG("Enabled Mnesia Prometheus metrics", []), all; true -> ?INFO_MSG("Disabled Mnesia Prometheus metrics", []), [] end), ok. update_vm(Opts) -> lists:foreach( fun({Name, EnvName, Mod}) -> application:set_env( prometheus, EnvName, case maps:get(Name, Opts, false) of true -> prometheus_registry:register_collector(Mod), ?INFO_MSG("Enabled Erlang VM ~p Prometheus metrics", [Name]), all; _ -> ?INFO_MSG("Disabled Erlang VM ~p Prometheus metrics", [Name]), [] end ) end, [ {distribution, vm_dist_collector_metrics, prometheus_vm_dist_collector}, {memory, vm_memory_collector_metrics, prometheus_vm_memory_collector}, {microstate_accounting, prometheus_vm_dist_collector, prometheus_vm_msacc_collector}, {statistics, vm_statistics_collector_metrics, prometheus_vm_statistics_collector}, {system_info, vm_system_info_collector_metrics, prometheus_vm_system_info_collector} ] ). %% When the runner starts running this hook %% Hook =:= Hook: process_histogram(#{hook := Hook}=InitArg, before, _Host, Hook, _) -> InitArg#{hook_duration_start_time => erlang:system_time(millisecond)}; %% When the runner stops running this hook %% Hook =:= Hook: process_histogram( #{name := Name, hook := Hook, labels := LabelNames, hook_duration_start_time := Time}=State, 'after', Host, Hook, Args ) -> Duration = erlang:system_time(millisecond) - Time, Labels = replace_labels(LabelNames, Args, Host, "total"), prometheus_histogram:observe(Name, Labels, Duration), maps:remove(hook_duration_start_time, State); %% When runner start running a callback and `labels` section contains `module`: %% Hook =:= Hook: process_histogram( #{hook := Hook, labels := LabelNames}=State, before_callback, _Host, Hook, {_Mod, _Func, _Seq, _Args} ) -> case lists:member(module, LabelNames) of true -> State#{module_duration_start_time => erlang:system_time(millisecond)}; _ -> State end; %% When runner is done running a callback and `labels` section contains `module`: %% Hook =:= Hook: process_histogram( #{hook := Hook, name := Name, module_duration_start_time := Time}=State, after_callback, Host, Hook, {Mod, _Func, _Seq, Args} ) -> Duration = erlang:system_time(millisecond) - Time, LabelNames = maps:get(labels, State, []), Labels = replace_labels(LabelNames, Args, Host, Mod), prometheus_histogram:observe(Name, Labels, Duration), maps:remove(module_duration_start_time, State); %% When runner runs a callback and we are going to collect this callback info: %% {Mod, Func} =:= {Mod, Func}: process_histogram(#{callback := {Mod, Func}}=State, before_callback, _Host, _Hook, {Mod, Func, _Seq, _Args}) -> State#{callback_duration_start_time => erlang:system_time(millisecond)}; %% When runner done running a callback and we are going to collect this callback info: %% {Mod, Func} =:= {Mod, Func}: process_histogram( #{callback := {Mod, Func}, name := Name, callback_duration_start_time := Time}=State, after_callback, Host, _Hook, {Mod, Func, _Seq, Args} ) -> Duration = erlang:system_time(millisecond) - Time, LabelNames = maps:get(labels, State, []), Labels = replace_labels(LabelNames, Args, Host, Mod), prometheus_histogram:observe(Name, Labels, Duration), maps:remove(callback_duration_start_time, State); process_histogram(#{}=State, _Event, _Host, _Hook, _) -> State. %% When the runner starts running this hook %% Hook =:= Hook: process_counter(#{hook := Hook}=InitArg, before, _Host, Hook, _) -> InitArg; %% When the runner stops running this hook %% Hook =:= Hook: process_counter( #{name := Name, hook := Hook, labels := LabelNames}=State, 'after', Host, Hook, Args ) -> Labels = replace_labels(LabelNames, Args, Host, "total"), prometheus_counter:inc(Name, Labels), State; %% When runner start running a callback and `labels` section contains `module`: %% Hook =:= Hook: process_counter( #{hook := Hook}=State, before_callback, _Host, Hook, {_Mod, _Func, _Seq, _Args} ) -> State; %% When runner is done running a callback and `labels` section contains `module`: %% Hook =:= Hook: process_counter( #{hook := Hook, name := Name}=State, after_callback, Host, Hook, {Mod, _Func, _Seq, Args} ) -> LabelNames = maps:get(labels, State, []), case lists:member(module, LabelNames) of true -> LabelNames = maps:get(labels, State, []), Labels = replace_labels(LabelNames, Args, Host, Mod), prometheus_counter:inc(Name, Labels); _ -> ok end, State; %% When runner runs a callback and we are going to collect this callback info: %% {Mod, Func} =:= {Mod, Func}: process_counter(#{callback := {Mod, Func}}=State, before_callback, _Host, _Hook, {Mod, Func, _Seq, _Args}) -> State; %% When runner done running a callback and we are going to collect this callback info: %% {Mod, Func} =:= {Mod, Func}: process_counter( #{callback := {Mod, Func}, name := Name}=State, after_callback, Host, _Hook, {Mod, Func, _Seq, Args} ) -> LabelNames = maps:get(labels, State, []), Labels = replace_labels(LabelNames, Args, Host, Mod), prometheus_counter:inc(Name, Labels), State; process_counter(#{}=State, _Event, _Host, _Hook, _) -> State. handle_hooks([HookOpts | Hooks], Host, Action, Metrics) -> handle_hooks(Hooks, Host, Action, Metrics ++ handle_hook(HookOpts)); handle_hooks([], Host, Action, [{Type, Name, MName, Opts, InitArg} | Metrics]) -> case lists:any( fun({_, _, OtherMName, _, _}) -> MName == OtherMName end, Metrics ) of true -> ?ERROR_MSG("Dropped Prometheus duplicate metric name ~tp for hook ~tp", [MName, Name]); _ -> case Type of histogram -> handle_histogram(Name, MName, Opts, Host, Action, InitArg); counter -> handle_counter(Name, MName, Opts, Host, Action, InitArg) end end, handle_hooks([], Host, Action, Metrics); handle_hooks([], _Host, _Action, []) -> ok. handle_hook(#{hook := Name}=Opts) -> Collect = maps:get(collect, Opts, all), Type = maps:get(type, Opts, histogram), case Type of histogram -> case Collect of all -> [{Type, Name, duration_histogram_name(Name), Opts, #{hook => Name}}]; Callbacks -> Opts2 = maps:remove(collect, Opts), Labels = maps:get(labels, Opts, []), [ { Type, Name, duration_histogram_name(Name, Mod, Func), (maps:merge(Opts2, Callback))#{ %% Merge labels: labels => sets:to_list(sets:from_list(Labels ++ maps:get(labels, Callback, []))) }, #{callback => {Mod, Func}} } || #{module := Mod, function := Func}=Callback <- Callbacks ] end; counter -> case Collect of all -> [{Type, Name, counter_name(Name), Opts, #{hook => Name}}]; Callbacks -> Opts2 = maps:remove(collect, Opts), Labels = maps:get(labels, Opts, []), [ { Type, Name, counter_name(Name, Mod, Func), (maps:merge(Opts2, Callback))#{ %% Merge labels: labels => sets:to_list(sets:from_list(Labels ++ maps:get(labels, Callback, []))) }, #{callback => {Mod, Func}} } || #{module := Mod, function := Func}=Callback <- Callbacks ] end end. handle_histogram(Name, HName, HistogramOpts, Host, Action, State) -> LabelNames = maps:get(labels, HistogramOpts, []), InitArg = State#{name => HName, labels => LabelNames}, case Action of subscribe -> prometheus_histogram:declare( [ {name, HName}, {buckets, maps:get(buckets, HistogramOpts, [1, 10, 100, 500, 750, 1000, 3000, 5000])}, {help, maps:get(help, HistogramOpts, "No help")}, {labels, LabelNames} ] ), ?INFO_MSG("Created new Prometheus histogram for ~p with labels ~p", [HName, LabelNames]), ejabberd_hooks:subscribe(Name, Host, ?MODULE, process_histogram, InitArg); _ -> try prometheus_histogram:deregister(HName) of _ -> ?INFO_MSG("Removed Prometheus histogram for ~p with labels ~p", [HName, LabelNames]) catch _:{unknown_metric, _, _} -> ok end, ejabberd_hooks:unsubscribe(Name, Host, ?MODULE, process_histogram, InitArg) end. handle_counter(Name, HName, CounterOpts, Host, Action, State) -> LabelNames = maps:get(labels, CounterOpts, []), InitArg = State#{name => HName, labels => LabelNames}, case Action of subscribe -> prometheus_counter:declare( [{name, HName}, {help, maps:get(help, CounterOpts, "No help")}, {labels, LabelNames}] ), ?INFO_MSG("Created new Prometheus counter for ~p with labels ~p", [HName, LabelNames]), ejabberd_hooks:subscribe(Name, Host, ?MODULE, process_counter, InitArg); _ -> try prometheus_counter:deregister(HName) of _ -> ?INFO_MSG("Removed Prometheus counter for ~p with labels ~p", [HName, LabelNames]) catch _:{unknown_metric, _, _} -> ok end, ejabberd_hooks:unsubscribe(Name, Host, ?MODULE, process_counter, InitArg) end. duration_histogram_name(Hook) -> list_to_atom(atom_to_list(Hook) ++ "_duration_milliseconds"). duration_histogram_name(Hook, Mod, Func) when Hook =:= Func -> list_to_atom(atom_to_list(Hook) ++ "_" ++ atom_to_list(Mod) ++ "_duration_milliseconds"); duration_histogram_name(Hook, Mod, Func) -> list_to_atom(atom_to_list(Hook) ++ "_" ++ atom_to_list(Mod) ++ atom_to_list(Func) ++ "_duration_milliseconds"). counter_name(Hook) -> list_to_atom(atom_to_list(Hook) ++ "_total"). counter_name(Hook, Mod, Func) when Hook =:= Func -> list_to_atom(atom_to_list(Hook) ++ "_" ++ atom_to_list(Mod) ++ "_total"); counter_name(Hook, Mod, Func) -> list_to_atom(atom_to_list(Hook) ++ "_" ++ atom_to_list(Mod) ++ atom_to_list(Func) ++ "_total"). maybe_remove_module_prefix(Mod) when is_atom(Mod) -> maybe_remove_module_prefix(atom_to_list(Mod)); maybe_remove_module_prefix("mod_" ++ Name) -> Name; maybe_remove_module_prefix(Name) -> Name. replace_labels([host | LabelNames], HookArgs, Host, Mod) when Host /= undefined -> [Host | replace_labels(LabelNames, HookArgs, Host, Mod)]; replace_labels([stanza | LabelNames], HookArgs, Host, Mod) when HookArgs /= undefined -> [find_stanza_type(HookArgs) | replace_labels(LabelNames, HookArgs, Host, Mod)]; replace_labels([module | LabelNames], HookArgs, Host, Mod) when Mod /= undefined -> [maybe_remove_module_prefix(Mod) | replace_labels(LabelNames, HookArgs, Host, Mod)]; replace_labels([_Unwanted | LabelNames], HookArgs, Host, Mod) -> replace_labels(LabelNames, HookArgs, Host, Mod); replace_labels([], _, _, _) -> []. find_stanza_type({Arg, _}) when ?is_stanza(Arg) -> %% c2s element(1, Arg); find_stanza_type([{Arg, _} | _]) when ?is_stanza(Arg) -> %% c2s element(1, Arg); find_stanza_type([Arg | _]) when ?is_stanza(Arg) -> element(1, Arg); find_stanza_type(Tup) when is_tuple(Tup) -> find_stanza_type(erlang:tuple_to_list(Tup)); find_stanza_type([Arg | Args]) when is_tuple(Arg) -> find_stanza_type(erlang:tuple_to_list(Arg) ++ Args); find_stanza_type([_ | Args]) -> find_stanza_type(Args); find_stanza_type([]) -> unknown. tmpogm5kjkl/mod_prometheus/README.md0000664000175000017500000000443114751665140020226 0ustar debalancedebalancemod_prometheus - Prometheus metrics =================================== - Requires: ejabberd 24.07 or higher - Author: [Pouriya Jahanbakhsh](https://github.com/pouriya) This module provides a web page with metrics suitable for [Prometheus](https://prometheus.io/), using the [prometheus](https://github.com/deadtrickster/prometheus.erl) erlang library. Options ------- The configurable options are: - `mnesia: true | false` Enable mnesia metrics or not. Default: `false` - `vm: [metric: true | false, ...]` Enable some Erlang Virtual Machine metrics. Available ones are: `memory`, `system_info`, `statistics`, `distribution`, `microstate_accounting`. For details please consult [prometheus.erl collectors](https://github.com/deadtrickster/prometheus.erl?tab=readme-ov-file#erlang-vm--otp-collectors). Default: `[]` - `hooks: [Hook]` List of hooks to investigate. Default is an empty list: `[]` Each Hook is: - `hook: atom()`: the name of the hook - `type: counter | histogram` - `help: "Explanation"` - `stanza_label: true | false` - `host_label: true | false` - `collect: all | [Callback]` where each Callback is: - `module: atom()` - `function: atom()` - `help: "Explanation"` - `buckets: [integer()]` Quick Start Guide ----------------- ### Install module 1. Start ejabberd 1. Download dependencies, compile and install this module: ```sh ejabberdctl module_install mod_prometheus ``` 1. Check ejabberd provides metrics in the URL: http://localhost:5289/metrics/ ### Start Prometheus and Grafana Start Prometheus and Grafana, for example using Podman or Docker: ```sh cd example podman-compose up # or # docker-compose up ``` ### Test Prometheus 1. Open in web browser http://localhost:9090/ 1. Enter example query: `erlang_mnesia_tablewise_size{table="muc_online_room"}` ### Setup Grafana 1. Open in web browser http://localhost:3000/ 1. Login with username `admin` and password `admin` 1. Add your first data source: - Add data source: `Prometheus` - Connection URL: `http://localhost:9090` - Click `Save & test` 1. Create your first dashboard - Import dashboard - Upload dashboard JSON file: you can try `ejabberd-dash.json` - prometheus: select the data source you created previously - Click `Import` tmpogm5kjkl/mod_prometheus/COPYING0000664000175000017500000004346414751665140020013 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. tmpogm5kjkl/mod_prometheus/example/0000775000175000017500000000000014751665140020400 5ustar debalancedebalancetmpogm5kjkl/mod_prometheus/example/docker-compose.yml0000664000175000017500000000107014751665140024033 0ustar debalancedebalanceversion: '3.7' services: prometheus: image: docker.io/prom/prometheus container_name: prometheus ports: - "9090:9090" volumes: - prometheus-data:/prometheus - ./prometheus.yml:/etc/prometheus/prometheus.yml restart: always grafana: image: docker.io/grafana/grafana-enterprise container_name: grafana ports: - "3000:3000" volumes: - grafana-data:/var/lib/grafana - ./grafana_defaults.ini:/usr/share/grafana/conf/defaults.ini restart: always volumes: prometheus-data: grafana-data: tmpogm5kjkl/mod_prometheus/example/ejabberd-dash.json0000664000175000017500000004276114751665140023760 0ustar debalancedebalance{ "__inputs": [ { "name": "DS_PROMETHEUS", "label": "prometheus", "description": "", "type": "datasource", "pluginId": "prometheus", "pluginName": "Prometheus" } ], "__elements": {}, "__requires": [ { "type": "grafana", "id": "grafana", "name": "Grafana", "version": "11.1.0" }, { "type": "datasource", "id": "prometheus", "name": "Prometheus", "version": "1.0.0" }, { "type": "panel", "id": "timeseries", "name": "Time series", "version": "" } ], "annotations": { "list": [ { "builtIn": 1, "datasource": { "type": "grafana", "uid": "-- Grafana --" }, "enable": true, "hide": true, "iconColor": "rgba(0, 211, 255, 1)", "name": "Annotations & Alerts", "type": "dashboard" } ] }, "editable": true, "fiscalYearStartMonth": 0, "graphTooltip": 0, "id": null, "links": [], "panels": [ { "collapsed": false, "gridPos": { "h": 1, "w": 24, "x": 0, "y": 0 }, "id": 4, "panels": [], "title": "Erlang VM", "type": "row" }, { "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" }, "description": "", "fieldConfig": { "defaults": { "color": { "mode": "palette-classic" }, "custom": { "axisBorderShow": false, "axisCenteredZero": false, "axisColorMode": "text", "axisLabel": "", "axisPlacement": "auto", "barAlignment": 0, "drawStyle": "bars", "fillOpacity": 0, "gradientMode": "none", "hideFrom": { "legend": false, "tooltip": false, "viz": false }, "insertNulls": false, "lineInterpolation": "linear", "lineWidth": 1, "pointSize": 5, "scaleDistribution": { "type": "linear" }, "showPoints": "auto", "spanNulls": false, "stacking": { "group": "A", "mode": "none" }, "thresholdsStyle": { "mode": "off" } }, "mappings": [], "thresholds": { "mode": "absolute", "steps": [ { "color": "green", "value": null }, { "color": "red", "value": 80 } ] } }, "overrides": [] }, "gridPos": { "h": 5, "w": 6, "x": 0, "y": 1 }, "id": 2, "options": { "legend": { "calcs": [], "displayMode": "list", "placement": "bottom", "showLegend": true }, "tooltip": { "mode": "single", "sort": "none" } }, "targets": [ { "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" }, "disableTextWrap": false, "editorMode": "builder", "expr": "erlang_vm_atom_count", "fullMetaSearch": false, "includeNullMetadata": true, "instant": false, "legendFormat": "__auto", "range": true, "refId": "A", "useBackend": false } ], "title": "Atoms", "type": "timeseries" }, { "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" }, "fieldConfig": { "defaults": { "color": { "mode": "palette-classic" }, "custom": { "axisBorderShow": false, "axisCenteredZero": false, "axisColorMode": "text", "axisLabel": "", "axisPlacement": "auto", "barAlignment": 0, "drawStyle": "bars", "fillOpacity": 0, "gradientMode": "none", "hideFrom": { "legend": false, "tooltip": false, "viz": false }, "insertNulls": false, "lineInterpolation": "linear", "lineWidth": 1, "pointSize": 5, "scaleDistribution": { "type": "linear" }, "showPoints": "auto", "spanNulls": false, "stacking": { "group": "A", "mode": "none" }, "thresholdsStyle": { "mode": "off" } }, "mappings": [], "thresholds": { "mode": "absolute", "steps": [ { "color": "green", "value": null }, { "color": "red", "value": 80 } ] } }, "overrides": [] }, "gridPos": { "h": 5, "w": 5, "x": 6, "y": 1 }, "id": 7, "options": { "legend": { "calcs": [], "displayMode": "list", "placement": "bottom", "showLegend": true }, "tooltip": { "mode": "single", "sort": "none" } }, "targets": [ { "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" }, "disableTextWrap": false, "editorMode": "builder", "expr": "erlang_vm_process_count", "fullMetaSearch": false, "includeNullMetadata": true, "instant": false, "legendFormat": "processes", "range": true, "refId": "processes", "useBackend": false } ], "title": "Processes", "type": "timeseries" }, { "collapsed": false, "gridPos": { "h": 1, "w": 24, "x": 0, "y": 6 }, "id": 5, "panels": [], "title": "Users", "type": "row" }, { "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" }, "fieldConfig": { "defaults": { "color": { "mode": "palette-classic" }, "custom": { "axisBorderShow": false, "axisCenteredZero": false, "axisColorMode": "text", "axisLabel": "", "axisPlacement": "auto", "barAlignment": 0, "drawStyle": "line", "fillOpacity": 0, "gradientMode": "none", "hideFrom": { "legend": false, "tooltip": false, "viz": false }, "insertNulls": false, "lineInterpolation": "linear", "lineWidth": 1, "pointSize": 5, "scaleDistribution": { "type": "linear" }, "showPoints": "auto", "spanNulls": false, "stacking": { "group": "A", "mode": "none" }, "thresholdsStyle": { "mode": "off" } }, "mappings": [], "thresholds": { "mode": "absolute", "steps": [ { "color": "green", "value": null }, { "color": "red", "value": 80 } ] } }, "overrides": [] }, "gridPos": { "h": 6, "w": 6, "x": 0, "y": 7 }, "id": 1, "options": { "legend": { "calcs": [], "displayMode": "list", "placement": "bottom", "showLegend": true }, "tooltip": { "mode": "single", "sort": "none" } }, "targets": [ { "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" }, "disableTextWrap": false, "editorMode": "builder", "expr": "erlang_mnesia_tablewise_size{table=\"passwd\"}", "fullMetaSearch": false, "includeNullMetadata": true, "instant": false, "legendFormat": "registered", "range": true, "refId": "A", "useBackend": false }, { "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" }, "disableTextWrap": false, "editorMode": "builder", "expr": "erlang_mnesia_tablewise_size{table=\"session\"}", "fullMetaSearch": false, "hide": false, "includeNullMetadata": true, "instant": false, "legendFormat": "online", "range": true, "refId": "B", "useBackend": false } ], "title": "Accounts", "type": "timeseries" }, { "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" }, "fieldConfig": { "defaults": { "color": { "mode": "palette-classic" }, "custom": { "axisBorderShow": false, "axisCenteredZero": false, "axisColorMode": "text", "axisLabel": "", "axisPlacement": "auto", "barAlignment": 0, "drawStyle": "bars", "fillOpacity": 0, "gradientMode": "none", "hideFrom": { "legend": false, "tooltip": false, "viz": false }, "insertNulls": false, "lineInterpolation": "linear", "lineWidth": 1, "pointSize": 5, "scaleDistribution": { "type": "linear" }, "showPoints": "auto", "spanNulls": false, "stacking": { "group": "A", "mode": "none" }, "thresholdsStyle": { "mode": "off" } }, "mappings": [], "thresholds": { "mode": "absolute", "steps": [ { "color": "green", "value": null }, { "color": "red", "value": 80 } ] } }, "overrides": [] }, "gridPos": { "h": 6, "w": 5, "x": 6, "y": 7 }, "id": 9, "options": { "legend": { "calcs": [], "displayMode": "list", "placement": "bottom", "showLegend": true }, "tooltip": { "mode": "single", "sort": "none" } }, "targets": [ { "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" }, "disableTextWrap": false, "editorMode": "builder", "expr": "erlang_mnesia_tablewise_size{table=\"offline_msg\"}", "fullMetaSearch": false, "includeNullMetadata": true, "instant": false, "legendFormat": "total count", "range": true, "refId": "A", "useBackend": false } ], "title": "Offline messages", "type": "timeseries" }, { "collapsed": false, "gridPos": { "h": 1, "w": 24, "x": 0, "y": 13 }, "id": 6, "panels": [], "title": "MUC", "type": "row" }, { "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" }, "fieldConfig": { "defaults": { "color": { "mode": "palette-classic" }, "custom": { "axisBorderShow": false, "axisCenteredZero": false, "axisColorMode": "text", "axisLabel": "", "axisPlacement": "auto", "barAlignment": 0, "drawStyle": "line", "fillOpacity": 0, "gradientMode": "none", "hideFrom": { "legend": false, "tooltip": false, "viz": false }, "insertNulls": false, "lineInterpolation": "linear", "lineWidth": 1, "pointSize": 5, "scaleDistribution": { "type": "linear" }, "showPoints": "auto", "spanNulls": false, "stacking": { "group": "A", "mode": "none" }, "thresholdsStyle": { "mode": "off" } }, "mappings": [], "thresholds": { "mode": "absolute", "steps": [ { "color": "green", "value": null }, { "color": "red", "value": 80 } ] } }, "overrides": [] }, "gridPos": { "h": 6, "w": 6, "x": 0, "y": 14 }, "id": 3, "options": { "legend": { "calcs": [], "displayMode": "list", "placement": "bottom", "showLegend": true }, "tooltip": { "mode": "single", "sort": "none" } }, "targets": [ { "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" }, "disableTextWrap": false, "editorMode": "builder", "expr": "erlang_mnesia_tablewise_size{table=\"muc_online_room\"}", "fullMetaSearch": false, "includeNullMetadata": true, "instant": false, "legendFormat": "online", "range": true, "refId": "online", "useBackend": false }, { "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" }, "disableTextWrap": false, "editorMode": "builder", "expr": "erlang_mnesia_tablewise_size{table=\"muc_room\"}", "fullMetaSearch": false, "hide": false, "includeNullMetadata": true, "instant": false, "legendFormat": "total", "range": true, "refId": "total", "useBackend": false } ], "title": "MUC Rooms", "type": "timeseries" }, { "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" }, "description": "Nicks registered in the MUC Service", "fieldConfig": { "defaults": { "color": { "mode": "palette-classic" }, "custom": { "axisBorderShow": false, "axisCenteredZero": false, "axisColorMode": "text", "axisLabel": "", "axisPlacement": "auto", "barAlignment": 0, "drawStyle": "bars", "fillOpacity": 0, "gradientMode": "none", "hideFrom": { "legend": false, "tooltip": false, "viz": false }, "insertNulls": false, "lineInterpolation": "linear", "lineWidth": 1, "pointSize": 5, "scaleDistribution": { "type": "linear" }, "showPoints": "auto", "spanNulls": false, "stacking": { "group": "A", "mode": "none" }, "thresholdsStyle": { "mode": "off" } }, "mappings": [], "thresholds": { "mode": "absolute", "steps": [ { "color": "green", "value": null }, { "color": "red", "value": 80 } ] } }, "overrides": [] }, "gridPos": { "h": 6, "w": 5, "x": 6, "y": 14 }, "id": 8, "options": { "legend": { "calcs": [], "displayMode": "list", "placement": "bottom", "showLegend": true }, "tooltip": { "mode": "single", "sort": "none" } }, "targets": [ { "datasource": { "type": "prometheus", "uid": "${DS_PROMETHEUS}" }, "disableTextWrap": false, "editorMode": "builder", "exemplar": false, "expr": "erlang_mnesia_tablewise_size{table=\"muc_registered\"}", "fullMetaSearch": false, "includeNullMetadata": true, "instant": false, "legendFormat": "nicks", "range": true, "refId": "A", "useBackend": false } ], "title": "Registered nicks", "type": "timeseries" } ], "refresh": "5s", "schemaVersion": 39, "tags": [ "ejabberd", "xmpp", "jabber" ], "templating": { "list": [] }, "time": { "from": "now-30m", "to": "now" }, "timepicker": {}, "timezone": "browser", "title": "ejabberd-dash", "uid": "adqj20f610kcgd", "version": 2, "weekStart": "" }tmpogm5kjkl/mod_prometheus/example/prometheus.yml0000664000175000017500000000146514751665140023324 0ustar debalancedebalanceglobal: scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is every 1 minute. evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute. # scrape_timeout is set to the global default (10s). # Alertmanager configuration alerting: alertmanagers: - static_configs: - targets: # - alertmanager:9093 # Load rules once and periodically evaluate them according to the global 'evaluation_interval'. rule_files: # - "first_rules.yml" # - "second_rules.yml" # A scrape configuration containing exactly one endpoint to scrape: # Here it's Prometheus itself. scrape_configs: - job_name: "prometheus" static_configs: - targets: ["localhost:9090"] - job_name: "ejabberd" static_configs: - targets: ["localhost:5289"] tmpogm5kjkl/mod_prometheus/conf/0000775000175000017500000000000014751665140017672 5ustar debalancedebalancetmpogm5kjkl/mod_prometheus/conf/mod_prometheus.yml0000664000175000017500000000335714751665140023457 0ustar debalancedebalancelisten: - port: 5289 ip: "::" module: ejabberd_http request_handlers: /metrics: mod_prometheus modules: mod_prometheus: mnesia: true vm: memory: true system_info: true statistics: false distribution: false microstate_accounting: false hooks: # Histogram for a hook: - hook: user_send_packet type: histogram help: "Handling of sent messages duration in millisecond" labels: - host - stanza # Histogram for all modules of a hook: - hook: user_receive_packet type: histogram help: "Handling of received messages duration in millisecond" labels: - host - stanza - module # Counter for a hook: - hook: sm_register_connection_hook type: counter labels: - host - stanza # Counter for all modules of a hook: - hook: sm_remove_connection_hook type: counter labels: - host - stanza - module help: "Number of closed c2s sessions" # Histogram for some modules (callbacks) of a hook: - hook: user_send_packet type: histogram labels: - host collect: - module: mod_carboncopy function: user_send_packet help: "Handling of carbon copied messages in millisecond" - module: mod_mam function: user_send_packet help: "Handling of MAM messages in millisecond" labels: # It also inherits above `host` label - stanza buckets: - 10 - 100 - 750 - 1000 - 1500 tmpogm5kjkl/mod_prometheus/mod_prometheus.spec0000664000175000017500000000035014751665140022651 0ustar debalancedebalanceauthor: "Pouriya Jahanbakhsh " category: "stats" summary: "Prometheus metrics" home: "https://github.com/processone/ejabberd-contrib/tree/master/" url: "git@github.com:processone/ejabberd-contrib.git" tmpogm5kjkl/mod_push_offline/0000775000175000017500000000000014751665140017233 5ustar debalancedebalancetmpogm5kjkl/mod_push_offline/src/0000775000175000017500000000000014751665140020022 5ustar debalancedebalancetmpogm5kjkl/mod_push_offline/src/mod_push_offline_opt.erl0000664000175000017500000000037114751665140024731 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). tmpogm5kjkl/mod_push_offline/src/mod_push_offline.erl0000664000175000017500000001220314751665140024044 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">>).tmpogm5kjkl/mod_push_offline/mod_push_offline.spec0000664000175000017500000000036414751665140023432 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" tmpogm5kjkl/mod_push_offline/README.md0000664000175000017500000001133714751665140020517 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? ``` tmpogm5kjkl/mod_push_offline/COPYING0000664000175000017500000010451514751665140020274 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 . tmpogm5kjkl/mod_push_offline/conf/0000775000175000017500000000000014751665140020160 5ustar debalancedebalancetmpogm5kjkl/mod_push_offline/conf/mod_push_offline.yml0000664000175000017500000000003714751665140024223 0ustar debalancedebalancemodules: mod_push_offline: {}tmpogm5kjkl/ejabberd_observer_cli/0000775000175000017500000000000014751665140020207 5ustar debalancedebalancetmpogm5kjkl/ejabberd_observer_cli/rebar.config0000664000175000017500000000036714751665140022477 0ustar debalancedebalance{deps, [ {observer_cli, ".*", {git, "https://github.com/zhongwencool/observer_cli"}}, {os_stats, ".*", {git, "https://github.com/zhongwencool/os_stats"}}, {recon, "2.5.5", {git, "https://github.com/ferd/recon"}} ]}. tmpogm5kjkl/ejabberd_observer_cli/src/0000775000175000017500000000000014751665140020776 5ustar debalancedebalancetmpogm5kjkl/ejabberd_observer_cli/src/ejabberd_observer_cli_muc.erl0000664000175000017500000000253114751665140026643 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}. tmpogm5kjkl/ejabberd_observer_cli/src/ejabberd_observer_cli_users.erl0000664000175000017500000000610314751665140027217 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. tmpogm5kjkl/ejabberd_observer_cli/src/ejabberd_observer_cli_userstophost.erl0000664000175000017500000000347114751665140030645 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}. tmpogm5kjkl/ejabberd_observer_cli/src/ejabberd_observer_cli_vhosts.erl0000664000175000017500000000451614751665140027412 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}. tmpogm5kjkl/ejabberd_observer_cli/src/ejabberd_observer_cli.erl0000664000175000017500000000231514751665140025777 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 } ]. tmpogm5kjkl/ejabberd_observer_cli/ejabberd_observer_cli.spec0000664000175000017500000000034614751665140025362 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" tmpogm5kjkl/ejabberd_observer_cli/README.md0000664000175000017500000000222414751665140021466 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/ tmpogm5kjkl/ejabberd_observer_cli/COPYING0000664000175000017500000004346414751665140021255 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. tmpogm5kjkl/mod_isolation/0000775000175000017500000000000014751665140016553 5ustar debalancedebalancetmpogm5kjkl/mod_isolation/src/0000775000175000017500000000000014751665140017342 5ustar debalancedebalancetmpogm5kjkl/mod_isolation/src/mod_isolation.erl0000664000175000017500000000511014751665140022703 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. tmpogm5kjkl/mod_isolation/README.md0000664000175000017500000000071614751665140020036 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: {} ``` tmpogm5kjkl/mod_isolation/mod_isolation.spec0000664000175000017500000000040414751665140022265 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" tmpogm5kjkl/mod_isolation/COPYING0000664000175000017500000004346414751665140017621 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. tmpogm5kjkl/mod_isolation/conf/0000775000175000017500000000000014751665140017500 5ustar debalancedebalancetmpogm5kjkl/mod_isolation/conf/mod_isolation.yml0000664000175000017500000000013514751665140023062 0ustar debalancedebalancemodules: mod_isolation: {} ### If you want to block whole s2s as well: # s2s_access: none tmpogm5kjkl/mod_example/0000775000175000017500000000000014751665140016205 5ustar debalancedebalancetmpogm5kjkl/mod_example/rebar.config0000664000175000017500000000002414751665140020463 0ustar debalancedebalance{deps, [ ]}. tmpogm5kjkl/mod_example/src/0000775000175000017500000000000014751665140016774 5ustar debalancedebalancetmpogm5kjkl/mod_example/src/mod_example.erl0000664000175000017500000005637514751665140022012 0ustar debalancedebalance%%%------------------------------------------------------------------- %%% File : mod_example.erl %%% Author : Author Name %%% Purpose : Example ejabberd module %%% Created : %%% %%% %%% ejabberd, Copyright (C) 2002-2024 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. %%% %%%------------------------------------------------------------------- %%%% definitions %% @format-begin -module(mod_example). -author('name@example.org'). %% %% gen_mod -behaviour(gen_mod). -export([start/2, stop/1, reload/3, mod_options/1, depends/2, mod_doc/0]). -include("logger.hrl"). -include_lib("xmpp/include/xmpp.hrl"). %% %% commands -export([get_commands_spec/0]). -export([apiversion0/0, apiversion2/0, apizero/0, apione/0, integer/1, string/1, binary/1, tuple/1, list/1, list_tuple/1, atom/1, rescode/1, restuple/2, all/6]). -include("ejabberd_commands.hrl"). -include("translate.hrl"). %% %% hooks %% run event -export([run_hook_global/0, run_hook_host/1, run_hook_fold_global/0, run_hook_fold_host/1]). %% add hook -export([example_hook_global_function1/2, example_hook_global_function2/2, example_hook_global_function3/2]). -export([example_hook_host_subs/5]). -export([example_hook_host_function1/2, example_hook_host_function2/2, example_hook_host_function3/2]). -export([example_hook_fold_global_function1/3, example_hook_fold_global_function2/3, example_hook_fold_global_function3/3]). -export([example_hook_fold_host_function1/3, example_hook_fold_host_function2/3, example_hook_fold_host_function3/3]). %% %% iqdisc %% %% webadmin %%%================================== %%%% gen_mod start(Host, _Opts) -> register_commands(), register_hooks(), register_hooks(Host), register_hooks_fold(), register_hooks_fold(Host), register_hooks_commands(), %register_iq_handlers(Host), ok. stop(Host) -> unregister_commands(Host), unregister_hooks(), unregister_hooks(Host), unregister_hooks_fold(), unregister_hooks_fold(Host), unregister_hooks_commands(Host), %unregister_iq_handlers(Host), ok. reload(_Host, _NewOpts, _OldOpts) -> ok. depends(_Host, _Opts) -> []. mod_options(_) -> []. mod_doc() -> #{desc => [?T("This is an example module."), "", ?T("Here you can also find example code for some ejabberd features:"), "", ?T("- commands"), ?T("- hooks"), ?T("- iqdisc"), ?T("- WebAdmin"), "", ?T("You can copy this file, remove the unnecessary code, " "adapt the useful one and add your features.")], example => [{?T("This is an example configuration:"), ["modules:", " mod_example:", " - resource: \"modadminextraf8x,31ad\""]}, {?T("Call to srg-create using double-quotes and single-quotes:"), ["ejabberdctl srg-create g1 example.org \"\'Group number 1\'\" this_is_g1 g1"]}]}. %%%================================== %%%% commands: define register_commands() -> ejabberd_commands:register_commands(?MODULE, get_commands_spec()). unregister_commands(Host) -> case gen_mod:is_loaded_elsewhere(Host, ?MODULE) of false -> ejabberd_commands:unregister_commands(get_commands_spec()); true -> ok end. get_commands_spec() -> [#ejabberd_commands{name = command_test_apiversion, tags = [test], desc = "Command to test apiversion", module = ?MODULE, function = apiversion0, version = 0, args = [], result = {apiversion, integer}, args_example = [], result_example = 0}, #ejabberd_commands{name = command_test_apiversion, tags = [test], desc = "Command to test apiversion", module = ?MODULE, function = apiversion2, version = 2, args = [], result = {apiversion, integer}, args_example = [], result_example = 2}, #ejabberd_commands{name = command_test_apizero, tags = [test], desc = "Command to test apizero", module = ?MODULE, function = apizero, args = [], result = {apiversion, integer}, args_example = [], result_example = 0}, #ejabberd_commands{name = command_test_apione, tags = [test], desc = "Command to test apione", module = ?MODULE, function = apione, version = 1, args = [], result = {apiversion, integer}, args_example = [], result_example = 0}, #ejabberd_commands{name = command_test_integer, tags = [test], desc = "Command to test integer", module = ?MODULE, function = integer, args = [{arg_integer, integer}], result = {res_integer, integer}, args_example = [7], result_example = 7}, #ejabberd_commands{name = command_test_string, tags = [test], desc = "Command to test string", module = ?MODULE, function = string, args = [{arg_string, string}], result = {res_string, string}, args_example = ["Some string."], result_example = "Some string"}, #ejabberd_commands{name = command_test_binary, tags = [test], desc = "Command to test binary", module = ?MODULE, function = binary, args = [{arg_binary, binary}], result = {res_string, string}, args_example = ["Some binary."], result_example = "Some binary"}, #ejabberd_commands{name = command_test_tuple, tags = [test], desc = "Command to test tuple", module = ?MODULE, function = tuple, args = [{arg_tuple, {tuple, [{element1, string}, {element2, string}, {element3, string}]}}], result = {res_tuple, {tuple, [{element1, string}, {element2, string}, {element3, string}]}}, args_example = [{"one", "first", "primary"}], result_example = {"one", "first", "primary"}}, #ejabberd_commands{name = command_test_list, tags = [test], desc = "Command to test list", module = ?MODULE, function = list, args = [{arg_list, {list, {element, string}}}], result = {res_list, {list, {element, string}}}, args_example = [["one", "two", "three"]], result_example = ["one", "two", "three"]}, #ejabberd_commands{name = command_test_list_tuple, tags = [test], desc = "Command to test list of tuples", module = ?MODULE, function = list_tuple, args = [{arg_list, {list, {list_tuple, {tuple, [{element1, string}, {element2, string}]}}}}], result = {res_list, {list, {list_tuple, {tuple, [{element1, string}, {element2, string}]}}}}, args_example = [[{"one", "uno"}, {"two", "dos"}, {"three", "tres"}]], result_example = [{"one", "uno"}, {"two", "dos"}, {"three", "tres"}]}, #ejabberd_commands{name = command_test_atom, tags = [test], desc = "Command to test atom result", module = ?MODULE, function = atom, args = [{arg_string, string}], result = {res_atom, atom}, args_example = ["Some string."], result_example = 'Some string'}, #ejabberd_commands{name = command_test_rescode, tags = [test], desc = "Command to test rescode result", module = ?MODULE, function = rescode, args = [{code, string}], result = {res_atom, rescode}, args_example = ["ok"], result_example = 0}, #ejabberd_commands{name = command_test_restuple, tags = [test], desc = "Command to test restuple result", module = ?MODULE, function = restuple, args = [{code, string}, {text, string}], result = {res_atom, restuple}, args_example = ["ok", "Some result text"], result_example = {ok, <<"Some result text">>}}, #ejabberd_commands{name = command_test_all, tags = [test], desc = "Test command that requires all argument types and returns all result types", module = ?MODULE, function = all, args = [{arg_integer, integer}, {arg_string, string}, {arg_binary, binary}, {arg_tuple, {tuple, [{tuple_integer, integer}, {tuple_string, string}]}}, {arg_list, {list, {list_string, string}}}, {arg_listtuple, {list, {list_tuple, {tuple, [{list_tuple_integer, integer}, {list_tuple_string, string}]}}}}], result = {response, {tuple, [{arg_integer, integer}, {arg_string, string}, {arg_atom, atom}, {arg_tuple, {tuple, [{tuple_integer, integer}, {tuple_string, string}]}}, {arg_list, {list, {list_string, string}}}, {arg_listtuple, {list, {list_tuple, {tuple, [{list_tuple_integer, integer}, {list_tuple_string, string}]}}}}]}}}]. %%%================================== %%%% commands: implement apiversion0() -> 0. apiversion2() -> 2. apizero() -> 0. apione() -> 1. integer(Integer) when is_integer(Integer) -> Integer. string([Char | _] = String) when is_list(String) and is_integer(Char) -> String. binary(Binary) when is_binary(Binary) -> Binary. tuple({T1, T2, T3}) -> {T1, T2, T3}. list([Head | _] = List) when is_list(List) and is_list(Head) -> List. list_tuple(ListTuple) when is_list(ListTuple) -> ListTuple. atom(String) when is_list(String) -> list_to_atom(String). rescode(Code) when Code == "true"; Code == "ok" -> list_to_atom(Code); rescode(Other) -> Other. restuple(Code, Text) when Code == "true"; Code == "ok" -> {list_to_atom(Code), Text}; restuple(Other, Text) -> {list_to_atom(Other), Text}. all(Integer, [Char | _] = String, Binary, {_T1, _T2} = Tuple, [Head | _] = List, ListTuple) when is_integer(Integer) and is_list(String) and is_integer(Char) and is_binary(Binary) and is_list(List) and is_list(Head) and is_list(ListTuple) -> {Integer, String, misc:binary_to_atom(Binary), Tuple, List, ListTuple}. %%%================================== %%%% hooks: run hooks register_hooks_commands() -> ejabberd_commands:register_commands(?MODULE, get_hooks_commands_spec()). unregister_hooks_commands(Host) -> case gen_mod:is_loaded_elsewhere(Host, ?MODULE) of false -> ejabberd_commands:unregister_commands(get_hooks_commands_spec()); true -> ok end. get_hooks_commands_spec() -> [#ejabberd_commands{name = run_hook_global, tags = [test], module = ?MODULE, function = run_hook_global, args = [], result = {res, rescode}}, #ejabberd_commands{name = run_hook_host, tags = [test], module = ?MODULE, function = run_hook_host, args = [{host, binary}], result = {res, rescode}}, #ejabberd_commands{name = run_hook_fold_global, tags = [test], module = ?MODULE, function = run_hook_fold_global, args = [], result = {functions, {list, {function, string}}}}, #ejabberd_commands{name = run_hook_fold_host, tags = [test], module = ?MODULE, function = run_hook_fold_host, args = [{host, binary}], result = {functions, {list, {function, string}}}}]. run_hook_global() -> Arg1 = "arg1", Arg2 = "arg2", ejabberd_hooks:run(example_hook_global, [Arg1, Arg2]). run_hook_host(Host) -> Arg1 = "arg1", Arg2 = "arg2", ejabberd_hooks:run(example_hook_host, Host, [Arg1, Arg2]). run_hook_fold_global() -> Arg1 = "arg1", Arg2 = "arg2", ejabberd_hooks:run_fold(example_hook_fold_global, [], [Arg1, Arg2]). run_hook_fold_host(Host) -> Arg1 = "arg1", Arg2 = "arg2", ejabberd_hooks:run_fold(example_hook_fold_host, Host, [], [Arg1, Arg2]). %%%================================== %%%% hooks: add global register_hooks() -> ejabberd_hooks:add(example_hook_global, ?MODULE, example_hook_global_function1, 81), ejabberd_hooks:add(example_hook_global, ?MODULE, example_hook_global_function2, 82), ejabberd_hooks:add(example_hook_global, ?MODULE, example_hook_global_function3, 83). unregister_hooks() -> ejabberd_hooks:delete(example_hook_global, ?MODULE, example_hook_global_function1, 81), ejabberd_hooks:delete(example_hook_global, ?MODULE, example_hook_global_function2, 82), ejabberd_hooks:delete(example_hook_global, ?MODULE, example_hook_global_function3, 83). example_hook_global_function1(Arg1, Arg2) -> io:format("~nexample_hook_global_function1: ~n" " Arg1: ~p~n Arg2: ~p~n" " continue...~n", [Arg1, Arg2]). example_hook_global_function2(Arg1, Arg2) -> io:format("~nexample_hook_global_function2: ~n" " Arg1: ~p~n Arg2: ~p~n" " stop.~n~n", [Arg1, Arg2]), stop. %% As function2 returns stop, function3 will not be called example_hook_global_function3(Arg1, Arg2) -> io:format("~nexample_hook_global_function3: ~n" " Arg1: ~p~n Arg2: ~p~n~n", [Arg1, Arg2]). %%%================================== %%%% hooks: add host register_hooks(Host) -> ejabberd_hooks:subscribe(example_hook_host, Host, ?MODULE, example_hook_host_subs, init_args), ejabberd_hooks:add(example_hook_host, Host, ?MODULE, example_hook_host_function1, 81), ejabberd_hooks:add(example_hook_host, Host, ?MODULE, example_hook_host_function2, 82), ejabberd_hooks:add(example_hook_host, Host, ?MODULE, example_hook_host_function3, 83). unregister_hooks(Host) -> ejabberd_hooks:delete(example_hook_host, Host, ?MODULE, example_hook_host_function1, 81), ejabberd_hooks:delete(example_hook_host, Host, ?MODULE, example_hook_host_function2, 82), ejabberd_hooks:delete(example_hook_host, Host, ?MODULE, example_hook_host_function3, 83). example_hook_host_subs(InitArgs, Time, Host, Hook, Args) -> io:format("~nexample_hook_host_subs: ~n" " InitArgs: ~p~n" " Time: ~p~n" " Host: ~p~n" " Hook: ~p~n" " Args: ~p~n", [InitArgs, Time, Host, Hook, Args]), ok. example_hook_host_function1(Arg1, Arg2) -> io:format("~nexample_hook_host_function1: ~n" " Arg1: ~p~n Arg2: ~p~n" " continue...~n", [Arg1, Arg2]). example_hook_host_function2(Arg1, Arg2) -> io:format("~nexample_hook_host_function2: ~n" " Arg1: ~p~n Arg2: ~p~n" " stop.~n~n", [Arg1, Arg2]), stop. %% As function2 returns stop, function3 will not be called example_hook_host_function3(Arg1, Arg2) -> io:format("~nexample_hook_host_function3: ~n" " Arg1: ~p~n Arg2: ~p~n~n", [Arg1, Arg2]). %%%================================== %%%% hooks: add global fold register_hooks_fold() -> ejabberd_hooks:add(example_hook_fold_global, ?MODULE, example_hook_fold_global_function1, 81), ejabberd_hooks:add(example_hook_fold_global, ?MODULE, example_hook_fold_global_function2, 82), ejabberd_hooks:add(example_hook_fold_global, ?MODULE, example_hook_fold_global_function3, 83). unregister_hooks_fold() -> ejabberd_hooks:delete(example_hook_fold_global, ?MODULE, example_hook_fold_global_function1, 81), ejabberd_hooks:delete(example_hook_fold_global, ?MODULE, example_hook_fold_global_function2, 82), ejabberd_hooks:delete(example_hook_fold_global, ?MODULE, example_hook_fold_global_function3, 83). example_hook_fold_global_function1(Acc0, Arg1, Arg2) -> io:format("~nexample_hook_fold_global_function1: ~n" " Acc: ~p~n Arg1: ~p~n Arg2: ~p~n" " continue...~n", [Acc0, Arg1, Arg2]), [example_hook_fold_global_function1 | Acc0]. example_hook_fold_global_function2(Acc0, Arg1, Arg2) -> io:format("~nexample_hook_fold_global_function2: ~n" " Acc: ~p~n Arg1: ~p~n Arg2: ~p~n" " stop.~n~n", [Acc0, Arg1, Arg2]), {stop, [example_hook_fold_global_function2 | Acc0]}. %% As function2 returns {stop, _}, function3 will not be called example_hook_fold_global_function3(Acc0, Arg1, Arg2) -> io:format("~nexample_hook_fold_global_function3: ~n" " Acc: ~p~n Arg1: ~p~n Arg2: ~p~n~n", [Acc0, Arg1, Arg2]), [example_hook_fold_global_function3 | Acc0]. %%%================================== %%%% hooks: add host fold register_hooks_fold(Host) -> ejabberd_hooks:add(example_hook_fold_host, Host, ?MODULE, example_hook_fold_host_function1, 81), ejabberd_hooks:add(example_hook_fold_host, Host, ?MODULE, example_hook_fold_host_function2, 82), ejabberd_hooks:add(example_hook_fold_host, Host, ?MODULE, example_hook_fold_host_function3, 83). unregister_hooks_fold(Host) -> ejabberd_hooks:delete(example_hook_fold_host, Host, ?MODULE, example_hook_fold_host_function1, 81), ejabberd_hooks:delete(example_hook_fold_host, Host, ?MODULE, example_hook_fold_host_function2, 82), ejabberd_hooks:delete(example_hook_fold_host, Host, ?MODULE, example_hook_fold_host_function3, 83). example_hook_fold_host_function1(Acc0, Arg1, Arg2) -> io:format("~nexample_hook_fold_host_function1: ~n" " Acc: ~p~n Arg1: ~p~n Arg2: ~p~n" " continue...~n", [Acc0, Arg1, Arg2]), [example_hook_fold_host_function1 | Acc0]. example_hook_fold_host_function2(Acc0, Arg1, Arg2) -> io:format("~nexample_hook_fold_host_function2: ~n" " Acc: ~p~n Arg1: ~p~n Arg2: ~p~n" " stop.~n~n", [Acc0, Arg1, Arg2]), {stop, [example_hook_fold_host_function2 | Acc0]}. %% As function2 returns {stop, _}, function3 will not be called example_hook_fold_host_function3(Acc0, Arg1, Arg2) -> io:format("~nexample_hook_fold_host_function3: ~n" " Acc: ~p~n Arg1: ~p~n Arg2: ~p~n~n", [Acc0, Arg1, Arg2]), [example_hook_fold_host_function3 | Acc0]. %%%================================== %%%% iqdisc %register_iq_handlers(Host) -> % gen_iq_handler:add_iq_handler(ejabberd_sm, Host, ?NS_PING, ?MODULE, iq_ping), % gen_iq_handler:add_iq_handler(ejabberd_local, Host, ?NS_PING, ?MODULE, iq_ping). %unregister_iq_handlers(Host) -> % gen_iq_handler:remove_iq_handler(ejabberd_local, Host, ?NS_PING), % gen_iq_handler:remove_iq_handler(ejabberd_sm, Host, ?NS_PING). %%%================================== %%%% webadmin %%%================================== %%% vim: set foldmethod=marker foldmarker=%%%%,%%%=: tmpogm5kjkl/mod_example/mod_example.spec0000664000175000017500000000036614751665140021360 0ustar debalancedebalanceauthor: "Author name " category: "example" summary: "Example ejabberd module for testing and development" home: "https://github.com/processone/ejabberd-contrib/tree/master/" url: "git@github.com:processone/ejabberd-contrib.git" tmpogm5kjkl/mod_example/README.md0000664000175000017500000000066314751665140017471 0ustar debalancedebalancemod_example - Example ejabberd module ==================================== - Requires: ejabberd 24.06 or higher - Author: Author name This is an example ejabberd module. Right now it includes example use of commands and hooks. In the future, it could also include examples of module options, documentation, webadmin pages, iq handlers ... Copy those files, rename, modify as you please. Options ------- No configurable options. tmpogm5kjkl/mod_example/COPYING0000664000175000017500000004346414751665140017253 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. tmpogm5kjkl/mod_example/conf/0000775000175000017500000000000014751665140017132 5ustar debalancedebalancetmpogm5kjkl/mod_example/conf/mod_example.yml0000664000175000017500000000003314751665140022143 0ustar debalancedebalancemodules: mod_example: {} tmpogm5kjkl/mod_statsdx/0000775000175000017500000000000014751665140016244 5ustar debalancedebalancetmpogm5kjkl/mod_statsdx/src/0000775000175000017500000000000014751665140017033 5ustar debalancedebalancetmpogm5kjkl/mod_statsdx/src/mod_statsdx.erl0000664000175000017500000020252314751665140022074 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/3, web_page_node/5, % ejabberd 24.02 or older 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">>}]. %% ejabberd 24.02 or older web_user(Acc, User, Host, Lang) when is_binary(Lang) -> EmptyRequest = #request{method = 'GET', raw_path = <<"">>, ip = {{127,0,0,1}, 0}, lang = Lang, sockmod = 'gen_tcp', socket = hd(erlang:ports())}, web_user(Acc, User, Host, EmptyRequest); web_user(Acc, User, Host, #request{lang = 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. %% ejabberd 24.02 or older web_page_node(Acc, Node, Path, Query, Lang) -> web_page_node(Acc, Node, #request{method = 'GET', raw_path = <<"">>, ip = {{127,0,0,1}, 0}, sockmod = 'gen_tcp', socket = hd(erlang:ports()), path = Path, q = Query, lang = Lang}). web_page_node(_, Node, #request{path = [<<"statsdx">>], lang = 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=%%%%,%%%=: tmpogm5kjkl/mod_statsdx/src/mod_stats2file.erl0000664000175000017500000002332314751665140022461 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]) ). tmpogm5kjkl/mod_statsdx/mod_statsdx.spec0000664000175000017500000000035714751665140021456 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" tmpogm5kjkl/mod_statsdx/README.md0000664000175000017500000000430414751665140017524 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"] ``` tmpogm5kjkl/mod_statsdx/COPYING0000664000175000017500000004332414751665140017305 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. tmpogm5kjkl/mod_statsdx/ChangeLog0000664000175000017500000000350014751665140020014 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. tmpogm5kjkl/mod_statsdx/conf/0000775000175000017500000000000014751665140017171 5ustar debalancedebalancetmpogm5kjkl/mod_statsdx/conf/mod_statsdx.yml0000664000175000017500000000007214751665140022244 0ustar debalancedebalancemodules: mod_statsdx: hooks: false # hooks: true tmpogm5kjkl/mod_cron/0000775000175000017500000000000014751665140015513 5ustar debalancedebalancetmpogm5kjkl/mod_cron/src/0000775000175000017500000000000014751665140016302 5ustar debalancedebalancetmpogm5kjkl/mod_cron/src/mod_cron.erl0000664000175000017500000002400614751665140020610 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), Heir = {heir, whereis(ext_mod), ?MODULE}, catch ets:new(cron_tasks, [ordered_set, named_table, public, {keypos, 2}, Heir]), [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)])]. tmpogm5kjkl/mod_cron/README.md0000664000175000017500000001134514751665140016776 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. tmpogm5kjkl/mod_cron/COPYING0000664000175000017500000004332414751665140016554 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. tmpogm5kjkl/mod_cron/ChangeLog0000664000175000017500000000146014751665140017266 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. tmpogm5kjkl/mod_cron/mod_cron.spec0000664000175000017500000000033714751665140020172 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" tmpogm5kjkl/mod_cron/conf/0000775000175000017500000000000014751665140016440 5ustar debalancedebalancetmpogm5kjkl/mod_cron/conf/mod_cron.yml0000664000175000017500000000003214751665140020756 0ustar debalancedebalance#modules: # mod_cron: {} tmpogm5kjkl/mod_default_rooms/0000775000175000017500000000000014751665140017415 5ustar debalancedebalancetmpogm5kjkl/mod_default_rooms/src/0000775000175000017500000000000014751665140020204 5ustar debalancedebalancetmpogm5kjkl/mod_default_rooms/src/mod_default_rooms.erl0000664000175000017500000000771314751665140024422 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}. tmpogm5kjkl/mod_default_rooms/README.md0000664000175000017500000000163014751665140020674 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. tmpogm5kjkl/mod_default_rooms/mod_default_rooms.spec0000664000175000017500000000035714751665140024000 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" tmpogm5kjkl/mod_default_rooms/COPYING0000664000175000017500000004346414751665140020463 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. tmpogm5kjkl/mod_default_rooms/conf/0000775000175000017500000000000014751665140020342 5ustar debalancedebalancetmpogm5kjkl/mod_default_rooms/conf/mod_default_rooms.yml0000664000175000017500000000005714751665140024571 0ustar debalancedebalance#modules: # mod_default_rooms: # rooms: [] tmpogm5kjkl/mod_grafite/0000775000175000017500000000000014751665140016173 5ustar debalancedebalancetmpogm5kjkl/mod_grafite/src/0000775000175000017500000000000014751665140016762 5ustar debalancedebalancetmpogm5kjkl/mod_grafite/src/mod_grafite.erl0000664000175000017500000001437314751665140021756 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}]. tmpogm5kjkl/mod_grafite/README.md0000664000175000017500000000113114751665140017446 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 tmpogm5kjkl/mod_grafite/mod_grafite.spec0000664000175000017500000000040514751665140021326 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" tmpogm5kjkl/mod_grafite/conf/0000775000175000017500000000000014751665140017120 5ustar debalancedebalancetmpogm5kjkl/mod_grafite/conf/mod_grafite.yml0000664000175000017500000000012714751665140022123 0ustar debalancedebalance#modules: # mod_grafite: # statsdhost: "carbonr.xmpp.com.br" # statsdport: 8125 tmpogm5kjkl/mod_s2s_log/0000775000175000017500000000000014751665140016122 5ustar debalancedebalancetmpogm5kjkl/mod_s2s_log/mod_s2s_log.spec0000664000175000017500000000035514751665140021210 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" tmpogm5kjkl/mod_s2s_log/src/0000775000175000017500000000000014751665140016711 5ustar debalancedebalancetmpogm5kjkl/mod_s2s_log/src/mod_s2s_log.erl0000664000175000017500000001066714751665140021636 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). tmpogm5kjkl/mod_s2s_log/README.md0000664000175000017500000000044014751665140017377 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" ``` tmpogm5kjkl/mod_s2s_log/COPYING0000664000175000017500000004332414751665140017163 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. tmpogm5kjkl/mod_s2s_log/ChangeLog0000664000175000017500000000040214751665140017670 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 tmpogm5kjkl/mod_s2s_log/conf/0000775000175000017500000000000014751665140017047 5ustar debalancedebalancetmpogm5kjkl/mod_s2s_log/conf/mod_s2s_log.yml0000664000175000017500000000012614751665140022000 0ustar debalancedebalancemodules: mod_s2s_log: filename: auto # filename: "/var/log/ejabberd/s2s.log" tmpogm5kjkl/mod_logxml/0000775000175000017500000000000014751665140016054 5ustar debalancedebalancetmpogm5kjkl/mod_logxml/src/0000775000175000017500000000000014751665140016643 5ustar debalancedebalancetmpogm5kjkl/mod_logxml/src/mod_logxml.erl0000664000175000017500000002160514751665140021514 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : mod_logxml.erl %%% Author : Badlop %%% Purpose : Log XMPP packets to XML file %%% Created : %%% Id : %%%---------------------------------------------------------------------- -module(mod_logxml). -author('badlop@ono.com'). -behaviour(gen_mod). -export([start/2, init/6, stop/1, send_packet/1, receive_packet/1, mod_opt_type/1, mod_options/1, depends/2, mod_doc/0]). -include_lib("xmpp/include/xmpp.hrl"). -define(PROCNAME, ejabberd_mod_logxml). %% ------------------- %% Module control %% ------------------- start(Host, Opts) -> Logdir = case gen_mod:get_opt(logdir, Opts) of auto -> filename:dirname(ejabberd_logger:get_log_path()); LD -> LD end, Rd = case gen_mod:get_opt(rotate_days, Opts) of 0 -> no; Rd1 -> Rd1 end, Rf = case gen_mod:get_opt(rotate_megs, Opts) of 0 -> no; Rf1 -> Rf1*1024*1024 end, Rp = case gen_mod:get_opt(rotate_kpackets, Opts) of 0 -> no; Rp1 -> Rp1*1000 end, RotateO = {Rd, Rf, Rp}, CheckRKP = gen_mod:get_opt(check_rotate_kpackets, Opts), Orientation = gen_mod:get_opt(orientation, Opts), Stanza = gen_mod:get_opt(stanza, Opts), Direction = gen_mod:get_opt(direction, Opts), FilterO = { {orientation, Orientation}, {stanza, Stanza}, {direction, Direction}}, ShowIP = gen_mod:get_opt(show_ip, Opts), ejabberd_hooks:add(user_send_packet, Host, ?MODULE, send_packet, 90), ejabberd_hooks:add(user_receive_packet, Host, ?MODULE, receive_packet, 90), register(gen_mod:get_module_proc(Host, ?PROCNAME), spawn(?MODULE, init, [binary_to_list(Host), Logdir, RotateO, CheckRKP, ShowIP, FilterO])), ok. stop(Host) -> ejabberd_hooks:delete(user_send_packet, Host, ?MODULE, send_packet, 90), ejabberd_hooks:delete(user_receive_packet, Host, ?MODULE, receive_packet, 90), Proc = gen_mod:get_module_proc(Host, ?PROCNAME), Proc ! stop, {wait, Proc}. init(Host, Logdir, RotateO, CheckRKP, ShowIP, FilterO) -> {IoDevice, Filename, Gregorian_day} = open_file(Logdir, Host), loop(Host, IoDevice, Filename, Logdir, CheckRKP, RotateO, 0, Gregorian_day, ShowIP, FilterO). depends(_Host, _Opts) -> []. mod_doc() -> #{}. %% ------------------- %% Main %% ------------------- manage_rotate(Host, IoDevice, Filename, Logdir, RotateO, PacketC, Gregorian_day_log) -> {RO_days, RO_size, RO_packets} = RotateO, Rotate1 = case RO_packets of no -> false; PacketC -> true; _ -> false end, Filesize = filelib:file_size(Filename), Rotate2 = if RO_size == no -> false; Filesize >= RO_size -> true; true -> false end, Gregorian_day_today = get_gregorian_day(), Rotate3 = if RO_days == no -> false; (Gregorian_day_today - Gregorian_day_log) >= RO_days -> true; true -> false end, case lists:any(fun(E) -> E end, [Rotate1, Rotate2, Rotate3]) of true -> {IoDevice2, Filename2, Gregorian_day2} = rotate_log(IoDevice, Logdir, Host), {IoDevice2, Filename2, Gregorian_day2, 0}; false -> {IoDevice, Filename, Gregorian_day_log, PacketC+1} end. filter(FilterO, E) -> {{orientation, OrientationO},{stanza, StanzaO},{direction, DirectionO}} = FilterO, {Orientation, From, To, Packet} = E, Stanza = element(1, Packet), Hosts_all = ejabberd_config:get_option(hosts), {Host_local, Host_remote} = case Orientation of send -> {From#jid.lserver, To#jid.lserver}; recv -> {To#jid.lserver, From#jid.lserver} end, Direction = case Host_remote of Host_local -> internal; _ -> case lists:member(Host_remote, Hosts_all) of true -> vhosts; false -> external end end, {lists:all(fun(O) -> O end, [lists:member(Orientation, OrientationO), lists:member(Stanza, StanzaO), lists:member(Direction, DirectionO)]), {Orientation, Stanza, Direction}}. loop(Host, IoDevice, Filename, Logdir, CheckRKP, RotateO, PacketC, Gregorian_day, ShowIP, FilterO) -> receive {addlog, E} -> {IoDevice3, Filename3, Gregorian_day3, PacketC3} = case filter(FilterO, E) of {true, OSD} -> Div = calc_div(PacketC, CheckRKP), {IoDevice2, Filename2, Gregorian_day2, PacketC2} = case Div==round(Div) of true -> manage_rotate(Host, IoDevice, Filename, Logdir, RotateO, PacketC, Gregorian_day); false -> {IoDevice, Filename, Gregorian_day, PacketC+1} end, add_log(IoDevice2, ShowIP, E, OSD), {IoDevice2, Filename2, Gregorian_day2, PacketC2}; _ -> {IoDevice, Filename, Gregorian_day, PacketC} end, loop(Host, IoDevice3, Filename3, Logdir, CheckRKP, RotateO, PacketC3, Gregorian_day3, ShowIP, FilterO); stop -> close_file(IoDevice), ok; _ -> loop(Host, IoDevice, Filename, Logdir, CheckRKP, RotateO, PacketC, Gregorian_day, ShowIP, FilterO) end. send_packet({P, State}) -> {FromJID, ToJID} = get_from_to(P), Host = FromJID#jid.lserver, Proc = gen_mod:get_module_proc(Host, ?PROCNAME), Proc ! {addlog, {send, FromJID, ToJID, P}}, {P, State}. receive_packet({P, State}) -> {FromJID, ToJID} = get_from_to(P), Host = ToJID#jid.lserver, Proc = gen_mod:get_module_proc(Host, ?PROCNAME), Proc ! {addlog, {recv, FromJID, ToJID, P}}, {P, State}. get_from_to(Packet) -> case Packet of #iq{from = F, to = T} -> {F, T}; #message{from = F, to = T} -> {F, T}; #presence{from = F, to = T} -> {F, T} end. add_log(Io, ShowIP, {Orientation, From, To, Packet}, _OSD) -> %%{Orientation, Stanza, Direction} = OSD, LocalJID = case Orientation of send -> From; recv -> To end, LocalIPS = case ShowIP of true -> case ejabberd_sm:get_user_ip( LocalJID#jid.user, LocalJID#jid.server, LocalJID#jid.resource) of {UserIP, _Port} -> io_lib:format("lip=\"~s\" ", [inet_parse:ntoa(UserIP)]); undefined -> "lip=\"undefined\" " end; false -> "" end, TimestampISO = get_now_iso(), io:fwrite(Io, "~s~n", [Orientation, binary_to_list(jid:encode(LocalJID)), LocalIPS, binary_to_list(TimestampISO), binary_to_list(fxml:element_to_binary(xmpp:encode(Packet)))]). %% ------------------- %% File %% ------------------- open_file(Logdir, Host) -> {{Year, Month, Day}, {Hour, Min, Sec}} = calendar:universal_time(), Logname = str:format("~s-~4..0B~2..0B~2..0BT~2..0B:~2..0B:~2..0B.xml", [Host, Year, Month, Day, Hour, Min, Sec]), Filename = filename:join([Logdir, Logname]), Gregorian_day = get_gregorian_day(), %% Open file, create if it does not exist, create parent dirs if needed case file:read_file_info(Filename) of {ok, _} -> {ok, IoDevice} = file:open(Filename, [append]); {error, enoent} -> make_dir_rec(Logdir), {ok, IoDevice} = file:open(Filename, [append]), io:fwrite(IoDevice, "~s~n", [""]), io:fwrite(IoDevice, "~s~n", [""]), io:fwrite(IoDevice, "~s~n", [""]) end, {IoDevice, Filename, Gregorian_day}. close_file(IoDevice) -> io:fwrite(IoDevice, "~s~n", [""]), file:close(IoDevice). rotate_log(IoDevice, Logdir, Host) -> close_file(IoDevice), open_file(Logdir, Host). make_dir_rec(Dir) -> case file:read_file_info(Dir) of {ok, _} -> ok; {error, enoent} -> DirS = filename:split(Dir), DirR = lists:sublist(DirS, length(DirS)-1), make_dir_rec(filename:join(DirR)), file:make_dir(Dir) end. %% ------------------- %% Utils %% ------------------- get_gregorian_day() -> calendar:date_to_gregorian_days(date()). get_now_iso() -> xmpp_util:encode_timestamp(erlang:timestamp()). calc_div(A, B) when is_integer(A) and is_integer(B) and (B /= 0) -> A/B; calc_div(_A, _B) -> 0.5. %% This ensures that no rotation is performed mod_opt_type(stanza) -> econf:list(econf:enum([iq, message, presence, other])); mod_opt_type(direction) -> econf:list(econf:enum([internal, vhosts, external])); mod_opt_type(orientation) -> econf:list(econf:enum([send, recv])); mod_opt_type(logdir) -> econf:either(auto, econf:directory(write)); mod_opt_type(show_ip) -> econf:bool(); mod_opt_type(rotate_days) -> econf:non_neg_int(); mod_opt_type(rotate_megs) -> econf:non_neg_int(); mod_opt_type(rotate_kpackets) -> econf:non_neg_int(); mod_opt_type(check_rotate_kpackets) -> econf:non_neg_int(). mod_options(_Host) -> [{stanza, [iq, message, presence, other]}, {direction, [internal, vhosts, external]}, {orientation, [send, recv]}, {logdir, auto}, {show_ip, false}, {rotate_days, 1}, {rotate_megs, 10}, {rotate_kpackets, 10}, {check_rotate_kpackets, 1}]. tmpogm5kjkl/mod_logxml/mod_logxml.spec0000664000175000017500000000033714751665140021074 0ustar debalancedebalanceauthor: "Badlop " category: "log" summary: "Log XMPP packets to XML file" home: "https://github.com/processone/ejabberd-contrib/tree/master/" url: "git@github.com:processone/ejabberd-contrib.git" tmpogm5kjkl/mod_logxml/README.md0000664000175000017500000000430614751665140017336 0ustar debalancedebalancemod_logxml - Log XMPP packets to XML file ========================================= * Homepage: http://www.ejabberd.im/mod_logxml * Author: Badlop * Requires: ejabberd 19.08 or higher Description ----------- This module sniffs all the XMPP traffic send and received by ejabberd, both internally and externally transmitted. It logs the XMPP packets to a XML formatted file. It's posible to filter transmitted packets by orientation, stanza and direction. It's possible to configure the file rotation rules and intervals. This module reuses code from `mod_log_forensic`, `mod_stats2file`, `mod_muc_log`. Configuration ------------- - `stanza`: Log packets only when stanza matches. Default value: `[iq, message, presence, other]` - `direction`: Log packets only when direction matches. Default value: `[internal, vhosts, external]` - `orientation`: Log packets only when orientation matches. Default value: `[send, recv]` - `logdir`: Base filename, including absolute path. If set to `auto`, it uses the ejabberd log path. Default value: `auto` - `show_ip`: If the IP address of the local user should be logged to file. Default value: `false` - `rotate_days`: Rotate logs every X days. Put 0 to disable this limit. Default value: `1` - `rotate_megs`: Rotate when the logfile size is higher than this, in megabytes. Put 0 to disable this limit. Default value: `10` - `rotate_kpackets`: Rotate every *1000 XMPP packets logged. Put `0` to disable this limit. Default value: `10` - `check_rotate_kpackets`: Check rotation every `*1000` packets. Default value: `1` Example Configuration --------------------- ```yaml modules: mod_logxml: stanza: - iq - other direction: - external orientation: - send - recv logdir: "/tmp/logs/" show_ip: false rotate_days: 1 rotate_megs: 100 rotate_kpackets: 0 check_rotate_kpackets: 1 ``` XML Format ---------- XMPP packets are enclosed in ``, with attributes: - `or`: orientation of the packet, either `send` or `recv` - `ljid`: local JID of the sender or receiver, depending on the orientation - `ts`: timestamp when the packet was logged tmpogm5kjkl/mod_logxml/COPYING0000664000175000017500000004332414751665140017115 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. tmpogm5kjkl/mod_logxml/ChangeLog0000664000175000017500000000170014751665140017624 0ustar debalancedebalance2008-03-18 Badlop * README.txt: Disable show_ip in example configuration because it requires ejabberd 2.0.0 * src/mod_logxml.erl: Fixed indentation * ChangeLog.txt: New file to track changes 2007-07-20 Badlop * mod_logxml.erl: Added new option: show_ip 2007-03-20 Badlop * mod_logxml.erl: The file name respects the timezone option 2007-02-03 Badlop * mod_logxml.erl: Added new option: timezone 2006-08-08 Badlop * mod_logxml.erl: Fixed small bug on start/2 2006-03-08 Badlop * mod_logxml.erl: Changed some configuration options: rotate_days, rotate_mages and rotate_kpackets can now be set independently * mod_logxml.erl: New format of XML logs: now XMPP packets are enclosed in a 'packet' element with attributes: or, ljid, ts 2005-11-11 Badlop * mod_logxml.erl: Initial version tmpogm5kjkl/mod_logxml/conf/0000775000175000017500000000000014751665140017001 5ustar debalancedebalancetmpogm5kjkl/mod_logxml/conf/mod_logxml.yml0000664000175000017500000000045514751665140021671 0ustar debalancedebalance#modules: # mod_logxml: # stanza: # - iq # - other # direction: # - external # orientation: # - send # - recv # logdir: "/tmp/logs/" # show_ip: false # rotate_days: 1 # rotate_megs: 100 # rotate_kpackets: 0 # check_rotate_kpackets: 1 tmpogm5kjkl/mod_spam_filter/0000775000175000017500000000000014751665140017057 5ustar debalancedebalancetmpogm5kjkl/mod_spam_filter/src/0000775000175000017500000000000014751665140017646 5ustar debalancedebalancetmpogm5kjkl/mod_spam_filter/src/mod_spam_filter.erl0000664000175000017500000007110214751665140023517 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, sm_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)). -define(HTTPC_TIMEOUT, timer:seconds(3)). -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(sm_receive_packet, Host, ?MODULE, sm_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({resolve_redirects, URLs}, _From, State) -> ResolvedURLs = do_resolve_redirects(URLs, []), {reply, {spam_filter, ResolvedURLs}, State}; 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(sm_receive_packet, Host, ?MODULE, sm_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() | drop, s2s_in_state()} | {stop, {drop, s2s_in_state()}}. s2s_receive_packet({A, State}) -> case sm_receive_packet(A) of {stop, drop} -> {stop, {drop, State}}; Result -> {Result, State} end. -spec sm_receive_packet(stanza() | drop) -> stanza() | drop | {stop, drop}. sm_receive_packet(drop = Acc) -> Acc; sm_receive_packet(#message{from = From, to = #jid{lserver = LServer} = To, type = Type, body = Body} = Msg = 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), {stop, drop} end; spam -> reject(Msg), {stop, drop} end; false -> Acc end; sm_receive_packet(#presence{from = From, to = #jid{lserver = LServer} = To, type = subscribe} = Presence = Acc) -> case needs_checking(From, To) of true -> case check_from(LServer, From) of ham -> Acc; spam -> reject(Presence), {stop, drop} end; false -> Acc end; sm_receive_packet(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(Host, 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(), binary()) -> {urls, [url()]} | none. extract_urls(Host, Body) -> RE = <<"https?://\\S+">>, Options = [global, {capture, all, binary}], case re:run(Body, RE, Options) of {match, Captured} when is_list(Captured) -> Urls = resolve_redirects(Host, lists:flatten(Captured)), {urls, Urls}; nomatch -> none end. -spec resolve_redirects(binary(), [url()]) -> [url()]. resolve_redirects(Host, URLs) -> Proc = get_proc_name(Host), try gen_server:call(Proc, {resolve_redirects, URLs}) of {spam_filter, ResolvedURLs} -> ResolvedURLs catch exit:{timeout, _} -> ?WARNING_MSG("Timeout while resolving redirects: ~p", [URLs]), URLs end. -spec do_resolve_redirects([url()], [url()]) -> [url()]. do_resolve_redirects([], Result) -> Result; do_resolve_redirects([URL | Rest], Acc) -> case httpc:request(get, {URL, [{"user-agent", "curl/8.7.1"}]}, [{autoredirect, false}, {timeout, ?HTTPC_TIMEOUT}], []) of {ok, {{_, StatusCode, _}, Headers, _Body}} when StatusCode >= 300, StatusCode < 400 -> Location = proplists:get_value("location", Headers), case Location == undefined orelse lists:member(Location, Acc) of true -> do_resolve_redirects(Rest, [URL | Acc]); false -> do_resolve_redirects([Location | Rest], [URL | Acc]) end; _Res -> do_resolve_redirects(Rest, [URL | Acc]) 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. tmpogm5kjkl/mod_spam_filter/README.md0000664000175000017500000000657314751665140020351 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 ``` tmpogm5kjkl/mod_spam_filter/mod_spam_filter.spec0000664000175000017500000000040114751665140023072 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" tmpogm5kjkl/mod_spam_filter/COPYING0000664000175000017500000004346414751665140020125 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. tmpogm5kjkl/mod_spam_filter/conf/0000775000175000017500000000000014751665140020004 5ustar debalancedebalancetmpogm5kjkl/mod_spam_filter/conf/mod_spam_filter.yml0000664000175000017500000000031514751665140023672 0ustar debalancedebalance#modules: # mod_spam_filter: #{} # spam_jids_file: "/etc/ejabberd/spam-filter/jids.txt" # spam_urls_file: "/etc/ejabberd/spam-filter/urls.txt" # spam_dump_file: "/var/log/ejabberd/spam_dump.log" tmpogm5kjkl/mod_http_redirect/0000775000175000017500000000000014751665140017412 5ustar debalancedebalancetmpogm5kjkl/mod_http_redirect/src/0000775000175000017500000000000014751665140020201 5ustar debalancedebalancetmpogm5kjkl/mod_http_redirect/src/mod_http_redirect.erl0000664000175000017500000000501014751665140024400 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() -> "". tmpogm5kjkl/mod_http_redirect/README.md0000664000175000017500000000166414751665140020700 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` tmpogm5kjkl/mod_http_redirect/mod_http_redirect.spec0000664000175000017500000000034514751665140023767 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" tmpogm5kjkl/mod_http_redirect/COPYING0000664000175000017500000004346414751665140020460 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. tmpogm5kjkl/mod_http_redirect/conf/0000775000175000017500000000000014751665140020337 5ustar debalancedebalancetmpogm5kjkl/mod_http_redirect/conf/mod_http_redirect.yml0000664000175000017500000000027414751665140024564 0ustar debalancedebalance#listen: # - # port: 5286 # module: ejabberd_http # request_handlers: # /: mod_http_redirect # #modules: # mod_http_redirect: # location: http://example.com/some-path/ tmpogm5kjkl/mod_pubsub_serverinfo/0000775000175000017500000000000014751665140020314 5ustar debalancedebalancetmpogm5kjkl/mod_pubsub_serverinfo/src/0000775000175000017500000000000014751665140021103 5ustar debalancedebalancetmpogm5kjkl/mod_pubsub_serverinfo/src/mod_pubsub_serverinfo.erl0000664000175000017500000002514114751665140026213 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : mod_pubsub_serverinfo.erl %%% Author : Guus der Kinderen %%% Purpose : Exposes server information over Pub/Sub %%% Created : 26 Dec 2023 by Guus der Kinderen %%% %%% %%% ejabberd, Copyright (C) 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_pubsub_serverinfo). -author('guus.der.kinderen@gmail.com'). -behaviour(gen_mod). -behaviour(gen_server). -include("pubsub_serverinfo_codec.hrl"). -include("logger.hrl"). -include_lib("xmpp/include/xmpp.hrl"). %% gen_mod callbacks. -export([start/2, stop/1, depends/2, mod_options/1, get_local_features/5, mod_doc/0]). -export([init/1, handle_cast/2, handle_call/3, handle_info/2, terminate/2]). -export([in_auth_result/3, out_auth_result/2, get_info/5]). -define(NS_URN_SERVERINFO, <<"urn:xmpp:serverinfo:0">>). -define(PUBLIC_HOSTS_URL, <<"https://data.xmpp.net/providers/v2/providers-Ds.json">>). -record(state, {host, pubsub_host, node, monitors = #{}, timer = undefined, public_hosts = []}). start(Host, Opts) -> xmpp:register_codec(pubsub_serverinfo_codec), ejabberd_hooks:add(disco_local_features, Host, ?MODULE, get_local_features, 50), ejabberd_hooks:add(disco_info, Host, ?MODULE, get_info, 50), ejabberd_hooks:add(s2s_out_auth_result, Host, ?MODULE, out_auth_result, 50), ejabberd_hooks:add(s2s_in_auth_result, Host, ?MODULE, in_auth_result, 50), gen_mod:start_child(?MODULE, Host, Opts). stop(Host) -> ejabberd_hooks:delete(disco_local_features, Host, ?MODULE, get_local_features, 50), ejabberd_hooks:delete(disco_info, Host, ?MODULE, get_info, 50), ejabberd_hooks:delete(s2s_out_auth_result, Host, ?MODULE, out_auth_result, 50), ejabberd_hooks:delete(s2s_in_auth_result, Host, ?MODULE, in_auth_result, 50), gen_mod:stop_child(?MODULE, Host). init([Host, _Opts]) -> TRef = timer:send_interval(timer:minutes(5), self(), update_pubsub), Monitors = init_monitors(Host), PublicHosts = fetch_public_hosts(), %% [FIXME] pubsub_host shouldn't just be hardcoded, there should be a config option to reflect %% the `hosts` option of mod_pubsub's configuration State = #state{host = Host, pubsub_host = <<"pubsub.", Host/binary>>, node = <<"serverinfo">>, timer = TRef, monitors = Monitors, public_hosts = PublicHosts}, self() ! update_pubsub, {ok, State}. -spec init_monitors(binary()) -> map(). init_monitors(Host) -> lists:foldl( fun(Domain, Monitors) -> RefIn = make_ref(), % just dummies RefOut = make_ref(), maps:merge(#{RefIn => {incoming, {Host, Domain, true}}, RefOut => {outgoing, {Host, Domain, true}}}, Monitors) end, #{}, ejabberd_option:hosts() -- [Host]). -spec fetch_public_hosts() -> list(). fetch_public_hosts() -> try {ok, {{_, 200, _}, _Headers, Body}} = httpc:request(?PUBLIC_HOSTS_URL), case misc:json_decode(Body) of PublicHosts when is_list(PublicHosts) -> PublicHosts; Other -> ?WARNING_MSG("Parsed JSON for public hosts was not a list: ~p", [Other]), [] end catch E:R -> ?WARNING_MSG("Failed fetching public hosts (~p): ~p", [E, R]), [] end. handle_cast({Event, Domain, Pid}, #state{host = Host, monitors = Mons} = State) when Event == register_in; Event == register_out -> Ref = monitor(process, Pid), IsPublic = check_if_public(Domain, State), NewMons = maps:put(Ref, {event_to_dir(Event), {Host, Domain, IsPublic}}, Mons), {noreply, State#state{monitors = NewMons}}; handle_cast(_, State) -> {noreply, State}. event_to_dir(register_in) -> incoming; event_to_dir(register_out) -> outgoing. handle_call(_Request, _From, State) -> {noreply, State}. handle_info({iq_reply, IQReply, {LServer, RServer}}, #state{monitors = Mons} = State) -> case IQReply of #iq{type = result, sub_els = [El]} -> case xmpp:decode(El) of #disco_info{features = Features} -> case lists:member(?NS_URN_SERVERINFO, Features) of true -> NewMons = maps:fold(fun(Ref, {Dir, {LServer0, RServer0, _}}, Acc) when LServer == LServer0, RServer == RServer0 -> maps:put(Ref, {Dir, {LServer, RServer, true}}, Acc); (Ref, Other, Acc) -> maps:put(Ref, Other, Acc) end, #{}, Mons), {noreply, State#state{monitors = NewMons}}; _ -> {noreply, State} end; _ -> {noreply, State} end; _ -> {noreply, State} end; handle_info(update_pubsub, State) -> update_pubsub(State), {noreply, State}; handle_info({'DOWN', Mon, process, _Pid, _Info}, #state{monitors = Mons} = State) -> {noreply, State#state{monitors = maps:remove(Mon, Mons)}}; handle_info(_Request, State) -> {noreply, State}. terminate(_Reason, #state{monitors = Mons, timer = Timer}) -> case is_reference(Timer) of true -> case erlang:cancel_timer(Timer) of false -> receive {timeout, Timer, _} -> ok after 0 -> ok end; _ -> ok end; _ -> ok end, maps:fold( fun(Mon, _, _) -> demonitor(Mon) end, ok, Mons). depends(_Host, _Opts) -> [{mod_pubsub, hard}]. mod_options(_Host) -> []. mod_doc() -> #{}. in_auth_result(#{server_host := Host, remote_server := RServer} = State, true, _Server) -> gen_server:cast(gen_mod:get_module_proc(Host, ?MODULE), {register_in, RServer, self()}), State; in_auth_result(State, _, _) -> State. out_auth_result(#{server_host := Host, remote_server := RServer} = State, true) -> gen_server:cast(gen_mod:get_module_proc(Host, ?MODULE), {register_out, RServer, self()}), State; out_auth_result(State, _) -> State. check_if_public(Domain, State) -> maybe_send_disco_info(is_public(Domain, State) orelse is_monitored(Domain, State), Domain, State). is_public(Domain, #state{public_hosts = PublicHosts}) -> lists:member(Domain, PublicHosts). is_monitored(Domain, #state{host = Host, monitors = Mons}) -> maps:size( maps:filter( fun(_Ref, {_Dir, {LServer, RServer, IsPublic}}) when LServer == Host, RServer == Domain -> IsPublic; (_Ref, _Other) -> false end, Mons)) =/= 0. maybe_send_disco_info(true, _Domain, _State) -> true; maybe_send_disco_info(false, Domain, #state{host = Host}) -> Proc = gen_mod:get_module_proc(Host, ?MODULE), IQ = #iq{type = get, from = jid:make(Host), to = jid:make(Domain), sub_els = [#disco_info{}]}, ejabberd_router:route_iq(IQ, {Host, Domain}, Proc), false. update_pubsub(#state{host = Host, pubsub_host = PubsubHost, node = Node, monitors = Mons}) -> Map = maps:fold( fun(_, {Dir, {MyDomain, Target, IsPublic}}, Acc) -> maps:update_with(MyDomain, fun(Acc2) -> maps:update_with(Target, fun({Types, _}) -> {Types#{Dir => true}, IsPublic} end, {#{Dir => true}, IsPublic}, Acc2) end, #{Target => {#{Dir => true}, IsPublic}}, Acc) end, #{}, Mons), Domains = maps:fold( fun(MyDomain, Targets, Acc) -> Remote = maps:fold( fun(Remote, {Types, true}, Acc2) -> [#pubsub_serverinfo_remote_domain{name = Remote, type = maps:keys(Types)} | Acc2]; (_HiddenRemote, {Types, false}, Acc2) -> [#pubsub_serverinfo_remote_domain{type = maps:keys(Types)} | Acc2] end, [], Targets), [#pubsub_serverinfo_domain{name = MyDomain, remote_domain = Remote} | Acc] end, [], Map), PubOpts = [{persist_items, true}, {max_items, 1}, {access_model, open}], ?DEBUG("Publishing serverinfo pubsub item on ~s: ~p", [PubsubHost, Domains]), mod_pubsub:publish_item( PubsubHost, Host, Node, jid:make(Host), <<"current">>, [xmpp:encode(#pubsub_serverinfo{domain = Domains})], PubOpts, all). get_local_features({error, _} = Acc, _From, _To, _Node, _Lang) -> Acc; get_local_features(Acc, _From, _To, Node, _Lang) when Node == <<>> -> case Acc of {result, Features} -> {result, [?NS_URN_SERVERINFO | Features]}; empty -> {result, [?NS_URN_SERVERINFO]} end; get_local_features(Acc, _From, _To, _Node, _Lang) -> Acc. get_info(Acc, Host, Mod, Node, Lang) when (Mod == undefined orelse Mod == mod_disco), Node == <<"">> -> case mod_disco:get_info(Acc, Host, Mod, Node, Lang) of [#xdata{fields = Fields} = XD | Rest] -> NodeField = #xdata_field{var = <<"serverinfo-pubsub-node">>, %% [FIXME] don't hardcode pubsub host (see above) values = [<<"xmpp:pubsub.", Host/binary, "?;node=serverinfo">>]}, {stop, [XD#xdata{fields = Fields ++ [NodeField]} | Rest]}; _ -> Acc end; get_info(Acc, Host, Mod, Node, _Lang) when Node == <<"">>, is_atom(Mod) -> [#xdata{type = result, fields = [ #xdata_field{type = hidden, var = <<"FORM_TYPE">>, values = [?NS_SERVERINFO]}, #xdata_field{var = <<"serverinfo-pubsub-node">>, %% [FIXME] don't hardcode pubsub host (see above) values = [<<"xmpp:pubsub.", Host/binary, "?;node=serverinfo">>]}]} | Acc]; get_info(Acc, _Host, _Mod, _Node, _Lang) -> Acc. tmpogm5kjkl/mod_pubsub_serverinfo/src/pubsub_serverinfo_codec.erl0000664000175000017500000010016014751665140026504 0ustar debalancedebalance%% Created automatically by XML generator (fxml_gen.erl) %% Source: pubsub_serverinfo_codec.spec -module(pubsub_serverinfo_codec). -compile(export_all). decode(El) -> decode(El, <<>>, []). decode(El, Opts) -> decode(El, <<>>, Opts). decode({xmlel, Name, Attrs, _} = El, TopXMLNS, Opts) -> XMLNS = get_attr(<<"xmlns">>, Attrs, TopXMLNS), case get_mod(Name, XMLNS) of undefined when XMLNS == <<>> -> erlang:error({pubsub_serverinfo_codec, {missing_tag_xmlns, Name}}); undefined -> erlang:error({pubsub_serverinfo_codec, {unknown_tag, Name, XMLNS}}); Mod -> Mod:do_decode(Name, XMLNS, El, Opts) end. encode(El) -> encode(El, <<>>). encode({xmlel, _, _, _} = El, _) -> El; encode({xmlcdata, _} = CData, _) -> CData; encode(El, TopXMLNS) -> Mod = get_mod(El), Mod:do_encode(El, TopXMLNS). get_name(El) -> Mod = get_mod(El), Mod:do_get_name(El). get_ns(El) -> Mod = get_mod(El), Mod:do_get_ns(El). is_known_tag({xmlel, Name, Attrs, _}, TopXMLNS) -> XMLNS = get_attr(<<"xmlns">>, Attrs, TopXMLNS), get_mod(Name, XMLNS) /= undefined. get_els(Term) -> Mod = get_mod(Term), Mod:get_els(Term). set_els(Term, Els) -> Mod = get_mod(Term), Mod:set_els(Term, Els). do_decode(<<"connection">>, <<"urn:xmpp:serverinfo:0">>, El, Opts) -> decode_pubsub_serverinfo_connection(<<"urn:xmpp:serverinfo:0">>, Opts, El); do_decode(<<"remote-domain">>, <<"urn:xmpp:serverinfo:0">>, El, Opts) -> decode_pubsub_serverinfo_remote_domain(<<"urn:xmpp:serverinfo:0">>, Opts, El); do_decode(<<"federation">>, <<"urn:xmpp:serverinfo:0">>, El, Opts) -> decode_pubsub_serverinfo_federation(<<"urn:xmpp:serverinfo:0">>, Opts, El); do_decode(<<"domain">>, <<"urn:xmpp:serverinfo:0">>, El, Opts) -> decode_pubsub_serverinfo_domain(<<"urn:xmpp:serverinfo:0">>, Opts, El); do_decode(<<"serverinfo">>, <<"urn:xmpp:serverinfo:0">>, El, Opts) -> decode_pubsub_serverinfo(<<"urn:xmpp:serverinfo:0">>, Opts, El); do_decode(Name, <<>>, _, _) -> erlang:error({pubsub_serverinfo_codec, {missing_tag_xmlns, Name}}); do_decode(Name, XMLNS, _, _) -> erlang:error({pubsub_serverinfo_codec, {unknown_tag, Name, XMLNS}}). tags() -> [{<<"connection">>, <<"urn:xmpp:serverinfo:0">>}, {<<"remote-domain">>, <<"urn:xmpp:serverinfo:0">>}, {<<"federation">>, <<"urn:xmpp:serverinfo:0">>}, {<<"domain">>, <<"urn:xmpp:serverinfo:0">>}, {<<"serverinfo">>, <<"urn:xmpp:serverinfo:0">>}]. do_encode({pubsub_serverinfo, _} = Serverinfo, TopXMLNS) -> encode_pubsub_serverinfo(Serverinfo, TopXMLNS); do_encode({pubsub_serverinfo_domain, _, _} = Domain, TopXMLNS) -> encode_pubsub_serverinfo_domain(Domain, TopXMLNS); do_encode({pubsub_serverinfo_remote_domain, _, _} = Remote_domain, TopXMLNS) -> encode_pubsub_serverinfo_remote_domain(Remote_domain, TopXMLNS). do_get_name({pubsub_serverinfo, _}) -> <<"serverinfo">>; do_get_name({pubsub_serverinfo_domain, _, _}) -> <<"domain">>; do_get_name({pubsub_serverinfo_remote_domain, _, _}) -> <<"remote-domain">>. do_get_ns({pubsub_serverinfo, _}) -> <<"urn:xmpp:serverinfo:0">>; do_get_ns({pubsub_serverinfo_domain, _, _}) -> <<"urn:xmpp:serverinfo:0">>; do_get_ns({pubsub_serverinfo_remote_domain, _, _}) -> <<"urn:xmpp:serverinfo:0">>. register_module(Mod) -> register_module(Mod, pubsub_serverinfo_codec_external). unregister_module(Mod) -> unregister_module(Mod, pubsub_serverinfo_codec_external). format_error({bad_attr_value, Attr, Tag, XMLNS}) -> <<"Bad value of attribute '", Attr/binary, "' in tag <", Tag/binary, "/> qualified by namespace '", XMLNS/binary, "'">>; format_error({bad_cdata_value, <<>>, Tag, XMLNS}) -> <<"Bad value of cdata in tag <", Tag/binary, "/> qualified by namespace '", XMLNS/binary, "'">>; format_error({missing_tag, Tag, XMLNS}) -> <<"Missing tag <", Tag/binary, "/> qualified by namespace '", XMLNS/binary, "'">>; format_error({missing_attr, Attr, Tag, XMLNS}) -> <<"Missing attribute '", Attr/binary, "' in tag <", Tag/binary, "/> qualified by namespace '", XMLNS/binary, "'">>; format_error({missing_cdata, <<>>, Tag, XMLNS}) -> <<"Missing cdata in tag <", Tag/binary, "/> qualified by namespace '", XMLNS/binary, "'">>; format_error({unknown_tag, Tag, XMLNS}) -> <<"Unknown tag <", Tag/binary, "/> qualified by namespace '", XMLNS/binary, "'">>; format_error({missing_tag_xmlns, Tag}) -> <<"Missing namespace for tag <", Tag/binary, "/>">>. io_format_error({bad_attr_value, Attr, Tag, XMLNS}) -> {<<"Bad value of attribute '~s' in tag <~s/> " "qualified by namespace '~s'">>, [Attr, Tag, XMLNS]}; io_format_error({bad_cdata_value, <<>>, Tag, XMLNS}) -> {<<"Bad value of cdata in tag <~s/> qualified " "by namespace '~s'">>, [Tag, XMLNS]}; io_format_error({missing_tag, Tag, XMLNS}) -> {<<"Missing tag <~s/> qualified by namespace " "'~s'">>, [Tag, XMLNS]}; io_format_error({missing_attr, Attr, Tag, XMLNS}) -> {<<"Missing attribute '~s' in tag <~s/> " "qualified by namespace '~s'">>, [Attr, Tag, XMLNS]}; io_format_error({missing_cdata, <<>>, Tag, XMLNS}) -> {<<"Missing cdata in tag <~s/> qualified " "by namespace '~s'">>, [Tag, XMLNS]}; io_format_error({unknown_tag, Tag, XMLNS}) -> {<<"Unknown tag <~s/> qualified by namespace " "'~s'">>, [Tag, XMLNS]}; io_format_error({missing_tag_xmlns, Tag}) -> {<<"Missing namespace for tag <~s/>">>, [Tag]}. get_attr(Attr, Attrs, Default) -> case lists:keyfind(Attr, 1, Attrs) of {_, Val} -> Val; false -> Default end. enc_xmlns_attrs(XMLNS, XMLNS) -> []; enc_xmlns_attrs(XMLNS, _) -> [{<<"xmlns">>, XMLNS}]. choose_top_xmlns(<<>>, NSList, TopXMLNS) -> case lists:member(TopXMLNS, NSList) of true -> TopXMLNS; false -> hd(NSList) end; choose_top_xmlns(XMLNS, _, _) -> XMLNS. register_module(Mod, ResolverMod) -> MD5Sum = try Mod:module_info(md5) of Val -> Val catch error:badarg -> {ok, {Mod, Val}} = beam_lib:md5(code:which(Mod)), Val end, case orddict:find(Mod, ResolverMod:modules()) of {ok, MD5Sum} -> ok; _ -> Mods = orddict:store(Mod, MD5Sum, ResolverMod:modules()), recompile_resolver(Mods, ResolverMod) end. unregister_module(Mod, ResolverMod) -> case orddict:find(Mod, ResolverMod:modules()) of {ok, _} -> Mods = orddict:erase(Mod, ResolverMod:modules()), recompile_resolver(Mods, ResolverMod); error -> ok end. recompile_resolver(Mods, ResolverMod) -> Tags = lists:flatmap(fun (M) -> [{Name, XMLNS, M} || {Name, XMLNS} <- M:tags()] end, orddict:fetch_keys(Mods)), Records = lists:flatmap(fun (M) -> [{RecName, RecSize, M} || {RecName, RecSize} <- M:records()] end, orddict:fetch_keys(Mods)), Lookup1 = string:join(lists:map(fun ({RecName, RecSize, M}) -> io_lib:format("lookup({~s}) -> '~s'", [string:join([io_lib:format("'~s'", [RecName]) | ["_" || _ <- lists:seq(1, RecSize)]], ","), M]) end, Records) ++ ["lookup(Term) -> erlang:error(badarg, " "[Term])."], ";" ++ io_lib:nl()), Lookup2 = string:join(lists:map(fun ({Name, XMLNS, M}) -> io_lib:format("lookup(~w, ~w) -> '~s'", [Name, XMLNS, M]) end, Tags) ++ ["lookup(_, _) -> undefined."], ";" ++ io_lib:nl()), Modules = io_lib:format("modules() -> [~s].", [string:join([io_lib:format("{'~s', ~w}", [M, S]) || {M, S} <- Mods], ",")]), Module = io_lib:format("-module(~s).", [ResolverMod]), Compile = "-compile(export_all).", Forms = lists:map(fun (Expr) -> {ok, Tokens, _} = erl_scan:string(lists:flatten(Expr)), {ok, Form} = erl_parse:parse_form(Tokens), Form end, [Module, Compile, Modules, Lookup1, Lookup2]), {ok, Code} = case compile:forms(Forms, []) of {ok, ResolverMod, Bin} -> {ok, Bin}; {ok, ResolverMod, Bin, _Warnings} -> {ok, Bin}; Error -> Error end, {module, ResolverMod} = code:load_binary(ResolverMod, "nofile", Code), ok. dec_enum(Val, Enums) -> AtomVal = erlang:binary_to_existing_atom(Val, utf8), case lists:member(AtomVal, Enums) of true -> AtomVal end. enc_enum(Atom) -> erlang:atom_to_binary(Atom, utf8). pp(pubsub_serverinfo, 1) -> [domain]; pp(pubsub_serverinfo_domain, 2) -> [name, remote_domain]; pp(pubsub_serverinfo_remote_domain, 2) -> [name, type]; pp(xmlel, 3) -> [name, attrs, children]; pp(Name, Arity) -> try get_mod(erlang:make_tuple(Arity + 1, undefined, [{1, Name}])) of Mod -> Mod:pp(Name, Arity) catch error:badarg -> no end. records() -> [{pubsub_serverinfo, 1}, {pubsub_serverinfo_domain, 2}, {pubsub_serverinfo_remote_domain, 2}]. get_mod(<<"serverinfo">>, <<"urn:xmpp:serverinfo:0">>) -> pubsub_serverinfo_codec; get_mod(<<"remote-domain">>, <<"urn:xmpp:serverinfo:0">>) -> pubsub_serverinfo_codec; get_mod(<<"federation">>, <<"urn:xmpp:serverinfo:0">>) -> pubsub_serverinfo_codec; get_mod(<<"domain">>, <<"urn:xmpp:serverinfo:0">>) -> pubsub_serverinfo_codec; get_mod(<<"connection">>, <<"urn:xmpp:serverinfo:0">>) -> pubsub_serverinfo_codec; get_mod(Name, XMLNS) -> pubsub_serverinfo_codec_external:lookup(Name, XMLNS). get_mod({pubsub_serverinfo, _}) -> pubsub_serverinfo_codec; get_mod({pubsub_serverinfo_domain, _, _}) -> pubsub_serverinfo_codec; get_mod({pubsub_serverinfo_remote_domain, _, _}) -> pubsub_serverinfo_codec; get_mod(Record) -> pubsub_serverinfo_codec_external:lookup(Record). decode_pubsub_serverinfo_connection(__TopXMLNS, __Opts, {xmlel, <<"connection">>, _attrs, _els}) -> Type = decode_pubsub_serverinfo_connection_attrs(__TopXMLNS, _attrs, undefined), Type. decode_pubsub_serverinfo_connection_attrs(__TopXMLNS, [{<<"type">>, _val} | _attrs], _Type) -> decode_pubsub_serverinfo_connection_attrs(__TopXMLNS, _attrs, _val); decode_pubsub_serverinfo_connection_attrs(__TopXMLNS, [_ | _attrs], Type) -> decode_pubsub_serverinfo_connection_attrs(__TopXMLNS, _attrs, Type); decode_pubsub_serverinfo_connection_attrs(__TopXMLNS, [], Type) -> decode_pubsub_serverinfo_connection_attr_type(__TopXMLNS, Type). encode_pubsub_serverinfo_connection(Type, __TopXMLNS) -> __NewTopXMLNS = pubsub_serverinfo_codec:choose_top_xmlns(<<"urn:xmpp:serverinfo:0">>, [], __TopXMLNS), _els = [], _attrs = encode_pubsub_serverinfo_connection_attr_type(Type, pubsub_serverinfo_codec:enc_xmlns_attrs(__NewTopXMLNS, __TopXMLNS)), {xmlel, <<"connection">>, _attrs, _els}. decode_pubsub_serverinfo_connection_attr_type(__TopXMLNS, undefined) -> erlang:error({pubsub_serverinfo_codec, {missing_attr, <<"type">>, <<"connection">>, __TopXMLNS}}); decode_pubsub_serverinfo_connection_attr_type(__TopXMLNS, _val) -> case catch dec_enum(_val, [incoming, outgoing, bidi]) of {'EXIT', _} -> erlang:error({pubsub_serverinfo_codec, {bad_attr_value, <<"type">>, <<"connection">>, __TopXMLNS}}); _res -> _res end. encode_pubsub_serverinfo_connection_attr_type(_val, _acc) -> [{<<"type">>, enc_enum(_val)} | _acc]. decode_pubsub_serverinfo_remote_domain(__TopXMLNS, __Opts, {xmlel, <<"remote-domain">>, _attrs, _els}) -> Type = decode_pubsub_serverinfo_remote_domain_els(__TopXMLNS, __Opts, _els, []), Name = decode_pubsub_serverinfo_remote_domain_attrs(__TopXMLNS, _attrs, undefined), {pubsub_serverinfo_remote_domain, Name, Type}. decode_pubsub_serverinfo_remote_domain_els(__TopXMLNS, __Opts, [], Type) -> lists:reverse(Type); decode_pubsub_serverinfo_remote_domain_els(__TopXMLNS, __Opts, [{xmlel, <<"connection">>, _attrs, _} = _el | _els], Type) -> case pubsub_serverinfo_codec:get_attr(<<"xmlns">>, _attrs, __TopXMLNS) of <<"urn:xmpp:serverinfo:0">> -> decode_pubsub_serverinfo_remote_domain_els(__TopXMLNS, __Opts, _els, [decode_pubsub_serverinfo_connection(<<"urn:xmpp:serverinfo:0">>, __Opts, _el) | Type]); _ -> decode_pubsub_serverinfo_remote_domain_els(__TopXMLNS, __Opts, _els, Type) end; decode_pubsub_serverinfo_remote_domain_els(__TopXMLNS, __Opts, [_ | _els], Type) -> decode_pubsub_serverinfo_remote_domain_els(__TopXMLNS, __Opts, _els, Type). decode_pubsub_serverinfo_remote_domain_attrs(__TopXMLNS, [{<<"name">>, _val} | _attrs], _Name) -> decode_pubsub_serverinfo_remote_domain_attrs(__TopXMLNS, _attrs, _val); decode_pubsub_serverinfo_remote_domain_attrs(__TopXMLNS, [_ | _attrs], Name) -> decode_pubsub_serverinfo_remote_domain_attrs(__TopXMLNS, _attrs, Name); decode_pubsub_serverinfo_remote_domain_attrs(__TopXMLNS, [], Name) -> decode_pubsub_serverinfo_remote_domain_attr_name(__TopXMLNS, Name). encode_pubsub_serverinfo_remote_domain({pubsub_serverinfo_remote_domain, Name, Type}, __TopXMLNS) -> __NewTopXMLNS = pubsub_serverinfo_codec:choose_top_xmlns(<<"urn:xmpp:serverinfo:0">>, [], __TopXMLNS), _els = lists:reverse('encode_pubsub_serverinfo_remote_domain_$type'(Type, __NewTopXMLNS, [])), _attrs = encode_pubsub_serverinfo_remote_domain_attr_name(Name, pubsub_serverinfo_codec:enc_xmlns_attrs(__NewTopXMLNS, __TopXMLNS)), {xmlel, <<"remote-domain">>, _attrs, _els}. 'encode_pubsub_serverinfo_remote_domain_$type'([], __TopXMLNS, _acc) -> _acc; 'encode_pubsub_serverinfo_remote_domain_$type'([Type | _els], __TopXMLNS, _acc) -> 'encode_pubsub_serverinfo_remote_domain_$type'(_els, __TopXMLNS, [encode_pubsub_serverinfo_connection(Type, __TopXMLNS) | _acc]). decode_pubsub_serverinfo_remote_domain_attr_name(__TopXMLNS, undefined) -> erlang:error({pubsub_serverinfo_codec, {missing_attr, <<"name">>, <<"remote-domain">>, __TopXMLNS}}); decode_pubsub_serverinfo_remote_domain_attr_name(__TopXMLNS, _val) -> _val. encode_pubsub_serverinfo_remote_domain_attr_name(_val, _acc) -> [{<<"name">>, _val} | _acc]. decode_pubsub_serverinfo_federation(__TopXMLNS, __Opts, {xmlel, <<"federation">>, _attrs, _els}) -> Remote_domain = decode_pubsub_serverinfo_federation_els(__TopXMLNS, __Opts, _els, []), Remote_domain. decode_pubsub_serverinfo_federation_els(__TopXMLNS, __Opts, [], Remote_domain) -> lists:reverse(Remote_domain); decode_pubsub_serverinfo_federation_els(__TopXMLNS, __Opts, [{xmlel, <<"remote-domain">>, _attrs, _} = _el | _els], Remote_domain) -> case pubsub_serverinfo_codec:get_attr(<<"xmlns">>, _attrs, __TopXMLNS) of <<"urn:xmpp:serverinfo:0">> -> decode_pubsub_serverinfo_federation_els(__TopXMLNS, __Opts, _els, [decode_pubsub_serverinfo_remote_domain(<<"urn:xmpp:serverinfo:0">>, __Opts, _el) | Remote_domain]); _ -> decode_pubsub_serverinfo_federation_els(__TopXMLNS, __Opts, _els, Remote_domain) end; decode_pubsub_serverinfo_federation_els(__TopXMLNS, __Opts, [_ | _els], Remote_domain) -> decode_pubsub_serverinfo_federation_els(__TopXMLNS, __Opts, _els, Remote_domain). encode_pubsub_serverinfo_federation(Remote_domain, __TopXMLNS) -> __NewTopXMLNS = pubsub_serverinfo_codec:choose_top_xmlns(<<"urn:xmpp:serverinfo:0">>, [], __TopXMLNS), _els = lists:reverse('encode_pubsub_serverinfo_federation_$remote_domain'(Remote_domain, __NewTopXMLNS, [])), _attrs = pubsub_serverinfo_codec:enc_xmlns_attrs(__NewTopXMLNS, __TopXMLNS), {xmlel, <<"federation">>, _attrs, _els}. 'encode_pubsub_serverinfo_federation_$remote_domain'([], __TopXMLNS, _acc) -> _acc; 'encode_pubsub_serverinfo_federation_$remote_domain'([Remote_domain | _els], __TopXMLNS, _acc) -> 'encode_pubsub_serverinfo_federation_$remote_domain'(_els, __TopXMLNS, [encode_pubsub_serverinfo_remote_domain(Remote_domain, __TopXMLNS) | _acc]). decode_pubsub_serverinfo_domain(__TopXMLNS, __Opts, {xmlel, <<"domain">>, _attrs, _els}) -> Remote_domain = decode_pubsub_serverinfo_domain_els(__TopXMLNS, __Opts, _els, undefined), Name = decode_pubsub_serverinfo_domain_attrs(__TopXMLNS, _attrs, undefined), {pubsub_serverinfo_domain, Name, Remote_domain}. decode_pubsub_serverinfo_domain_els(__TopXMLNS, __Opts, [], Remote_domain) -> Remote_domain; decode_pubsub_serverinfo_domain_els(__TopXMLNS, __Opts, [{xmlel, <<"federation">>, _attrs, _} = _el | _els], Remote_domain) -> case pubsub_serverinfo_codec:get_attr(<<"xmlns">>, _attrs, __TopXMLNS) of <<"urn:xmpp:serverinfo:0">> -> decode_pubsub_serverinfo_domain_els(__TopXMLNS, __Opts, _els, decode_pubsub_serverinfo_federation(<<"urn:xmpp:serverinfo:0">>, __Opts, _el)); _ -> decode_pubsub_serverinfo_domain_els(__TopXMLNS, __Opts, _els, Remote_domain) end; decode_pubsub_serverinfo_domain_els(__TopXMLNS, __Opts, [_ | _els], Remote_domain) -> decode_pubsub_serverinfo_domain_els(__TopXMLNS, __Opts, _els, Remote_domain). decode_pubsub_serverinfo_domain_attrs(__TopXMLNS, [{<<"name">>, _val} | _attrs], _Name) -> decode_pubsub_serverinfo_domain_attrs(__TopXMLNS, _attrs, _val); decode_pubsub_serverinfo_domain_attrs(__TopXMLNS, [_ | _attrs], Name) -> decode_pubsub_serverinfo_domain_attrs(__TopXMLNS, _attrs, Name); decode_pubsub_serverinfo_domain_attrs(__TopXMLNS, [], Name) -> decode_pubsub_serverinfo_domain_attr_name(__TopXMLNS, Name). encode_pubsub_serverinfo_domain({pubsub_serverinfo_domain, Name, Remote_domain}, __TopXMLNS) -> __NewTopXMLNS = pubsub_serverinfo_codec:choose_top_xmlns(<<"urn:xmpp:serverinfo:0">>, [], __TopXMLNS), _els = lists:reverse('encode_pubsub_serverinfo_domain_$remote_domain'(Remote_domain, __NewTopXMLNS, [])), _attrs = encode_pubsub_serverinfo_domain_attr_name(Name, pubsub_serverinfo_codec:enc_xmlns_attrs(__NewTopXMLNS, __TopXMLNS)), {xmlel, <<"domain">>, _attrs, _els}. 'encode_pubsub_serverinfo_domain_$remote_domain'(undefined, __TopXMLNS, _acc) -> _acc; 'encode_pubsub_serverinfo_domain_$remote_domain'(Remote_domain, __TopXMLNS, _acc) -> [encode_pubsub_serverinfo_federation(Remote_domain, __TopXMLNS) | _acc]. decode_pubsub_serverinfo_domain_attr_name(__TopXMLNS, undefined) -> erlang:error({pubsub_serverinfo_codec, {missing_attr, <<"name">>, <<"domain">>, __TopXMLNS}}); decode_pubsub_serverinfo_domain_attr_name(__TopXMLNS, _val) -> _val. encode_pubsub_serverinfo_domain_attr_name(_val, _acc) -> [{<<"name">>, _val} | _acc]. decode_pubsub_serverinfo(__TopXMLNS, __Opts, {xmlel, <<"serverinfo">>, _attrs, _els}) -> Domain = decode_pubsub_serverinfo_els(__TopXMLNS, __Opts, _els, []), {pubsub_serverinfo, Domain}. decode_pubsub_serverinfo_els(__TopXMLNS, __Opts, [], Domain) -> lists:reverse(Domain); decode_pubsub_serverinfo_els(__TopXMLNS, __Opts, [{xmlel, <<"domain">>, _attrs, _} = _el | _els], Domain) -> case pubsub_serverinfo_codec:get_attr(<<"xmlns">>, _attrs, __TopXMLNS) of <<"urn:xmpp:serverinfo:0">> -> decode_pubsub_serverinfo_els(__TopXMLNS, __Opts, _els, [decode_pubsub_serverinfo_domain(<<"urn:xmpp:serverinfo:0">>, __Opts, _el) | Domain]); _ -> decode_pubsub_serverinfo_els(__TopXMLNS, __Opts, _els, Domain) end; decode_pubsub_serverinfo_els(__TopXMLNS, __Opts, [_ | _els], Domain) -> decode_pubsub_serverinfo_els(__TopXMLNS, __Opts, _els, Domain). encode_pubsub_serverinfo({pubsub_serverinfo, Domain}, __TopXMLNS) -> __NewTopXMLNS = pubsub_serverinfo_codec:choose_top_xmlns(<<"urn:xmpp:serverinfo:0">>, [], __TopXMLNS), _els = lists:reverse('encode_pubsub_serverinfo_$domain'(Domain, __NewTopXMLNS, [])), _attrs = pubsub_serverinfo_codec:enc_xmlns_attrs(__NewTopXMLNS, __TopXMLNS), {xmlel, <<"serverinfo">>, _attrs, _els}. 'encode_pubsub_serverinfo_$domain'([], __TopXMLNS, _acc) -> _acc; 'encode_pubsub_serverinfo_$domain'([Domain | _els], __TopXMLNS, _acc) -> 'encode_pubsub_serverinfo_$domain'(_els, __TopXMLNS, [encode_pubsub_serverinfo_domain(Domain, __TopXMLNS) | _acc]). tmpogm5kjkl/mod_pubsub_serverinfo/src/pubsub_serverinfo_codec_external.erl0000664000175000017500000000040114751665140030403 0ustar debalancedebalance%% Created automatically by XML generator (fxml_gen.erl) %% Source: pubsub_serverinfo_codec.spec -module(pubsub_serverinfo_codec_external). -compile(export_all). modules() -> []. lookup(_, _) -> undefined. lookup(Term) -> erlang:error(badarg, [Term]). tmpogm5kjkl/mod_pubsub_serverinfo/spec/0000775000175000017500000000000014751665140021246 5ustar debalancedebalancetmpogm5kjkl/mod_pubsub_serverinfo/spec/pubsub_serverinfo_codec.spec0000664000175000017500000000357714751665140027035 0ustar debalancedebalance-xml(pubsub_serverinfo, #elem{name = <<"serverinfo">>, xmlns = <<"urn:xmpp:serverinfo:0">>, module = pubsub_serverinfo_codec, result = {pubsub_serverinfo, '$domain'}, refs = [#ref{name = pubsub_serverinfo_domain, label = '$domain', min = 0}]}). -xml(pubsub_serverinfo_domain, #elem{name = <<"domain">>, xmlns = <<"urn:xmpp:serverinfo:0">>, module = pubsub_serverinfo_codec, result = {pubsub_serverinfo_domain, '$name', '$remote_domain'}, attrs = [#attr{name = <<"name">>, label = '$name', required = true}], refs = [#ref{name = pubsub_serverinfo_federation, label = '$remote_domain', min = 0, max = 1}]}). -xml(pubsub_serverinfo_federation, #elem{name = <<"federation">>, xmlns = <<"urn:xmpp:serverinfo:0">>, module = pubsub_serverinfo_codec, result = '$remote_domain', refs = [#ref{name = pubsub_serverinfo_remote_domain, label = '$remote_domain', min = 0}]}). -xml(pubsub_serverinfo_remote_domain, #elem{name = <<"remote-domain">>, xmlns = <<"urn:xmpp:serverinfo:0">>, module = pubsub_serverinfo_codec, result = {pubsub_serverinfo_remote_domain, '$name', '$type'}, attrs = [#attr{name = <<"name">>, label = '$name', required = true}], refs = [#ref{name = pubsub_serverinfo_connection, label = '$type', min = 0}]}). -xml(pubsub_serverinfo_connection, #elem{name = <<"connection">>, xmlns = <<"urn:xmpp:serverinfo:0">>, module = pubsub_serverinfo_codec, result = '$type', attrs = [#attr{name = <<"type">>, label = '$type', required = true, enc = {enc_enum, []}, dec = {dec_enum, [[incoming, outgoing, bidi]]}}]}). tmpogm5kjkl/mod_pubsub_serverinfo/README.md0000664000175000017500000000163314751665140021576 0ustar debalancedebalancemod_pubsub_serverinfo - Exposes server information over Pub/Sub ============================================================== * Author: Guus der Kinderen Description ----------- Announces support for the ProtoXEP PubSub Server Information, by adding its Service Discovery feature. Future versions of this plugin are expected to publish data describing the local XMPP domain(s). > [!NOTE] > The module only shows S2S connections established while the module is running: > after installing the module, please run `ejabberdctl stop_s2s_connections`, or > restart ejabberd. Configuration ------------- This module does not have any configurable settings for now. > [!NOTE] > As of now your pubsub component must be reachable at `pubsub.` (the > default), otherwise this module would advertise the wrong address. > See: https://github.com/processone/ejabberd-contrib/issues/343 tmpogm5kjkl/mod_pubsub_serverinfo/mod_pubsub_serverinfo.spec0000664000175000017500000000037114751665140025572 0ustar debalancedebalanceauthor: "Guus der Kinderen " category: "stats" summary: "Exposes server information over Pub/Sub" home: "https://github.com/processone/ejabberd-contrib/tree/master/" url: "git@github.com:processone/ejabberd-contrib.git" tmpogm5kjkl/mod_pubsub_serverinfo/COPYING0000664000175000017500000004346414751665140021362 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. tmpogm5kjkl/mod_pubsub_serverinfo/conf/0000775000175000017500000000000014751665140021241 5ustar debalancedebalancetmpogm5kjkl/mod_pubsub_serverinfo/conf/mod_pubsub_serverinfo.yml0000664000175000017500000000004514751665140026364 0ustar debalancedebalancemodules: mod_pubsub_serverinfo: {} tmpogm5kjkl/mod_pubsub_serverinfo/include/0000775000175000017500000000000014751665140021737 5ustar debalancedebalancetmpogm5kjkl/mod_pubsub_serverinfo/include/pubsub_serverinfo_codec.hrl0000664000175000017500000000157114751665140027351 0ustar debalancedebalance%% Created automatically by XML generator (fxml_gen.erl) %% Source: pubsub_serverinfo_codec.spec -record(pubsub_serverinfo_remote_domain, {name = <<>> :: binary(), type = [] :: ['bidi' | 'incoming' | 'outgoing']}). -type pubsub_serverinfo_remote_domain() :: #pubsub_serverinfo_remote_domain{}. -record(pubsub_serverinfo_domain, {name = <<>> :: binary(), remote_domain :: 'undefined' | [#pubsub_serverinfo_remote_domain{}]}). -type pubsub_serverinfo_domain() :: #pubsub_serverinfo_domain{}. -record(pubsub_serverinfo, {domain = [] :: [#pubsub_serverinfo_domain{}]}). -type pubsub_serverinfo() :: #pubsub_serverinfo{}. -type pubsub_serverinfo_codec() :: pubsub_serverinfo() | pubsub_serverinfo_domain() | pubsub_serverinfo_remote_domain(). tmpogm5kjkl/mod_webpresence/0000775000175000017500000000000014751665140017054 5ustar debalancedebalancetmpogm5kjkl/mod_webpresence/TODO.txt0000664000175000017500000000155014751665140020363 0ustar debalancedebalance Feature requests for mod_webpresence Internationalization support ---------------------------- - The "text" output returns an empty string if the user doesn't have a status text. Proposal: in such case, return the string "Online", or "Busy" or whatever - The special cases in "presence/" and "presence/themes" should return a header lang=xx with the proper language instead of lang=en - The Icon Themes page should show the translated status. - Allow translation of separator commas and ending dots in lists of elements, since some languages may use other separation symbols. - Support the HTML attribute dir=(ltr|rtl) for languages that are RTL For example: {xmlelement, "html", [{"xmlns", "http://www.w3.org/1999/xhtml"}, ... {"dir", ltr_or_rtl()} And ltr_or_rtl() -> ?T("ltr"). This way RTL languages can change that string to rtl tmpogm5kjkl/mod_webpresence/src/0000775000175000017500000000000014751665140017643 5ustar debalancedebalancetmpogm5kjkl/mod_webpresence/src/mod_webpresence.erl0000664000175000017500000012461614751665140023522 0ustar debalancedebalance%%%---------------------------------------------------------------------- %%% File : mod_webpresence.erl %%% Author : Igor Goryachev , Badlop, runcom %%% Purpose : Allow user to show presence in the web %%% Created : 30 Apr 2006 by Igor Goryachev %%% Id : $Id: mod_webpresence.erl 1083 2010-06-01 18:32:55Z badlop $ %%%---------------------------------------------------------------------- -module(mod_webpresence). -behaviour(gen_server). -behaviour(gen_mod). %% API -export([start/2, stop/1, remove_user/2, web_menu_host/3, web_page_host/3, process_disco_info/1, process_disco_items/1, process_vcard/1, process_register/1, process/2 ]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3, mod_status/0, mod_opt_type/1, mod_options/1, depends/2, mod_doc/0]). %% API -export([start_link/0]). -include_lib("xmpp/include/xmpp.hrl"). -include("logger.hrl"). -include("translate.hrl"). -include("ejabberd_web_admin.hrl"). -include("ejabberd_http.hrl"). -record(webpresence, {us, ridurl = false, jidurl = false, xml = false, avatar = false, js = false, text = false, icon = "jsf-text"}). -record(state, {host, server_host, base_url, access}). -record(presence2, {resource, show, priority, status}). -define(AUTO_ACL, webpresence_auto). %%==================================================================== %% API %%==================================================================== start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). start(Host, Opts) -> Dir = case gen_mod:get_opt(pixmaps_path, Opts) of auto -> Package = atom_to_list(?MODULE), filename:join([ext_mod:modules_dir(), Package, "priv", "pixmaps"]); PP -> PP end, Heir = {heir, whereis(ext_mod), ?MODULE}, catch ets:new(pixmaps_dirs, [named_table, public, Heir]), ets:insert(pixmaps_dirs, {directory, Dir}), case gen_mod:start_child(?MODULE, Host, Opts) of {ok, Ref} -> {ok, Ref}; {error, {already_started, Ref}} -> {ok, Ref}; {error, Reason} -> {error, Reason} end. stop(Host) -> Proc = gen_mod:get_module_proc(Host, ?MODULE), gen_server:call(Proc, stop), gen_mod:stop_child(?MODULE, Host), ok. mod_opt_type(host) -> econf:host(); mod_opt_type(access) -> econf:acl(); mod_opt_type(pixmaps_path) -> econf:either(auto, econf:directory()); mod_opt_type(port) -> econf:pos_int(); mod_opt_type(path) -> econf:binary(); mod_opt_type(baseurl) -> econf:binary(). -spec mod_options(binary()) -> [{atom(), any()}]. mod_options(Host) -> [{host, <<"webpresence.", Host/binary>>}, {access, local}, {pixmaps_path, auto}, {port, 5280}, {path, <<"presence">>}, {baseurl, iolist_to_binary(io_lib:format(<<"http://~s:5280/presence/">>, [Host]))}]. -spec depends(binary(), gen_mod:opts()) -> [{module(), hard | soft}]. depends(_Host, _Opts) -> []. 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 Webpresence 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)). %%==================================================================== %% gen_server callbacks %%==================================================================== %%-------------------------------------------------------------------- %% Function: init(Args) -> {ok, State} | %% {ok, State, Timeout} | %% ignore | %% {stop, Reason} %% Description: Initiates the server %%-------------------------------------------------------------------- init([Host, Opts]) -> mnesia:create_table(webpresence, [{disc_copies, [node()]}, {attributes, record_info(fields, webpresence)}]), mnesia:add_table_index(webpresence, ridurl), update_table(), MyHost = gen_mod:get_opt(host, Opts), Access = gen_mod:get_opt(access, Opts), BaseURL1 = gen_mod:get_opt(baseurl, Opts), BaseURL2 = ejabberd_regexp:greplace(BaseURL1, <<"@HOST@">>, Host), register_iq_handlers(MyHost), ejabberd_router:register_route(MyHost, Host), ejabberd_hooks:add(remove_user, Host, ?MODULE, remove_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), {ok, #state{host = MyHost, server_host = Host, base_url = BaseURL2, access = Access}}. register_iq_handlers(Host) -> gen_iq_handler:add_iq_handler(ejabberd_local, Host, ?NS_REGISTER, ?MODULE, process_register), gen_iq_handler:add_iq_handler(ejabberd_local, Host, ?NS_VCARD, ?MODULE, process_vcard), gen_iq_handler:add_iq_handler(ejabberd_local, Host, ?NS_DISCO_INFO, ?MODULE, process_disco_info), gen_iq_handler:add_iq_handler(ejabberd_local, Host, ?NS_DISCO_ITEMS, ?MODULE, process_disco_items). unregister_iq_handlers(Host) -> gen_iq_handler:remove_iq_handler(ejabberd_local, Host, ?NS_REGISTER), gen_iq_handler:remove_iq_handler(ejabberd_local, Host, ?NS_VCARD), gen_iq_handler:remove_iq_handler(ejabberd_local, Host, ?NS_DISCO_INFO), gen_iq_handler:remove_iq_handler(ejabberd_local, Host, ?NS_DISCO_ITEMS). %%-------------------------------------------------------------------- %% Function: %% handle_call(Request, From, State) -> {reply, Reply, State} | %% {reply, Reply, State, Timeout} | %% {noreply, State} | %% {noreply, State, Timeout} | %% {stop, Reason, Reply, State} | %% {stop, Reason, State} %% Description: Handling call messages %%-------------------------------------------------------------------- handle_call(stop, _From, State) -> {stop, normal, ok, State}. %%-------------------------------------------------------------------- %% Function: handle_cast(Msg, State) -> {noreply, State} | %% {noreply, State, Timeout} | %% {stop, Reason, State} %% Description: Handling cast messages %%-------------------------------------------------------------------- handle_cast(_Msg, State) -> {noreply, State}. %%-------------------------------------------------------------------- %% Function: handle_info(Info, State) -> {noreply, State} | %% {noreply, State, Timeout} | %% {stop, Reason, State} %% Description: Handling all non call/cast messages %%-------------------------------------------------------------------- handle_info({route, Packet}, #state{host = Host, server_host = ServerHost, base_url = BaseURL, access = Access} = State) -> From = xmpp:get_from(Packet), To = xmpp:get_to(Packet), case catch do_route(Host, ServerHost, Access, From, To, Packet, BaseURL) of {'EXIT', Reason} -> ?ERROR_MSG("~p", [Reason]); _ -> ok end, {noreply, State}. %%-------------------------------------------------------------------- %% Function: terminate(Reason, State) -> void() %% Description: This function is called by a gen_server when it is about to %% terminate. It should be the opposite of Module:init/1 and do any necessary %% cleaning up. When it returns, the gen_server terminates with Reason. %% The return value is ignored. %%-------------------------------------------------------------------- terminate(_Reason, #state{host = Host}) -> ejabberd_router:unregister_route(Host), unregister_iq_handlers(Host), ejabberd_hooks:delete(remove_user, Host, ?MODULE, remove_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), ok. %%-------------------------------------------------------------------- %% Func: code_change(OldVsn, State, Extra) -> {ok, NewState} %% Description: Convert process state when code is changed %%-------------------------------------------------------------------- code_change(_OldVsn, State, _Extra) -> {ok, State}. %%-------------------------------------------------------------------- %%% Internal functions %%-------------------------------------------------------------------- do_route(Host, ServerHost, Access, From, To, Packet, BaseURL) -> case acl:match_rule(ServerHost, Access, From) of allow -> do_route1(Host, From, To, Packet, BaseURL); _ -> Lang = xmpp:get_lang(Packet), ErrText = <<"Access denied by service policy">>, Err = xmpp:err_forbidden(ErrText, Lang), ejabberd_router:route_error(Packet, Err) end. -spec process_vcard(iq()) -> iq(). process_vcard(#iq{type = get, lang = Lang, sub_els = [#vcard_temp{}]} = IQ) -> Desc = translate:translate(Lang, <<"ejabberd Web Presence module">>), xmpp:make_iq_result( IQ, #vcard_temp{fn = <<"ejabberd/mod_webpresence">>, url = ejabberd_config:get_uri(), desc = Desc}); process_vcard(#iq{type = set, lang = Lang} = IQ) -> Txt = <<"Value 'set' of 'type' attribute is not allowed">>, xmpp:make_error(IQ, xmpp:err_not_allowed(Txt, Lang)); process_vcard(#iq{lang = Lang} = IQ) -> Txt = <<"No module is handling this query">>, xmpp:make_error(IQ, xmpp:err_service_unavailable(Txt, Lang)). do_route1(_Host, _From, _To, #iq{} = IQ, _BaseURL) -> ejabberd_router:process_iq(IQ); do_route1(_Host, _From, _To, Packet, _BaseURL) -> case xmpp:get_type(Packet) of error -> ok; _ -> Err = xmpp:err_item_not_found(), ejabberd_router:route_error(Packet, Err) end. -spec process_register(iq()) -> iq(). process_register(#iq{type = get, from = From, to = To, lang = Lang, sub_els = [#register{}]} = IQ) -> Host = To#jid.lserver, xmpp:make_iq_result(IQ, iq_get_register_info(Host, From, Lang)); process_register(#iq{type = set, from = From, to = To, lang = Lang, sub_els = [El = #register{}]} = IQ) -> Host = To#jid.lserver, ServerHost = ejabberd_router:host_of_route(Host), case process_iq_register_set(ServerHost, Host, From, El, Lang) of {result, Result} -> xmpp:make_iq_result(IQ, Result); {error, Err} -> xmpp:make_error(IQ, Err) end. -spec process_disco_info(iq()) -> iq(). process_disco_info(#iq{type = set, lang = Lang} = IQ) -> Txt = <<"Value 'set' of 'type' attribute is not allowed">>, xmpp:make_error(IQ, xmpp:err_not_allowed(Txt, Lang)); process_disco_info(#iq{type = get, lang = Lang, sub_els = [#disco_info{node = <<"">>}]} = IQ) -> Features = [?NS_DISCO_INFO, ?NS_DISCO_ITEMS, ?NS_REGISTER, ?NS_VCARD], Identity = #identity{category = <<"component">>, type = <<"presence">>, name = translate:translate(Lang, <<"Web Presence">>)}, xmpp:make_iq_result( IQ, #disco_info{features = Features, identities = [Identity]}); process_disco_info(#iq{type = get, lang = Lang, sub_els = [#disco_info{}]} = IQ) -> xmpp:make_error(IQ, xmpp:err_item_not_found(<<"Node not found">>, Lang)); process_disco_info(#iq{lang = Lang} = IQ) -> Txt = <<"No module is handling this query">>, xmpp:make_error(IQ, xmpp:err_service_unavailable(Txt, Lang)). -spec process_disco_items(iq()) -> iq(). process_disco_items(#iq{type = set, lang = Lang} = IQ) -> Txt = <<"Value 'set' of 'type' attribute is not allowed">>, xmpp:make_error(IQ, xmpp:err_not_allowed(Txt, Lang)); process_disco_items(#iq{type = get, sub_els = [#disco_items{}]} = IQ) -> xmpp:make_iq_result(IQ, #disco_items{}); process_disco_items(#iq{lang = Lang} = IQ) -> Txt = <<"No module is handling this query">>, xmpp:make_error(IQ, xmpp:err_service_unavailable(Txt, Lang)). -define(XFIELDS(Type, Label, Var, Vals), #xmlel{ name = <<"field">>, attrs = [ {<<"type">>, Type}, {<<"label">>, translate:translate(Lang, ?T(Label))}, {<<"var">>, Var} ], children = Vals }). -define(XFIELD(Type, Label, Var, Val), ?XFIELDS(Type, Label, Var, [ #xmlel{ name = <<"value">>, attrs = [], children = [{xmlcdata, Val}] }]) ). -define(XFIELDFIXED(Val), #xmlel{ name = <<"field">>, attrs = [{<<"type">>, <<"fixed">>}], children = [ #xmlel{ name = <<"value">>, attrs = [], children = [{xmlcdata, Val}] } ] } ). -define(ATOM2BINARY(Val), iolist_to_binary(atom_to_list(Val))). -define(BC(L), iolist_to_binary(L)). ridurl_out(false) -> <<"false">>; ridurl_out(Id) when is_binary(Id) -> <<"true">>. get_pr(LUS) -> case catch mnesia:dirty_read(webpresence, LUS) of [#webpresence{jidurl = J, ridurl = H, xml = X, avatar = A, js = S, text = T, icon = I}] -> {J, H, X, A, S, T, I, true}; _ -> {true, false, false, false, false, false, <<"">>, false} end. iq_get_register_info(Host, From, Lang) -> LUS = {From#jid.luser, From#jid.lserver}, {_JidUrl, _RidUrl, _XML, _Avatar, _JS, _Text, Icon, Registered} = get_pr(LUS), Nick = Icon, Title = <<(translate:translate( Lang, <<"Web Presence Registration at ">>))/binary, Host/binary>>, Inst = translate:translate(Lang, <<"Enter iconset you want to use by default">>), Fields = muc_register:encode([{roomnick, Nick}], Lang), X = #xdata{type = form, title = Title, instructions = [Inst], fields = Fields}, #register{nick = Nick, registered = Registered, instructions = translate:translate( Lang, <<"You need a client that supports x:data " "to register to Web Presence">>), xdata = X}. process_iq_register_set(_ServerHost, Host, From, #register{remove = true}, Lang) -> unregister_webpresence(From, Host, Lang); process_iq_register_set(_ServerHost, _Host, _From, #register{xdata = #xdata{type = cancel}}, _Lang) -> {result, undefined}; process_iq_register_set(ServerHost, Host, From, #register{nick = Nick, xdata = XData}, Lang) -> case XData of #xdata{type = submit, fields = Fs} -> try Options = muc_register:decode(Fs), N = proplists:get_value(roomnick, Options), iq_set_register_info(ServerHost, Host, From, N, Lang) catch _:{muc_register, Why} -> ErrText = muc_register:format_error(Why), {error, xmpp:err_bad_request(ErrText, Lang)} end; #xdata{} -> Txt = <<"Incorrect data form">>, {error, xmpp:err_bad_request(Txt, Lang)}; _ when is_binary(Nick), Nick /= <<"">> -> iq_set_register_info(ServerHost, Host, From, Nick, Lang); _ -> ErrText = <<"You must fill in field \"Nickname\" in the form">>, {error, xmpp:err_not_acceptable(ErrText, Lang)} end. iq_set_register_info(ServerHost, Host, From, Nick, Lang) -> case iq_set_register_info2(ServerHost, Host, From, Nick, Lang) of {atomic, ok} -> {result, undefined}; _ -> Txt = <<"Database failure">>, {error, xmpp:err_internal_server_error(Txt, Lang)} end. iq_set_register_info2(ServerHost, Host, From, Icon, Lang) -> %% RidUrl2 = get_rid_final_value(RidUrl, LUS), LUS = {From#jid.luser, From#jid.lserver}, WP = #webpresence{us = LUS, jidurl = true, ridurl = false, xml = true, avatar = true, js = true, text = true, icon = Icon}, F = fun() -> mnesia:write(WP) end, case mnesia:transaction(F) of {atomic, ok} -> BaseURL = get_baseurl(ServerHost), send_message_registered(WP, From, Host, BaseURL, Lang), {atomic, ok}; _ -> {error, xmpp:err_internal_server_error()} end. send_message_registered(WP, To, Host, BaseURL, Lang) -> {User, Server} = WP#webpresence.us, JIDS = jid:encode({User, Server, <<"">>}), Oavatar = case WP#webpresence.avatar of %%false -> <<"">>; true -> <<" avatar\n" " avatar/my.png\n">> end, Ojs = case WP#webpresence.js of %%false -> <<"">>; true -> <<" js\n">> end, Otext = case WP#webpresence.text of %%false -> <<"">>; true -> ?BC([ <<" text\n" " text/res/<">>, translate:translate(Lang, ?T("Resource")), <<">\n">> ]) end, Oimage = case WP#webpresence.icon of <<"---">> -> ""; I when is_binary(I) -> ?BC([ <<" image\n" " image/example.php\n" " image/mypresence.png\n" " image/res/<">>, translate:translate(Lang, ?T("Resource")), <<">\n" " image/theme/<">>, translate:translate(Lang, ?T("Icon Theme")), <<">\n" " image/theme/<">>, translate:translate(Lang, ?T("Icon Theme")), <<">/res/<">>, translate:translate(Lang, ?T("Resource")), <<">\n">> ]) end, Oxml = case WP#webpresence.xml of %%false -> <<"">>; true -> <<" xml\n">> end, Allowed_type = case {Oimage, Oxml, Oavatar, Otext, Ojs} of {<<"">>, <<"">>, <<"">>, <<"">>, _} -> <<"js">>; {<<"">>, <<"">>, <<"">>, _, _} -> <<"text">>; {<<"">>, <<"">>, _, _, _} -> <<"avatar">>; {<<"">>, _, _, _, _} -> <<"xml">>; {_, _, _, _, _} -> <<"image">> end, {USERID_jid, Example_jid} = case WP#webpresence.jidurl of %%false -> {<<"">>, <<"">>}; true -> JIDT = ?BC([<<"jid/">>, User, <<"/">>, Server]), {?BC([<<" ">>, JIDT, <<"\n">>]), ?BC([<<" ">>, BaseURL, JIDT, <<"/">>, Allowed_type, <<"/\n">>])} end, {USERID_rid, Example_rid, Text_rid} = case WP#webpresence.ridurl of false -> {<<"">>, <<"">>, <<"">>}%; %%RID when is_binary(RID) -> %% RIDT = ?BC([<<"rid/">>, RID]), %% {?BC([<<" ">>, RIDT, <<"\n">>]), %% ?BC([<<" ">>, BaseURL, RIDT, <<"/">>, Allowed_type, <<"/\n">>]), %% ?BC([translate:translate(Lang, ?T("If you forget your RandomID, register again to receive this message.")), <<"\n">>, %% translate:translate(Lang, ?T("To get a new RandomID, disable the option and register again.")), <<"\n">>]) %% } end, Subject = ?BC([translate:translate(Lang, ?T("Web Presence")), <<": ">>, translate:translate(Lang, ?T("registered"))]), Body = ?BC([translate:translate(Lang, ?T("You have registered:")), <<" ">>, JIDS, <<"\n\n">>, translate:translate(Lang, ?T("Use URLs like:")), <<"\n">>, <<" ">>, BaseURL, <<"USERID/OUTPUT/\n">>, <<"\n">>, <<"USERID:\n">>, USERID_jid, USERID_rid, <<"\n">>, <<"OUTPUT:\n">>, Oimage, Oxml, Ojs, Otext, Oavatar, <<"\n">>, translate:translate(Lang, ?T("Example:")), <<"\n">>, Example_jid, Example_rid, <<"\n">>, Text_rid]), send_headline(Host, To, Subject, Body). send_message_unregistered(To, Host, Lang) -> Subject = ?BC([translate:translate(Lang, ?T("Web Presence")), <<": ">>, translate:translate(Lang, ?T("unregistered"))]), Body = ?BC([translate:translate(Lang, ?T("You have unregistered.")), <<"\n\n">>]), send_headline(Host, To, Subject, Body). send_headline(Host, To, Subject, Body) -> Packet = #message{type = headline, from = jid:make(Host), to = To, body = xmpp:mk_text(Body), subject = xmpp:mk_text(Subject)}, ejabberd_router:route(Packet). unregister_webpresence(From, Host, Lang) -> remove_user(From#jid.luser, From#jid.lserver), send_message_unregistered(From, Host, Lang), {result, undefined}. remove_user(User, Server) -> mnesia:dirty_delete(webpresence, {User, Server}). get_wp(LUser, LServer) -> LUS = {LUser, LServer}, case catch mnesia:dirty_read(webpresence, LUS) of {'EXIT', _Reason} -> try_auto_webpresence(LUser, LServer); [] -> try_auto_webpresence(LUser, LServer); [WP] when is_record(WP, webpresence) -> WP end. try_auto_webpresence(LUser, LServer) -> From = jid:make(LUser, LServer, <<"">>), case acl:match_rule(LServer, ?AUTO_ACL, From) of deny -> #webpresence{}; allow -> #webpresence{us = {LUser, LServer}, ridurl = true, jidurl = true, xml = true, avatar = true, js = true, text = true, icon = "jsf-jabber-text"} end. get_status_weight(Show) -> case Show of <<"chat">> -> 0; <<"available">> -> 1; <<"away">> -> 2; <<"xa">> -> 3; <<"dnd">> -> 4; _ -> 9 end. sid_to_presence({_, Pid}) -> P = ejabberd_c2s:get_presence(Pid), #presence2{resource = (P#presence.from)#jid.resource, show = misc:atom_to_binary(humanize_show(P#presence.show)), priority = P#presence.priority, status = xmpp:get_text(P#presence.status)}. humanize_show(undefined) -> available; humanize_show(Show) -> Show. get_presences({bare, LUser, LServer}) -> Sids = ejabberd_sm:get_session_sids(LUser, LServer), lists:map(fun sid_to_presence/1, Sids); get_presences({sorted, LUser, LServer}) -> lists:sort( fun(A, B) -> if A#presence2.priority == B#presence2.priority -> WA = get_status_weight(A#presence2.show), WB = get_status_weight(B#presence2.show), WA < WB; true -> A#presence2.priority > B#presence2.priority end end, get_presences({bare, LUser, LServer})); get_presences({xml, LUser, LServer, Show_us}) -> #xmlel{ name = <<"presence">>, attrs = case Show_us of true -> [{<<"user">>, LUser}, {<<"server">>, LServer}]; false -> [] end, children = lists:map( fun(Presence) -> #xmlel{ name = <<"resource">>, attrs = [ {<<"name">>, Presence#presence2.resource}, {<<"show">>, Presence#presence2.show}, {<<"priority">>, intund2string(Presence#presence2.priority)} ], children = [{xmlcdata, Presence#presence2.status}] } end, get_presences({sorted, LUser, LServer}) ) }; get_presences({status, LUser, LServer, LResource}) -> case get_presences({sorted, LUser, LServer}) of [] -> <<"unavailable">>; Rs -> {value, R} = lists:keysearch(LResource, 2, Rs), R#presence2.status end; get_presences({status, LUser, LServer}) -> case get_presences({sorted, LUser, LServer}) of [Highest | _Rest] -> Highest#presence2.status; _ -> <<"unavailable">> end; get_presences({show, LUser, LServer, LResource}) -> case get_presences({sorted, LUser, LServer}) of [] -> <<"unavailable">>; Rs -> {value, R} = lists:keysearch(LResource, 2, Rs), R#presence2.show end; get_presences({show, LUser, LServer}) -> case get_presences({sorted, LUser, LServer}) of [Highest | _Rest] -> Highest#presence2.show; _ -> <<"unavailable">> end. make_js(WP, Prs, Show_us, Lang, Q) -> {User, Server} = WP#webpresence.us, BaseURL = get_baseurl(Server), US_string = case Show_us of true -> ?BC([<<"var jabber_user='">>, User, <<"';\n">>, <<"var jabber_server='">>, Server, <<"';\n">>]); false -> <<"">> end, FunImage = fun(I, S) -> case I of <<"---">> -> <<"">>; Icon -> ?BC([<<" image:'">>, BaseURL, <<"image/">>, Icon, <<"/">>, S, <<"'\n">>]) end end, R_string_list = case Prs of [] -> Show = <<"unavailable">>, [?BC([<<"{show:'">>, Show, <<"',\n">>, <<" long_show:'">>, long_show(Show, Lang), <<"',\n">>, <<" status:'',\n">>, % TODO FunImage(WP#webpresence.icon, Show), <<"}">>])]; _ -> lists:map( fun(Pr) -> Show = Pr#presence2.show, ?BC([<<"{name:'">>, Pr#presence2.resource, <<"',\n">>, <<" priority:">>, intund2string(Pr#presence2.priority), <<",\n">>, <<" show:'">>, Show, <<"',\n">>, <<" long_show:'">>, long_show(Show, Lang), <<"',\n">>, <<" status:'">>, escape(Pr#presence2.status), <<"',\n">>, FunImage(WP#webpresence.icon, Show), <<"}">>]) end, Prs) end, R_string = lists:foldl( fun(RS, Res) -> case Res of <<"">> -> RS; _ -> ?BC([Res, <<",\n">>, RS]) end end, <<"">>, R_string_list), CB_string = case lists:keysearch(<<"cb">>, 1, Q) of {value, {_, CB}} -> ?BC([<<" ">>, CB, <<"();">>]); _ -> <<"">> end, ?BC([US_string, <<"var jabber_resources=[\n">>, R_string, <<"];">>, CB_string]). long_show(<<"available">>, Lang) -> translate:translate(Lang, ?T("available")); long_show(<<"chat">>, Lang) -> translate:translate(Lang, ?T("free for chat")); long_show(<<"away">>, Lang) -> translate:translate(Lang, ?T("away")); long_show(<<"xa">>, Lang) -> translate:translate(Lang, ?T("extended away")); long_show(<<"dnd">>, Lang) -> translate:translate(Lang, ?T("do not disturb")); long_show(_, Lang) -> translate:translate(Lang, ?T("unavailable")). intund2string(undefined) -> intund2string(0); intund2string(Int) when is_integer(Int) -> list_to_binary(integer_to_list(Int)). escape(S1) -> S2 = re:replace(S1, "\'", "\\'", [global, {return, list}]), re:replace(S2, "\n", "\\n", [global, {return, list}]). get_baseurl(Host) -> BaseURL1 = gen_mod:get_module_opt(Host, ?MODULE, baseurl), ejabberd_regexp:greplace(BaseURL1, <<"@HOST@">>, Host). -define(XML_HEADER, <<"">>). get_pixmaps_directory() -> [{directory, Path} | _] = ets:lookup(pixmaps_dirs, directory), Path. available_themes(list) -> case file:list_dir(get_pixmaps_directory()) of {ok, List} -> L2 = lists:sort(List), %% Remove from the list of themes the directories that start with a dot [T || T <- L2, hd(T) =/= 46]; {error, _} -> [] end. show_presence({image_no_check, Theme, Pr}) -> Dir = get_pixmaps_directory(), Image = ?BC([Pr, <<".{gif,png,jpg}">>]), [First | _Rest] = filelib:wildcard(binary_to_list(filename:join([Dir, Theme, Image]))), Mime = string:substr(First, string:len(First) - 2, 3), {ok, Content} = file:read_file(First), {200, [{<<"Content-Type">>, ?BC([<<"image/">>, ?BC(Mime)])}], binary_to_list(Content)}; show_presence({image, WP, LUser, LServer}) -> Icon = WP#webpresence.icon, false = (<<"---">> == Icon), Pr = get_presences({show, LUser, LServer}), show_presence({image_no_check, Icon, Pr}); show_presence({image, WP, LUser, LServer, Theme}) -> false = (<<"---">> == WP#webpresence.icon), Pr = get_presences({show, LUser, LServer}), show_presence({image_no_check, Theme, Pr}); show_presence({image_res, WP, LUser, LServer, LResource}) -> Icon = WP#webpresence.icon, false = (<<"---">> == Icon), Pr = get_presences({show, LUser, LServer, LResource}), show_presence({image_no_check, Icon, Pr}); show_presence({image_res, WP, LUser, LServer, Theme, LResource}) -> false = (<<"---">> == WP#webpresence.icon), Pr = get_presences({show, LUser, LServer, LResource}), show_presence({image_no_check, Theme, Pr}); show_presence({xml, WP, LUser, LServer, Show_us}) -> true = WP#webpresence.xml, Presence_xml = fxml:element_to_binary(get_presences({xml, LUser, LServer, Show_us})), {200, [{"Content-Type", "text/xml; charset=utf-8"}], ?BC([?XML_HEADER, Presence_xml])}; show_presence({js, WP, LUser, LServer, Show_us, Lang, Q}) -> true = WP#webpresence.js, Prs = get_presences({sorted, LUser, LServer}), Js = make_js(WP, Prs, Show_us, Lang, Q), {200, [{"Content-Type", "text/html; charset=utf-8"}], Js}; show_presence({text, WP, LUser, LServer}) -> true = WP#webpresence.text, Presence_text = get_presences({status, LUser, LServer}), {200, [{"Content-Type", "text/html; charset=utf-8"}], Presence_text}; show_presence({text, WP, LUser, LServer, LResource}) -> true = WP#webpresence.text, Presence_text = get_presences({status, LUser, LServer, LResource}), {200, [{"Content-Type", "text/html; charset=utf-8"}], Presence_text}; show_presence({avatar, WP, LUser, LServer}) -> true = WP#webpresence.avatar, [{_, Module, Function}] = ets:lookup(ejabberd_sm, {LServer, ?NS_VCARD}), JID = jid:make(LUser, LServer, <<"">>), IQ = #iq{type = get, from = JID, to = JID}, IQr = Module:Function(IQ), [VCard] = IQr#iq.sub_els, VCard2 = xmpp:decode(VCard), Mime = (VCard2#vcard_temp.photo)#vcard_photo.type, Photo = (VCard2#vcard_temp.photo)#vcard_photo.binval, {200, [{"Content-Type", Mime}], Photo}; show_presence({image_example, Theme, Show}) -> Dir = get_pixmaps_directory(), Image = ?BC([Show, <<".{gif,png,jpg}">>]), [First | _Rest] = filelib:wildcard(binary_to_list(filename:join([Dir, Theme, Image]))), Mime = string:substr(First, string:len(First) - 2, 3), {ok, Content} = file:read_file(First), {200, [{<<"Content-Type">>, ?BC([<<"image/">>, ?BC(Mime)])}], binary_to_list(Content)}. %% --------------------- %% Web Publish %% --------------------- make_xhtml(Els) -> make_xhtml([], Els). make_xhtml(Title, Els) -> #xmlel{ name = <<"html">>, attrs = [ {<<"xmlns">>, <<"http://www.w3.org/1999/xhtml">>}, {<<"xml:lang">>, <<"en">>}, {<<"lang">>, <<"en">>} ], children = [ #xmlel{ name = <<"head">>, attrs = [], children = [ #xmlel{ name = <<"meta">>, attrs = [ {<<"http-equiv">>, <<"Content-Type">>}, {<<"content">>, <<"text/html; charset=utf-8">>} ], children = [] } ] ++ Title }, #xmlel{ name = <<"body">>, attrs = [], children = Els } ] }. themes_to_xhtml(Themes) -> ShowL = ["available", "chat", "dnd", "away", "xa", "unavailable"], THeadL = [""] ++ ShowL, [?XAE(<<"table">>, [], [?XE( <<"tr">>, [?XC(<<"th">>, ?BC(T)) || T <- THeadL])] ++ [?XE(<<"tr">>, [?XC(<<"td">>, ?BC(Theme)) | [?XE(<<"td">>, [?XA(<<"img">>, [{<<"src">>, ?BC([<<"image/">>, ?BC(Theme), <<"/">>, ?BC(T)]) }])]) || T <- ShowL] ] ) || Theme <- Themes] ) ]. parse_lang(Lang) -> iolist_to_binary(hd(string:tokens(binary_to_list(Lang),"-"))). process(LocalPath, Request) -> case catch process2(LocalPath, Request) of {'EXIT', Reason} -> ?DEBUG("~p", [Request]), ?DEBUG("The call to path ~p in the~nrequest: ~p~ncrashed with error: ~p", [LocalPath, Request, Reason]), {404, [], make_xhtml([?XC(<<"h1">>, <<"Not found">>)])}; Res -> Res end. process2([], #request{lang = Lang1}) -> Lang = parse_lang(Lang1), Title = [?XC(<<"title">>, translate:translate(Lang, ?T("Web Presence")))], Desc = [?XC(<<"p">>, ?BC([ translate:translate(Lang, ?T("To publish your presence using this system you need a Jabber account in this Jabber server.")), <<" ">>, translate:translate(Lang, ?T("Login with a Jabber client, open the Service Discovery and register in Web Presence.")), translate:translate(Lang, ?T("You will receive a message with further instructions."))]))], Link_themes = [?AC(<<"themes">>, translate:translate(Lang, ?T("Icon Theme")))], Body = [?XC(<<"h1">>, translate:translate(Lang, ?T("Web Presence")))] ++ Desc ++ Link_themes, make_xhtml(Title, Body); process2([<<"themes">>], #request{lang = Lang1}) -> Lang = parse_lang(Lang1), Title = [?XC(<<"title">>, ?BC([translate:translate(Lang, ?T("Web Presence")), <<" - ">>, translate:translate(Lang, ?T("Icon Theme"))]))], Themes = available_themes(list), Icon_themes = themes_to_xhtml(Themes), Body = [?XC(<<"h1">>, translate:translate(Lang, ?T("Icon Theme")))] ++ Icon_themes, make_xhtml(Title, Body); process2([<<"image">>, Theme, Show], #request{} = _Request) -> Args = {image_example, Theme, Show}, show_presence(Args); process2([<<"jid">>, User, Server | Tail], Request) -> serve_web_presence(jid, User, Server, Tail, Request); process2([<<"rid">>, Rid | Tail], Request) -> [Pr] = mnesia:dirty_index_read(webpresence, Rid, #webpresence.ridurl), {User, Server} = Pr#webpresence.us, serve_web_presence(rid, User, Server, Tail, Request); %% Compatibility with old mod_presence process2([User, Server | Tail], Request) -> serve_web_presence(jid, User, Server, Tail, Request). serve_web_presence(TypeURL, User, Server, Tail, #request{lang = Lang1, q = Q}) -> LServer = jid:nameprep(Server), true = lists:member(Server, ejabberd_config:get_option(hosts)), LUser = jid:nodeprep(User), WP = get_wp(LUser, LServer), case TypeURL of jid -> true = WP#webpresence.jidurl; rid -> true = is_binary(WP#webpresence.ridurl) end, Show_us = (TypeURL == jid), Lang = parse_lang(Lang1), Args = case Tail of [<<"image">>, <<"theme">>, Theme, <<"res">>, Resource | _] -> {image_res, WP, LUser, LServer, Theme, Resource}; [<<"image">>, <<"theme">>, Theme | _] -> {image, WP, LUser, LServer, Theme}; [<<"image">>, <<"res">>, Resource | _] -> {image_res, WP, LUser, LServer, Resource}; [<<"image">> | _] -> {image, WP, LUser, LServer}; [<<"xml">>] -> {xml, WP, LUser, LServer, Show_us}; [<<"js">>] -> {js, WP, LUser, LServer, Show_us, Lang, Q}; [<<"text">>] -> {text, WP, LUser, LServer}; [<<"text">>, <<"res">>, Resource] -> {text, WP, LUser, LServer, Resource}; [<<"avatar">> | _] -> {avatar, WP, LUser, LServer} end, show_presence(Args). %%%% --------------------- %%%% Web Admin %%%% --------------------- web_menu_host(Acc, _Host, Lang) -> [{<<"webpresence">>, translate:translate(Lang, ?T("Web Presence"))} | Acc]. web_page_host(_, _Host, #request{path = [<<"webpresence">>], lang = Lang} = _Request) -> Res = [?XCT(<<"h1">>, <<"Web Presence">>), ?XE(<<"ul">>, [ ?LI([?ACT(<<"stats/">>, <<"Statistics">>)]), ?LI([?ACT(<<"users/">>, <<"Registered Users">>)])])], {stop, Res}; web_page_host(_, Host, #request{path = [<<"webpresence">>, <<"users">>], lang = Lang} = _Request) -> Users = get_users(Host), Table = make_users_table(Users, Lang), Res = [?XCT(<<"h1">>, <<"Web Presence">>), ?XCT(<<"h2">>, <<"Registered Users">>)] ++ Table, {stop, Res}; web_page_host(_, Host, #request{path = [<<"webpresence">>, <<"stats">>], lang = Lang} = _Request) -> Users = get_users(Host), Res = [?XCT(<<"h1">>, <<"Web Presence">>), css_table(), ?XCT(<<"h2">>, <<"Statistics">>)] ++ make_stats_options(Users, Lang) ++ make_stats_iconthemes(Users, Lang), {stop, Res}; web_page_host(Acc, _, _) -> Acc. get_users(Host) -> Select = [{{webpresence, {'$1', Host}, '$2', '$3', '$4', '$5', '$6', '$7', '$8'}, [], ['$$']}], mnesia:dirty_select(webpresence, Select). make_users_table(Records, Lang) -> TList = lists:map( fun([User, RidUrl, JIDUrl, XML, Avatar, JS, Text, Icon]) -> ?XE(<<"tr">>, [?XE(<<"td">>, [?AC(?BC([<<"../../user/">>, User, <<"/">>]), User)]), ?XC(<<"td">>, iolist_to_binary(atom_to_list(JIDUrl))), ?XC(<<"td">>, ridurl_out(RidUrl)), ?XC(<<"td">>, Icon), ?XC(<<"td">>, iolist_to_binary(atom_to_list(XML))), ?XC(<<"td">>, iolist_to_binary(atom_to_list(JS))), ?XC(<<"td">>, iolist_to_binary(atom_to_list(Text))), ?XC(<<"td">>, iolist_to_binary(atom_to_list(Avatar)))]) end, Records), [?XE(<<"table">>, [?XE(<<"thead">>, [?XE(<<"tr">>, [?XCT(<<"td">>, <<"User">>), ?XCT(<<"td">>, <<"Jabber ID">>), ?XCT(<<"td">>, <<"Random ID">>), ?XCT(<<"td">>, <<"Icon Theme">>), ?XC(<<"td">>, <<"XML">>), ?XC(<<"td">>, <<"JS">>), ?XCT(<<"td">>, <<"Text">>), ?XCT(<<"td">>, <<"Avatar">>) ])]), ?XE(<<"tbody">>, TList)])]. make_stats_options(Records, Lang) -> [RegUsers, JJ, RR, XX, AA, SS, TT, II] = lists:foldl( fun([_User, RidUrl, JidUrl, XML, Avatar, JS, Text, Icon], [N, J, R, X, A, S, T, I]) -> J2 = J + case JidUrl of false -> 0; true -> 1 end, R2 = R + case RidUrl of false -> 0; _ -> 1 end, X2 = X + case XML of false -> 0; true -> 1 end, A2 = A + case Avatar of false -> 0; true -> 1 end, S2 = S + case JS of false -> 0; true -> 1 end, T2 = T + case Text of false -> 0; true -> 1 end, I2 = I + case Icon of <<"---">> -> 0; _ -> 1 end, [N+1, J2, R2, X2, A2, S2, T2, I2] end, [0, 0, 0, 0, 0, 0, 0, 0], Records), URLTList = [{<<"Jabber ID">>, JJ}, {<<"Random ID">>, RR}], OutputTList = [{<<"Icon Theme">>, II}, {<<"XML">>, XX}, {<<"JavaScript">>, SS}, {<<"Text">>, TT}, {<<"Avatar">>, AA}], [ ?C(?BC([<<"Registered Users">>, <<": ">>, iolist_to_binary(integer_to_list(RegUsers))])), ?XCT(<<"h3">>, <<"URL Type">>), ?XAE(<<"table">>, [{<<"class">>, <<"stats">>}], [?XE(<<"tbody">>, do_stat_table_with(URLTList, RegUsers))] ), ?XCT(<<"h3">>, <<"Output Type">>), ?XAE(<<"table">>, [{<<"class">>, <<"stats">>}], [?XE(<<"tbody">>, do_stat_table_with(OutputTList, RegUsers))] )]. make_stats_iconthemes(Records, Lang) -> Themes1 = [{T, 0} || T <- available_themes(list)], Dict = lists:foldl( fun([_, _, _, _, _, _, _, Icon], D) -> dict:update_counter(Icon, 1, D) end, dict:from_list(Themes1), Records), Themes = lists:keysort(1, dict:to_list(Dict)), [?XCT(<<"h3">>, <<"Icon Theme">>), ?XAE(<<"table">>, [{<<"class">>, <<"stats">>}], [?XE(<<"tbody">>, do_stat_table_with(Themes))] )]. %% Do table with bars do_stat_table_with(Values) -> Ns = [Ni || {_, Ni} <- Values], Total = lists:sum(Ns), do_stat_table_with(Values, Total). do_stat_table_with(Values, Total) -> lists:map( fun({L, N}) -> Perc = case Total of 0 -> <<"0">>; _ -> iolist_to_binary(integer_to_list(trunc(100 * N / Total))) end, do_table_element(?C(L), io_lib:format("~p", [N]), Perc) end, Values). do_table_element(L, [N], Perc) -> ?XE(<<"tr">>, [?XE(<<"td">>, [L]), ?XAC(<<"td">>, [{<<"class">>, <<"alignright">>}], ?BC(N)), ?XE(<<"td">>, [?XAE(<<"div">>, [{<<"class">>, <<"graph">>}], [?XAC(<<"div">>, [{<<"class">>, <<"bar">>}, {<<"style">>, ?BC(["width: ", Perc, "%;"])}], <<>> )] )] ), ?XAC(<<"td">>, [{<<"class">>, <<"alignright">>}], ?BC([Perc, "%"])) ]). css_table()-> ?XAE(<<"style">>, [{<<"type">>, <<"text/css">>}], [?C(<<".stats { padding-left: 20px; padding-top: 10px; } .graph { position: relative; width: 200px; border: 1px solid #D47911; padding: 1px; } .graph .bar { display: block; position: relative; background: #FFE3C9; text-align: center; color: #333; height: 1.5em; line-height: 1.5em; } .graph .bar span { position: absolute; left: 1em; }">>)]). %%%-------------------------------- %%% Update table schema and content from older versions %%%-------------------------------- update_table() -> case catch mnesia:table_info(presence_registered, size) of Size when is_integer(Size) -> catch migrate_data_mod_presence(Size); _ -> ok end. migrate_data_mod_presence(Size) -> Migrate = fun(Old, S) -> {presence_registered, {US, _Host}, XML, Icon} = Old, New = #webpresence{us = US, ridurl = false, jidurl = true, xml = list_to_atom(XML), avatar = false, js = false, text = false, icon = Icon}, mnesia:write(New), mnesia:delete_object(Old), S-1 end, F = fun() -> mnesia:foldl(Migrate, Size, presence_registered) end, {atomic, 0} = mnesia:transaction(F), {atomic, ok} = mnesia:delete_table(presence_registered). tmpogm5kjkl/mod_webpresence/AUTHORS0000664000175000017500000000117014751665140020123 0ustar debalancedebalance CODE ---- Igor Goryachev: author of the original mod_presence Badlop: added WebAdmin features Tobias Markmann: example PHP code PIXMAPS ------- This module includes pixmap artwork from many different authors. The list of known authors in alphabetical order is shown below. Your help to complete this information is appreciated. Everaldo Coelho: crystal Jason Kim: stellar NoAlWin: jsf-jabber-text, jsf-text and jsf-text2 Unknown author: alphamod amibulb amiglobe dcraven dudes frickenhuge gabber gnome goojim gossip gota gtalk invision jabberbulb msn_amicons nuvola phpbb simplebulb star_amicons sun zyx tmpogm5kjkl/mod_webpresence/README.md0000664000175000017500000001766514751665140020352 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 `