From 628571f8cffd56174d762117064876cef82fd262 Mon Sep 17 00:00:00 2001 From: Christophe Romain Date: Tue, 13 Jul 2010 12:04:30 +0200 Subject: [PATCH 01/85] merge from ekhramtsov-ejabberd, which is latest 2.1.x with consistent hash --- contrib/ejabberd-modules.repo | 5 - src/Makefile.in | 14 +- src/aclocal.m4 | 17 +- src/configure | 36 ++- src/configure.ac | 11 +- src/ejabberd.app | 1 + src/ejabberd_app.erl | 3 + src/ejabberd_auth_anonymous.erl | 16 +- src/ejabberd_c2s.erl | 178 ++++++++++----- src/ejabberd_captcha.erl | 151 +++++++------ src/ejabberd_cluster.erl | 177 +++++++++++++++ src/ejabberd_ctl.erl | 3 +- src/ejabberd_debug.erl | 97 --------- src/ejabberd_frontend_socket.erl | 87 ++++---- src/ejabberd_local.erl | 50 ++--- src/ejabberd_node_groups.erl | 40 ++-- src/ejabberd_receiver.erl | 125 +++++++++-- src/ejabberd_router.erl | 37 +++- src/ejabberd_s2s.erl | 137 ++++++++---- src/ejabberd_s2s_in.erl | 10 +- src/ejabberd_s2s_out.erl | 25 ++- src/ejabberd_service.erl | 4 +- src/ejabberd_sm.erl | 204 ++++++++++------- src/ejabberd_socket.erl | 60 +++-- src/ejabberd_sup.erl | 16 +- src/ejabberdctl.template | 8 +- src/mod_last.erl | 2 +- src/mod_last_odbc.erl | 2 +- src/mod_muc/mod_muc.erl | 180 +++++++++------ src/mod_muc/mod_muc_log.erl | 24 +- src/mod_muc/mod_muc_room.erl | 82 ++++--- src/mod_offline_odbc.erl | 3 +- src/mod_proxy65/mod_proxy65_sm.erl | 10 + src/odbc/ejabberd_odbc.erl | 2 + src/odbc/ejabberd_odbc_sup.erl | 41 +++- src/p1_fsm.erl | 70 +++++- src/p1_prof.erl | 337 +++++++++++++++++++++++++++++ src/tls/Makefile.in | 1 + src/tls/tls.erl | 10 +- src/web/Makefile.in | 2 +- src/web/ejabberd_http_bind.erl | 110 +++++++--- src/web/ejabberd_http_poll.erl | 57 ++++- src/web/mod_http_bind.erl | 10 +- src/web/mod_http_fileserver.erl | 4 + src/xml.c | 230 ++++++++++++++++++++ src/xml.erl | 19 ++ src/xml_stream.erl | 3 + 47 files changed, 2028 insertions(+), 683 deletions(-) delete mode 100644 contrib/ejabberd-modules.repo create mode 100644 src/ejabberd_cluster.erl delete mode 100644 src/ejabberd_debug.erl create mode 100644 src/p1_prof.erl create mode 100644 src/xml.c diff --git a/contrib/ejabberd-modules.repo b/contrib/ejabberd-modules.repo deleted file mode 100644 index dfd4a1d17..000000000 --- a/contrib/ejabberd-modules.repo +++ /dev/null @@ -1,5 +0,0 @@ -% List of ejabberd-modules to add for ejabberd packaging (source archive and installer) -% -% HTTP-binding: -%https://svn.process-one.net/ejabberd-modules/http_bind/trunk -%https://svn.process-one.net/ejabberd-modules/mod_http_fileserver/trunk diff --git a/src/Makefile.in b/src/Makefile.in index 94fa8b1ac..cf600c324 100644 --- a/src/Makefile.in +++ b/src/Makefile.in @@ -30,16 +30,15 @@ else INIT_USER=$(INSTALLUSER) endif -EFLAGS += @ERLANG_SSL39@ -pa . +EFLAGS += @ERLANG_SSLVER@ -pa . # make debug=true to compile Erlang module with debug informations. ifdef debug EFLAGS+=+debug_info +export_all endif -DEBUGTOOLS = ejabberd_debug.erl -ifdef ejabberd_debug - EFLAGS+=-Dejabberd_debug +DEBUGTOOLS = p1_prof.erl +ifdef debugtools SOURCES+=$(DEBUGTOOLS) endif @@ -55,6 +54,11 @@ ifeq (@full_xml@, true) EFLAGS+=-DFULL_XML_SUPPORT endif +ifeq (@nif@, true) + EFLAGS+=-DNIF + ERLSHLIBS=xml.so +endif + ifeq (@transient_supervisors@, false) EFLAGS+=-DNO_TRANSIENT_SUPERVISORS endif @@ -68,7 +72,7 @@ prefix = @prefix@ exec_prefix = @exec_prefix@ SUBDIRS = @mod_irc@ @mod_pubsub@ @mod_muc@ @mod_proxy65@ @eldap@ @pam@ @web@ stringprep stun @tls@ @odbc@ @ejabberd_zlib@ -ERLSHLIBS = expat_erl.so +ERLSHLIBS += expat_erl.so ERLBEHAVS = cyrsasl.erl gen_mod.erl p1_fsm.erl SOURCES_ALL = $(wildcard *.erl) SOURCES_MISC = $(ERLBEHAVS) $(DEBUGTOOLS) diff --git a/src/aclocal.m4 b/src/aclocal.m4 index 79b0e3ec7..09b166b99 100644 --- a/src/aclocal.m4 +++ b/src/aclocal.m4 @@ -121,7 +121,6 @@ AC_DEFUN(AM_WITH_ERLANG, -author('alexey@sevcom.net'). -export([[start/0]]). --include_lib("ssl/include/ssl_pkix.hrl"). start() -> EIDirS = code:lib_dir("erl_interface") ++ "\n", @@ -130,11 +129,13 @@ start() -> file:write_file("conftest.out", list_to_binary(EIDirS ++ EILibS ++ ssldef() ++ RootDirS)), halt(). --[ifdef]('id-pkix'). -ssldef() -> "-DSSL39\n". --else. -ssldef() -> "\n". --endif. +ssldef() -> + OTP = (catch erlang:system_info(otp_release)), + if + OTP >= "R14" -> "-DSSL40\n"; + OTP >= "R12" -> "-DSSL39\n"; + true -> "" + end. %% return physical architecture based on OS/Processor archname() -> @@ -184,7 +185,7 @@ _EOF # Second line ERLANG_EI_LIB=`cat conftest.out | head -n 2 | tail -n 1` # Third line - ERLANG_SSL39=`cat conftest.out | head -n 3 | tail -n 1` + ERLANG_SSLVER=`cat conftest.out | head -n 3 | tail -n 1` # End line ERLANG_DIR=`cat conftest.out | tail -n 1` @@ -193,7 +194,7 @@ _EOF AC_SUBST(ERLANG_CFLAGS) AC_SUBST(ERLANG_LIBS) - AC_SUBST(ERLANG_SSL39) + AC_SUBST(ERLANG_SSLVER) AC_SUBST(ERLC) AC_SUBST(ERL) ]) diff --git a/src/configure b/src/configure index db7e63b43..a698ae8bb 100755 --- a/src/configure +++ b/src/configure @@ -611,6 +611,7 @@ build INSTALLUSER SSL_CFLAGS SSL_LIBS +nif full_xml transient_supervisors db_type @@ -647,7 +648,7 @@ EGREP GREP CPP LIBICONV -ERLANG_SSL39 +ERLANG_SSLVER ERLANG_LIBS ERLANG_CFLAGS ERL @@ -721,6 +722,7 @@ enable_roster_gateway_workaround enable_mssql enable_transient_supervisors enable_full_xml +enable_nif with_openssl enable_user ' @@ -1372,6 +1374,8 @@ Optional Features: (default: yes) --enable-full-xml use XML features in XMPP stream (ex: CDATA) (default: no, requires XML compliant clients) + --enable-nif replace some functions with C equivalents. Requires + Erlang R13B04 or higher (default: no) --enable-user[[[=USER]]] allow this system user to start ejabberd (default: no) @@ -3207,7 +3211,6 @@ fi -author('alexey@sevcom.net'). -export([start/0]). --include_lib("ssl/include/ssl_pkix.hrl"). start() -> EIDirS = code:lib_dir("erl_interface") ++ "\n", @@ -3216,11 +3219,13 @@ start() -> file:write_file("conftest.out", list_to_binary(EIDirS ++ EILibS ++ ssldef() ++ RootDirS)), halt(). --ifdef('id-pkix'). -ssldef() -> "-DSSL39\n". --else. -ssldef() -> "\n". --endif. +ssldef() -> + OTP = (catch erlang:system_info(otp_release)), + if + OTP >= "R14" -> "-DSSL40\n"; + OTP >= "R12" -> "-DSSL39\n"; + true -> "" + end. %% return physical architecture based on OS/Processor archname() -> @@ -3270,7 +3275,7 @@ _EOF # Second line ERLANG_EI_LIB=`cat conftest.out | head -n 2 | tail -n 1` # Third line - ERLANG_SSL39=`cat conftest.out | head -n 3 | tail -n 1` + ERLANG_SSLVER=`cat conftest.out | head -n 3 | tail -n 1` # End line ERLANG_DIR=`cat conftest.out | tail -n 1` @@ -4650,7 +4655,7 @@ if test "${enable_transient_supervisors+set}" = set; then : enableval=$enable_transient_supervisors; case "${enableval}" in yes) transient_supervisors=true ;; no) transient_supervisors=false ;; - *) as_fn_error "bad value ${enableval} for --enable-full-xml" "$LINENO" 5 ;; + *) as_fn_error "bad value ${enableval} for --enable-transient_supervisors" "$LINENO" 5 ;; esac else transient_supervisors=true @@ -4671,6 +4676,19 @@ fi +# Check whether --enable-nif was given. +if test "${enable_nif+set}" = set; then : + enableval=$enable_nif; case "${enableval}" in + yes) nif=true ;; + no) nif=false ;; + *) as_fn_error "bad value ${enableval} for --enable-nif" "$LINENO" 5 ;; +esac +else + nif=false +fi + + + ac_config_files="$ac_config_files Makefile $make_mod_irc $make_mod_muc $make_mod_pubsub $make_mod_proxy65 $make_eldap $make_pam $make_web stringprep/Makefile stun/Makefile $make_tls $make_odbc $make_ejabberd_zlib" #openssl diff --git a/src/configure.ac b/src/configure.ac index 20bfdf6f1..1497643d3 100644 --- a/src/configure.ac +++ b/src/configure.ac @@ -81,7 +81,7 @@ AC_ARG_ENABLE(transient_supervisors, [case "${enableval}" in yes) transient_supervisors=true ;; no) transient_supervisors=false ;; - *) AC_MSG_ERROR(bad value ${enableval} for --enable-full-xml) ;; + *) AC_MSG_ERROR(bad value ${enableval} for --enable-transient_supervisors) ;; esac],[transient_supervisors=true]) AC_SUBST(transient_supervisors) @@ -94,6 +94,15 @@ AC_ARG_ENABLE(full_xml, esac],[full_xml=false]) AC_SUBST(full_xml) +AC_ARG_ENABLE(nif, +[AC_HELP_STRING([--enable-nif], [replace some functions with C equivalents. Requires Erlang R13B04 or higher (default: no)])], +[case "${enableval}" in + yes) nif=true ;; + no) nif=false ;; + *) AC_MSG_ERROR(bad value ${enableval} for --enable-nif) ;; +esac],[nif=false]) +AC_SUBST(nif) + AC_CONFIG_FILES([Makefile $make_mod_irc $make_mod_muc diff --git a/src/ejabberd.app b/src/ejabberd.app index e347daf3b..67653d241 100644 --- a/src/ejabberd.app +++ b/src/ejabberd.app @@ -115,6 +115,7 @@ nodetree_virtual, p1_fsm, p1_mnesia, + p1_prof, randoms, sha, shaper, diff --git a/src/ejabberd_app.erl b/src/ejabberd_app.erl index 7a54fcc37..a14a53ed4 100644 --- a/src/ejabberd_app.erl +++ b/src/ejabberd_app.erl @@ -46,6 +46,7 @@ start(normal, _Args) -> db_init(), sha:start(), stringprep_sup:start_link(), + xml:start(), start(), translate:start(), acl:start(), @@ -65,6 +66,8 @@ start(normal, _Args) -> %ejabberd_debug:fprof_start(), maybe_add_nameservers(), start_modules(), + ejabberd_cluster:announce(), + ejabberd_node_groups:start(), ejabberd_listener:start_listeners(), ?INFO_MSG("ejabberd ~s is started in the node ~p", [?VERSION, node()]), Sup; diff --git a/src/ejabberd_auth_anonymous.erl b/src/ejabberd_auth_anonymous.erl index 1f86e2cc5..1e6a81f22 100644 --- a/src/ejabberd_auth_anonymous.erl +++ b/src/ejabberd_auth_anonymous.erl @@ -61,9 +61,11 @@ %% Register to login / logout events start(Host) -> %% TODO: Check cluster mode + update_tables(), mnesia:create_table(anonymous, [{ram_copies, [node()]}, - {type, bag}, + {type, bag}, {local_content, true}, {attributes, record_info(fields, anonymous)}]), + mnesia:add_table_copy(anonymous, node(), ram_copies), %% The hooks are needed to add / remove users from the anonymous tables ejabberd_hooks:add(sm_register_connection_hook, Host, ?MODULE, register_connection, 100), @@ -136,7 +138,7 @@ remove_connection(SID, LUser, LServer) -> F = fun() -> mnesia:delete_object({anonymous, US, SID}) end, - mnesia:transaction(F). + mnesia:async_dirty(F). %% Register connection register_connection(SID, #jid{luser = LUser, lserver = LServer}, Info) -> @@ -144,7 +146,7 @@ register_connection(SID, #jid{luser = LUser, lserver = LServer}, Info) -> case AuthModule == ?MODULE of true -> US = {LUser, LServer}, - mnesia:sync_dirty( + mnesia:async_dirty( fun() -> mnesia:write(#anonymous{us = US, sid=SID}) end); false -> @@ -246,3 +248,11 @@ remove_user(_User, _Server, _Password) -> plain_password_required() -> false. + +update_tables() -> + case catch mnesia:table_info(anonymous, local_content) of + false -> + mnesia:delete_table(anonymous); + _ -> + ok + end. diff --git a/src/ejabberd_c2s.erl b/src/ejabberd_c2s.erl index 6238cdae5..b25b0df83 100644 --- a/src/ejabberd_c2s.erl +++ b/src/ejabberd_c2s.erl @@ -35,7 +35,7 @@ %% External exports -export([start/2, stop/1, - start_link/2, + start_link/3, send_text/2, send_element/2, socket_type/0, @@ -56,8 +56,9 @@ code_change/4, handle_info/3, terminate/3, - print_state/1 - ]). + print_state/1, + migrate/3 + ]). -include("ejabberd.hrl"). -include("jlib.hrl"). @@ -96,6 +97,7 @@ conn = unknown, auth_module = unknown, ip, + fsm_limit_opts, lang}). %-define(DBGFSM, true). @@ -108,11 +110,12 @@ %% Module start with or without supervisor: -ifdef(NO_TRANSIENT_SUPERVISORS). --define(SUPERVISOR_START, ?GEN_FSM:start(ejabberd_c2s, [SockData, Opts], - fsm_limit_opts(Opts) ++ ?FSMOPTS)). +-define(SUPERVISOR_START, ?GEN_FSM:start(ejabberd_c2s, + [SockData, Opts, FSMLimitOpts], + FSMLimitOpts ++ ?FSMOPTS)). -else. -define(SUPERVISOR_START, supervisor:start_child(ejabberd_c2s_sup, - [SockData, Opts])). + [SockData, Opts, FSMLimitOpts])). -endif. %% This is the timeout to apply between event when starting a new @@ -140,12 +143,17 @@ %%%---------------------------------------------------------------------- %%% API %%%---------------------------------------------------------------------- +start(StateName, #state{fsm_limit_opts = Opts} = State) -> + start(StateName, State, Opts); start(SockData, Opts) -> + start(SockData, Opts, fsm_limit_opts(Opts)). + +start(SockData, Opts, FSMLimitOpts) -> ?SUPERVISOR_START. -start_link(SockData, Opts) -> - ?GEN_FSM:start_link(ejabberd_c2s, [SockData, Opts], - fsm_limit_opts(Opts) ++ ?FSMOPTS). +start_link(SockData, Opts, FSMLimitOpts) -> + ?GEN_FSM:start_link(ejabberd_c2s, [SockData, Opts, FSMLimitOpts], + FSMLimitOpts ++ ?FSMOPTS). socket_type() -> xml_stream. @@ -157,6 +165,9 @@ get_presence(FsmRef) -> stop(FsmRef) -> ?GEN_FSM:send_event(FsmRef, closed). +migrate(FsmRef, Node, After) -> + ?GEN_FSM:send_all_state_event(FsmRef, {migrate, Node, After}). + %%%---------------------------------------------------------------------- %%% Callback functions from gen_fsm %%%---------------------------------------------------------------------- @@ -168,7 +179,7 @@ stop(FsmRef) -> %% ignore | %% {stop, StopReason} %%---------------------------------------------------------------------- -init([{SockMod, Socket}, Opts]) -> +init([{SockMod, Socket}, Opts, FSMLimitOpts]) -> Access = case lists:keysearch(access, 1, Opts) of {value, {_, A}} -> A; _ -> all @@ -192,7 +203,12 @@ init([{SockMod, Socket}, Opts]) -> (_) -> false end, Opts), TLSOpts = [verify_none | TLSOpts1], - IP = peerip(SockMod, Socket), + IP = case lists:keysearch(frontend_ip, 1, Opts) of + {value, {_, IP1}} -> + IP1; + _ -> + peerip(SockMod, Socket) + end, %% Check if IP is blacklisted: case is_ip_blacklisted(IP) of true -> @@ -220,8 +236,35 @@ init([{SockMod, Socket}, Opts]) -> streamid = new_id(), access = Access, shaper = Shaper, - ip = IP}, + ip = IP, + fsm_limit_opts = FSMLimitOpts}, ?C2S_OPEN_TIMEOUT} + end; +init([StateName, StateData, _FSMLimitOpts]) -> + MRef = (StateData#state.sockmod):monitor(StateData#state.socket), + if StateName == session_established -> + Conn = get_conn_type(StateData), + Info = [{ip, StateData#state.ip}, {conn, Conn}, + {auth_module, StateData#state.auth_module}], + {Time, _} = StateData#state.sid, + SID = {Time, self()}, + Priority = case StateData#state.pres_last of + undefined -> + undefined; + El -> + get_priority_from_presence(El) + end, + ejabberd_sm:open_session( + SID, + StateData#state.user, + StateData#state.server, + StateData#state.resource, + Priority, + Info), + NewStateData = StateData#state{sid = SID, socket_monitor = MRef}, + {ok, StateName, NewStateData}; + true -> + {ok, StateName, StateData#state{socket_monitor = MRef}} end. %% Return list of all available resources of contacts, @@ -469,13 +512,13 @@ wait_for_auth({xmlstreamelement, El}, StateData) -> jlib:jid_to_string(JID), AuthModule]), SID = {now(), self()}, Conn = get_conn_type(StateData), - Info = [{ip, StateData#state.ip}, {conn, Conn}, - {auth_module, AuthModule}], + %% Info = [{ip, StateData#state.ip}, {conn, Conn}, + %% {auth_module, AuthModule}], Res1 = jlib:make_result_iq_reply(El), Res = setelement(4, Res1, []), send_element(StateData, Res), - ejabberd_sm:open_session( - SID, U, StateData#state.server, R, Info), + %% ejabberd_sm:open_session( + %% SID, U, StateData#state.server, R, Info), change_shaper(StateData, JID), {Fs, Ts} = ejabberd_hooks:run_fold( roster_get_subscription_lists, @@ -502,8 +545,7 @@ wait_for_auth({xmlstreamelement, El}, StateData) -> pres_f = ?SETS:from_list(Fs1), pres_t = ?SETS:from_list(Ts1), privacy_list = PrivList}, - fsm_next_state_pack(session_established, - NewStateData); + maybe_migrate(session_established, NewStateData); _ -> ?INFO_MSG( "(~w) Failed legacy authentication for ~s", @@ -627,7 +669,7 @@ wait_for_feature_request({xmlstreamelement, El}, StateData) -> Socket = StateData#state.socket, TLSSocket = (StateData#state.sockmod):starttls( Socket, TLSOpts, - xml:element_to_string( + xml:element_to_binary( {xmlelement, "proceed", [{"xmlns", ?NS_TLS}], []})), fsm_next_state(wait_for_stream, StateData#state{socket = TLSSocket, @@ -650,7 +692,7 @@ wait_for_feature_request({xmlstreamelement, El}, StateData) -> Socket = StateData#state.socket, ZlibSocket = (StateData#state.sockmod):compress( Socket, - xml:element_to_string( + xml:element_to_binary( {xmlelement, "compressed", [{"xmlns", ?NS_COMPRESS}], []})), fsm_next_state(wait_for_stream, @@ -831,7 +873,7 @@ wait_for_session({xmlstreamelement, El}, StateData) -> case jlib:iq_query_info(El) of #iq{type = set, xmlns = ?NS_SESSION} -> U = StateData#state.user, - R = StateData#state.resource, + %%R = StateData#state.resource, JID = StateData#state.jid, case acl:match_rule(StateData#state.server, StateData#state.access, JID) of @@ -857,10 +899,10 @@ wait_for_session({xmlstreamelement, El}, StateData) -> [U, StateData#state.server]), SID = {now(), self()}, Conn = get_conn_type(StateData), - Info = [{ip, StateData#state.ip}, {conn, Conn}, - {auth_module, StateData#state.auth_module}], - ejabberd_sm:open_session( - SID, U, StateData#state.server, R, Info), + %% Info = [{ip, StateData#state.ip}, {conn, Conn}, + %% {auth_module, StateData#state.auth_module}], + %% ejabberd_sm:open_session( + %% SID, U, StateData#state.server, R, Info), NewStateData = StateData#state{ sid = SID, @@ -868,8 +910,7 @@ wait_for_session({xmlstreamelement, El}, StateData) -> pres_f = ?SETS:from_list(Fs1), pres_t = ?SETS:from_list(Ts1), privacy_list = PrivList}, - fsm_next_state_pack(session_established, - NewStateData); + maybe_migrate(session_established, NewStateData); _ -> ejabberd_hooks:run(forbidden_session_hook, StateData#state.server, [JID]), @@ -1047,6 +1088,8 @@ session_established2(El, StateData) -> %% {next_state, NextStateName, NextStateData, Timeout} | %% {stop, Reason, NewStateData} %%---------------------------------------------------------------------- +handle_event({migrate, Node, After}, StateName, StateData) when Node /= node() -> + fsm_migrate(StateName, StateData, Node, After * 2); handle_event(_Event, StateName, StateData) -> fsm_next_state(StateName, StateData). @@ -1382,6 +1425,22 @@ print_state(State = #state{pres_t = T, pres_f = F, pres_a = A, pres_i = I}) -> %% Purpose: Shutdown the fsm %% Returns: any %%---------------------------------------------------------------------- +terminate({migrated, ClonePid}, StateName, StateData) -> + if StateName == session_established -> + ?INFO_MSG("(~w) Migrating ~s to ~p on node ~p", + [StateData#state.socket, + jlib:jid_to_string(StateData#state.jid), + ClonePid, node(ClonePid)]), + ejabberd_sm:close_session(StateData#state.sid, + StateData#state.user, + StateData#state.server, + StateData#state.resource); + true -> + ok + end, + (StateData#state.sockmod):change_controller( + StateData#state.socket, ClonePid), + ok; terminate(_Reason, StateName, StateData) -> case StateName of session_established -> @@ -1453,14 +1512,14 @@ change_shaper(StateData, JID) -> (StateData#state.sockmod):change_shaper(StateData#state.socket, Shaper). send_text(StateData, Text) -> - ?DEBUG("Send XML on stream = ~p", [lists:flatten(Text)]), + ?DEBUG("Send XML on stream = ~p", [Text]), (StateData#state.sockmod):send(StateData#state.socket, Text). send_element(StateData, El) when StateData#state.xml_socket -> (StateData#state.sockmod):send_xml(StateData#state.socket, {xmlstreamelement, El}); send_element(StateData, El) -> - send_text(StateData, xml:element_to_string(El)). + send_text(StateData, xml:element_to_binary(El)). send_header(StateData, Server, Version, Lang) when StateData#state.xml_socket -> @@ -1550,16 +1609,21 @@ get_auth_tags([], U, P, D, R) -> get_conn_type(StateData) -> case (StateData#state.sockmod):get_sockmod(StateData#state.socket) of - gen_tcp -> c2s; - tls -> c2s_tls; - ejabberd_zlib -> - case ejabberd_zlib:get_sockmod((StateData#state.socket)#socket_state.socket) of - gen_tcp -> c2s_compressed; - tls -> c2s_compressed_tls - end; - ejabberd_http_poll -> http_poll; - ejabberd_http_bind -> http_bind; - _ -> unknown + gen_tcp -> c2s; + tls -> c2s_tls; + ejabberd_zlib -> + if is_pid(StateData#state.socket) -> + unknown; + true -> + case ejabberd_zlib:get_sockmod( + (StateData#state.socket)#socket_state.socket) of + gen_tcp -> c2s_compressed; + tls -> c2s_compressed_tls + end + end; + ejabberd_http_poll -> http_poll; + ejabberd_http_bind -> http_bind; + _ -> unknown end. process_presence_probe(From, To, StateData) -> @@ -2158,16 +2222,28 @@ peerip(SockMod, Socket) -> _ -> undefined end. -%% fsm_next_state_pack: Pack the StateData structure to improve -%% sharing. -fsm_next_state_pack(StateName, StateData) -> - fsm_next_state_gc(StateName, pack(StateData)). - -%% fsm_next_state_gc: Garbage collect the process heap to make use of -%% the newly packed StateData structure. -fsm_next_state_gc(StateName, PackedStateData) -> - erlang:garbage_collect(), - fsm_next_state(StateName, PackedStateData). +maybe_migrate(StateName, StateData) -> + PackedStateData = pack(StateData), + case ejabberd_cluster:get_node({StateData#state.user, + StateData#state.server}) of + Node when Node == node() -> + Conn = get_conn_type(StateData), + Info = [{ip, StateData#state.ip}, {conn, Conn}, + {auth_module, StateData#state.auth_module}], + #state{user = U, server = S, resource = R, sid = SID} = StateData, + ejabberd_sm:open_session(SID, U, S, R, Info), + erlang:garbage_collect(), + case ejabberd_cluster:get_node_new({U, S}) of + Node -> + ok; + NewNode -> + After = ejabberd_cluster:rehash_timeout(), + migrate(self(), NewNode, After) + end, + fsm_next_state(StateName, PackedStateData); + Node -> + fsm_migrate(StateName, PackedStateData, Node, 0) + end. %% fsm_next_state: Generate the next_state FSM tuple with different %% timeout, depending on the future state @@ -2176,6 +2252,10 @@ fsm_next_state(session_established, StateData) -> fsm_next_state(StateName, StateData) -> {next_state, StateName, StateData, ?C2S_OPEN_TIMEOUT}. +fsm_migrate(StateName, StateData, Node, Timeout) -> + {migrate, StateData, + {Node, ?MODULE, start, [StateName, StateData]}, Timeout}. + %% fsm_reply: Generate the reply FSM tuple with different timeout, %% depending on the future state fsm_reply(Reply, session_established, StateData) -> diff --git a/src/ejabberd_captcha.erl b/src/ejabberd_captcha.erl index ab3271b80..e575d7c40 100644 --- a/src/ejabberd_captcha.erl +++ b/src/ejabberd_captcha.erl @@ -35,7 +35,7 @@ -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). --export([create_captcha/6, build_captcha_html/2, check_captcha/2, +-export([create_captcha/5, build_captcha_html/2, check_captcha/2, process_reply/1, process/2, is_feature_available/0]). -include("jlib.hrl"). @@ -48,19 +48,11 @@ -define(CAPTCHA_TEXT(Lang), translate:translate(Lang, "Enter the text you see")). -define(CAPTCHA_LIFETIME, 120000). % two minutes +-define(RPC_TIMEOUT, 5000). -record(state, {}). -record(captcha, {id, pid, key, tref, args}). --define(T(S), - case catch mnesia:transaction(fun() -> S end) of - {atomic, Res} -> - Res; - {_, Reason} -> - ?ERROR_MSG("mnesia transaction failed: ~p", [Reason]), - {error, Reason} - end). - %%==================================================================== %% API %%==================================================================== @@ -71,11 +63,12 @@ start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). -create_captcha(Id, SID, From, To, Lang, Args) - when is_list(Id), is_list(Lang), is_list(SID), +create_captcha(SID, From, To, Lang, Args) + when is_list(Lang), is_list(SID), is_record(From, jid), is_record(To, jid) -> case create_image() of {ok, Type, Key, Image} -> + Id = randoms:get_string() ++ "-" ++ ejabberd_cluster:node_id(), B64Image = jlib:encode_base64(binary_to_list(Image)), JID = jlib:jid_to_string(From), CID = "sha1+" ++ sha:sha(Image) ++ "@bob.xmpp.org", @@ -101,13 +94,9 @@ create_captcha(Id, SID, From, To, Lang, Args) OOB = {xmlelement, "x", [{"xmlns", ?NS_OOB}], [{xmlelement, "url", [], [{xmlcdata, get_url(Id)}]}]}, Tref = erlang:send_after(?CAPTCHA_LIFETIME, ?MODULE, {remove_id, Id}), - case ?T(mnesia:write(#captcha{id=Id, pid=self(), key=Key, - tref=Tref, args=Args})) of - ok -> - {ok, [Body, OOB, Captcha, Data]}; - _Err -> - error - end; + ets:insert(captcha, #captcha{id=Id, pid=self(), key=Key, + tref=Tref, args=Args}), + {ok, Id, [Body, OOB, Captcha, Data]}; _Err -> error end. @@ -119,8 +108,8 @@ create_captcha(Id, SID, From, To, Lang, Args) %% IdEl = xmlelement() %% KeyEl = xmlelement() build_captcha_html(Id, Lang) -> - case mnesia:dirty_read(captcha, Id) of - [#captcha{}] -> + case lookup_captcha(Id) of + {ok, _} -> ImgEl = {xmlelement, "img", [{"src", get_url(Id ++ "/image")}], []}, TextEl = {xmlcdata, ?CAPTCHA_TEXT(Lang)}, IdEl = {xmlelement, "input", [{"type", "hidden"}, @@ -150,21 +139,25 @@ build_captcha_html(Id, Lang) -> %% @spec (Id::string(), ProvidedKey::string()) -> captcha_valid | captcha_non_valid | captcha_not_found check_captcha(Id, ProvidedKey) -> - ?T(case mnesia:read(captcha, Id, write) of - [#captcha{pid=Pid, args=Args, key=StoredKey, tref=Tref}] -> - mnesia:delete({captcha, Id}), - erlang:cancel_timer(Tref), - if StoredKey == ProvidedKey -> - Pid ! {captcha_succeed, Args}, - captcha_valid; - true -> - Pid ! {captcha_failed, Args}, - captcha_non_valid - end; - _ -> - captcha_not_found - end). - + case string:tokens(Id, "-") of + [_, NodeID] -> + case ejabberd_cluster:get_node_by_id(NodeID) of + Node when Node == node() -> + do_check_captcha(Id, ProvidedKey); + Node -> + case catch rpc:call(Node, ?MODULE, check_captcha, + [Id, ProvidedKey], ?RPC_TIMEOUT) of + {'EXIT', _} -> + captcha_not_found; + {badrpc, _} -> + captcha_not_found; + Res -> + Res + end + end; + _ -> + captcha_not_found + end. process_reply({xmlelement, "captcha", _, _} = El) -> case xml:get_subtag(El, "x") of @@ -175,20 +168,14 @@ process_reply({xmlelement, "captcha", _, _} = El) -> case {proplists:get_value("challenge", Fields), proplists:get_value("ocr", Fields)} of {[Id|_], [OCR|_]} -> - ?T(case mnesia:read(captcha, Id, write) of - [#captcha{pid=Pid, args=Args, key=Key, tref=Tref}] -> - mnesia:delete({captcha, Id}), - erlang:cancel_timer(Tref), - if OCR == Key -> - Pid ! {captcha_succeed, Args}, - ok; - true -> - Pid ! {captcha_failed, Args}, - {error, bad_match} - end; - _ -> - {error, not_found} - end); + case check_captcha(Id, OCR) of + captcha_valid -> + ok; + captcha_non_valid -> + {error, bad_match}; + captcha_not_found -> + {error, not_found} + end; _ -> {error, malformed} end @@ -209,8 +196,8 @@ process(_Handlers, #request{method='GET', lang=Lang, path=[_, Id]}) -> end; process(_Handlers, #request{method='GET', path=[_, Id, "image"]}) -> - case mnesia:dirty_read(captcha, Id) of - [#captcha{key=Key}] -> + case lookup_captcha(Id) of + {ok, #captcha{key=Key}} -> case create_image(Key) of {ok, Type, _, Img} -> {200, @@ -249,10 +236,8 @@ process(_Handlers, _Request) -> %% gen_server callbacks %%==================================================================== init([]) -> - mnesia:create_table(captcha, - [{ram_copies, [node()]}, - {attributes, record_info(fields, captcha)}]), - mnesia:add_table_copy(captcha, node(), ram_copies), + mnesia:delete_table(captcha), + ets:new(captcha, [named_table, public, {keypos, #captcha.id}]), check_captcha_setup(), {ok, #state{}}. @@ -264,13 +249,13 @@ handle_cast(_Msg, State) -> handle_info({remove_id, Id}, State) -> ?DEBUG("captcha ~p timed out", [Id]), - _ = ?T(case mnesia:read(captcha, Id, write) of - [#captcha{args=Args, pid=Pid}] -> - Pid ! {captcha_failed, Args}, - mnesia:delete({captcha, Id}); - _ -> - ok - end), + case ets:lookup(captcha, Id) of + [#captcha{args=Args, pid=Pid}] -> + Pid ! {captcha_failed, Args}, + ets:delete(captcha, Id); + _ -> + ok + end, {noreply, State}; handle_info(_Info, State) -> @@ -414,3 +399,43 @@ check_captcha_setup() -> false -> ok end. + +lookup_captcha(Id) -> + case string:tokens(Id, "-") of + [_, NodeID] -> + case ejabberd_cluster:get_node_by_id(NodeID) of + Node when Node == node() -> + case ets:lookup(captcha, Id) of + [C] -> + {ok, C}; + _ -> + {error, enoent} + end; + Node -> + case catch rpc:call(Node, ets, lookup, + [captcha, Id], ?RPC_TIMEOUT) of + [C] -> + {ok, C}; + _ -> + {error, enoent} + end + end; + _ -> + {error, enoent} + end. + +do_check_captcha(Id, ProvidedKey) -> + case ets:lookup(captcha, Id) of + [#captcha{pid = Pid, args = Args, key = ValidKey, tref = Tref}] -> + ets:delete(captcha, Id), + erlang:cancel_timer(Tref), + if ValidKey == ProvidedKey -> + Pid ! {captcha_succeed, Args}, + captcha_valid; + true -> + Pid ! {captcha_failed, Args}, + captcha_non_valid + end; + _ -> + captcha_not_found + end. diff --git a/src/ejabberd_cluster.erl b/src/ejabberd_cluster.erl new file mode 100644 index 000000000..3db8dd29d --- /dev/null +++ b/src/ejabberd_cluster.erl @@ -0,0 +1,177 @@ +%%%------------------------------------------------------------------- +%%% File : ejabberd_cluster.erl +%%% Author : Evgeniy Khramtsov +%%% Description : +%%% +%%% Created : 2 Apr 2010 by Evgeniy Khramtsov +%%%------------------------------------------------------------------- +-module(ejabberd_cluster). + +-behaviour(gen_server). + +%% API +-export([start_link/0, get_node/1, get_node_new/1, announce/0, + node_id/0, get_node_by_id/1, get_nodes/0, rehash_timeout/0]). + +%% gen_server callbacks +-export([init/1, handle_call/3, handle_cast/2, handle_info/2, + terminate/2, code_change/3]). + +-include("ejabberd.hrl"). + +-define(HASHTBL, nodes_hash). +-define(HASHTBL_NEW, nodes_hash_new). +-define(POINTS, 16). +-define(REHASH_TIMEOUT, 5000). + +-record(state, {}). + +%%==================================================================== +%% API +%%==================================================================== +start_link() -> + gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). + +get_node(Key) -> + Hash = erlang:phash2(Key), + get_node_by_hash(?HASHTBL, Hash). + +get_node_new(Key) -> + Hash = erlang:phash2(Key), + get_node_by_hash(?HASHTBL_NEW, Hash). + +get_nodes() -> + %% TODO + mnesia:system_info(running_db_nodes). + +announce() -> + gen_server:call(?MODULE, announce, infinity). + +node_id() -> + integer_to_list(erlang:phash2(node())). + +rehash_timeout() -> + ?REHASH_TIMEOUT. + +get_node_by_id(NodeID) when is_list(NodeID) -> + case catch list_to_existing_atom(NodeID) of + {'EXIT', _} -> + node(); + Res -> + get_node_by_id(Res) + end; +get_node_by_id(NodeID) -> + case global:whereis_name(NodeID) of + Pid when is_pid(Pid) -> + node(Pid); + _ -> + node() + end. + +%%==================================================================== +%% gen_server callbacks +%%==================================================================== +init([]) -> + net_kernel:monitor_nodes(true, [{node_type, visible}]), + ets:new(?HASHTBL, [named_table, public, ordered_set]), + ets:new(?HASHTBL_NEW, [named_table, public, ordered_set]), + register_node(), + AllNodes = mnesia:system_info(running_db_nodes), + OtherNodes = case AllNodes of + [_] -> + AllNodes; + _ -> + AllNodes -- [node()] + end, + append_nodes(?HASHTBL, OtherNodes), + append_nodes(?HASHTBL_NEW, AllNodes), + {ok, #state{}}. + +handle_call(announce, _From, State) -> + case mnesia:system_info(running_db_nodes) of + [_MyNode] -> + ok; + Nodes -> + OtherNodes = Nodes -- [node()], + lists:foreach( + fun(Node) -> + {?MODULE, Node} ! {node_ready, node()} + end, OtherNodes), + ?INFO_MSG("waiting for migration from nodes: ~w", + [OtherNodes]), + timer:sleep(?REHASH_TIMEOUT), + append_node(?HASHTBL, node()) + end, + {reply, ok, State}; +handle_call(_Request, _From, State) -> + Reply = ok, + {reply, Reply, State}. + +handle_cast(_Msg, State) -> + {noreply, State}. + +handle_info({node_ready, Node}, State) -> + ?INFO_MSG("node ~p is ready, starting migration", [Node]), + append_node(?HASHTBL_NEW, Node), + ejabberd_hooks:run(node_hash_update, [?REHASH_TIMEOUT]), + timer:sleep(?REHASH_TIMEOUT), + ?INFO_MSG("adding node ~p to hash", [Node]), + append_node(?HASHTBL, Node), + {noreply, State}; +handle_info({nodedown, Node, _}, State) -> + ?INFO_MSG("node ~p goes down", [Node]), + delete_node(?HASHTBL, Node), + delete_node(?HASHTBL_NEW, Node), + {noreply, State}; +handle_info(_Info, State) -> + {noreply, State}. + +terminate(_Reason, _State) -> + ok. + +code_change(_OldVsn, State, _Extra) -> + {ok, State}. + +%%-------------------------------------------------------------------- +%% Internal functions +%%-------------------------------------------------------------------- +append_nodes(Tab, Nodes) -> + lists:foreach( + fun(Node) -> + append_node(Tab, Node) + end, Nodes). + +append_node(Tab, Node) -> + lists:foreach( + fun(I) -> + Hash = erlang:phash2({I, Node}), + ets:insert(Tab, {Hash, Node}) + end, lists:seq(1, ?POINTS)). + +delete_node(Tab, Node) -> + lists:foreach( + fun(I) -> + Hash = erlang:phash2({I, Node}), + ets:delete(Tab, Hash) + end, lists:seq(1, ?POINTS)). + +get_node_by_hash(Tab, Hash) -> + NodeHash = case ets:next(Tab, Hash) of + '$end_of_table' -> + ets:first(Tab); + NH -> + NH + end, + if NodeHash == '$end_of_table' -> + erlang:error(no_running_nodes); + true -> + case ets:lookup(Tab, NodeHash) of + [] -> + get_node_by_hash(Tab, Hash); + [{_, Node}] -> + Node + end + end. + +register_node() -> + global:register_name(list_to_atom(node_id()), self()). diff --git a/src/ejabberd_ctl.erl b/src/ejabberd_ctl.erl index aee1a011f..33b2fe4d0 100644 --- a/src/ejabberd_ctl.erl +++ b/src/ejabberd_ctl.erl @@ -201,8 +201,7 @@ process(Args) -> case String of [] -> ok; _ -> - io:format(String), - io:format("\n") + io:format("~s~n", [String]) end, Code. diff --git a/src/ejabberd_debug.erl b/src/ejabberd_debug.erl deleted file mode 100644 index f1baf1f78..000000000 --- a/src/ejabberd_debug.erl +++ /dev/null @@ -1,97 +0,0 @@ -%%%---------------------------------------------------------------------- -%%% File : ejabberd_debug.erl -%%% Author : Mickael Remond -%%% Purpose : ejabberd's application callback module -%%% Created : 6 may 2009 by Mickael Remond -%%% -%%% -%%% ejabberd, Copyright (C) 2002-2010 ProcessOne -%%% -%%% This program is free software; you can redistribute it and/or -%%% modify it under the terms of the GNU General Public License as -%%% published by the Free Software Foundation; either version 2 of the -%%% License, or (at your option) any later version. -%%% -%%% This program is distributed in the hope that it will be useful, -%%% but WITHOUT ANY WARRANTY; without even the implied warranty of -%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -%%% General Public License for more details. -%%% -%%% You should have received a copy of the GNU General Public License -%%% along with this program; if not, write to the Free Software -%%% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA -%%% 02111-1307 USA -%%% -%%%---------------------------------------------------------------------- - --module(ejabberd_debug). - --export([eprof_start/0, fprof_start/0, stop/0]). --export([pids/0]). - -eprof_start() -> - eprof:start(), - eprof:profile(pids()). - -fprof_start() -> - fprof:trace([start, {file, "/tmp/fprof"}, {procs, pids()}]). - -%% Stop all profilers -stop() -> - catch eprof:stop(), - catch fprof:stop(), - ok. - -pids() -> - lists:zf( - fun(Pid) -> - case process_info(Pid) of - ProcessInfo when is_list(ProcessInfo) -> - CurrentFunction = current_function(ProcessInfo), - InitialCall = initial_call(ProcessInfo), - RegisteredName = registered_name(ProcessInfo), - Ancestor = ancestor(ProcessInfo), - filter_pid(Pid, CurrentFunction, InitialCall, RegisteredName, Ancestor); - _ -> - false - end - end, - processes()). - -current_function(ProcessInfo) -> - {value, {_, {CurrentFunction, _,_}}} = - lists:keysearch(current_function, 1, ProcessInfo), - atom_to_list(CurrentFunction). - -initial_call(ProcessInfo) -> - {value, {_, {InitialCall, _,_}}} = - lists:keysearch(initial_call, 1, ProcessInfo), - atom_to_list(InitialCall). - -registered_name(ProcessInfo) -> - case lists:keysearch(registered_name, 1, ProcessInfo) of - {value, {_, Name}} when is_atom(Name) -> atom_to_list(Name); - _ -> "" - end. - -ancestor(ProcessInfo) -> - {value, {_, Dictionary}} = lists:keysearch(dictionary, 1, ProcessInfo), - case lists:keysearch('$ancestors', 1, Dictionary) of - {value, {_, [Ancestor|_T]}} when is_atom(Ancestor) -> - atom_to_list(Ancestor); - _ -> - "" - end. - -filter_pid(Pid, "ejabberd" ++ _, _InitialCall, _RegisteredName, _Ancestor) -> - {true, Pid}; -filter_pid(Pid, _CurrentFunction, "ejabberd" ++ _, _RegisteredName, _Ancestor) -> - {true, Pid}; -filter_pid(Pid, _CurrentFunction, _InitialCall, "ejabberd"++_, _Ancestor) -> - {true, Pid}; -filter_pid(Pid, _CurrentFunction, _InitialCall, "stringprep"++_, _Ancestor) -> - {true, Pid}; -filter_pid(Pid, _CurrentFunction, _InitialCall, _RegisteredName, "ejabberd"++_) -> - {true, Pid}; -filter_pid(_Pid, _CurrentFunction, _InitialCall, _RegisteredName, _Ancestor) -> - false. diff --git a/src/ejabberd_frontend_socket.erl b/src/ejabberd_frontend_socket.erl index 5ff4d08b4..88d77aed9 100644 --- a/src/ejabberd_frontend_socket.erl +++ b/src/ejabberd_frontend_socket.erl @@ -45,6 +45,8 @@ get_peer_certificate/1, get_verify_result/1, close/1, + setopts/2, + change_controller/2, sockname/1, peername/1]). %% gen_server callbacks @@ -94,18 +96,15 @@ start(Module, SockMod, Socket, Opts) -> todo end. -starttls(FsmRef, _TLSOpts) -> - %% TODO: Frontend improvements planned by Aleksey - %%gen_server:call(FsmRef, {starttls, TLSOpts}), - FsmRef. +starttls(FsmRef, TLSOpts) -> + starttls(FsmRef, TLSOpts, undefined). starttls(FsmRef, TLSOpts, Data) -> gen_server:call(FsmRef, {starttls, TLSOpts, Data}), FsmRef. compress(FsmRef) -> - gen_server:call(FsmRef, compress), - FsmRef. + compress(FsmRef, undefined). compress(FsmRef, Data) -> gen_server:call(FsmRef, {compress, Data}), @@ -138,11 +137,14 @@ close(FsmRef) -> sockname(FsmRef) -> gen_server:call(FsmRef, sockname). -peername(_FsmRef) -> - %% TODO: Frontend improvements planned by Aleksey - %%gen_server:call(FsmRef, peername). - {ok, {{0, 0, 0, 0}, 0}}. +setopts(FsmRef, Opts) -> + gen_server:call(FsmRef, {setopts, Opts}). +change_controller(FsmRef, C2SPid) -> + gen_server:call(FsmRef, {change_controller, C2SPid}). + +peername(FsmRef) -> + gen_server:call(FsmRef, peername). %%==================================================================== %% gen_server callbacks @@ -158,9 +160,16 @@ peername(_FsmRef) -> init([Module, SockMod, Socket, Opts, Receiver]) -> %% TODO: monitor the receiver Node = ejabberd_node_groups:get_closest_node(backend), + IP = case peername(SockMod, Socket) of + {ok, IP1} -> + IP1; + _ -> + undefined + end, {SockMod2, Socket2} = check_starttls(SockMod, Socket, Receiver, Opts), {ok, Pid} = - rpc:call(Node, Module, start, [{?MODULE, self()}, Opts]), + rpc:call(Node, Module, start, + [{?MODULE, self()}, [{frontend_ip, IP} | Opts]]), ejabberd_receiver:become_controller(Receiver, Pid), {ok, #state{sockmod = SockMod2, socket = Socket2, @@ -175,38 +184,16 @@ init([Module, SockMod, Socket, Opts, Receiver]) -> %% {stop, Reason, State} %% Description: Handling call messages %%-------------------------------------------------------------------- -handle_call({starttls, TLSOpts}, _From, State) -> - {ok, TLSSocket} = tls:tcp_to_tls(State#state.socket, TLSOpts), - ejabberd_receiver:starttls(State#state.receiver, TLSSocket), - Reply = ok, - {reply, Reply, State#state{socket = TLSSocket, sockmod = tls}, - ?HIBERNATE_TIMEOUT}; - handle_call({starttls, TLSOpts, Data}, _From, State) -> - {ok, TLSSocket} = tls:tcp_to_tls(State#state.socket, TLSOpts), - ejabberd_receiver:starttls(State#state.receiver, TLSSocket), - catch (State#state.sockmod):send( - State#state.socket, Data), + {ok, TLSSocket} = ejabberd_receiver:starttls( + State#state.receiver, TLSOpts, Data), Reply = ok, {reply, Reply, State#state{socket = TLSSocket, sockmod = tls}, ?HIBERNATE_TIMEOUT}; -handle_call(compress, _From, State) -> - {ok, ZlibSocket} = ejabberd_zlib:enable_zlib( - State#state.sockmod, - State#state.socket), - ejabberd_receiver:compress(State#state.receiver, ZlibSocket), - Reply = ok, - {reply, Reply, State#state{socket = ZlibSocket, sockmod = ejabberd_zlib}, - ?HIBERNATE_TIMEOUT}; - handle_call({compress, Data}, _From, State) -> - {ok, ZlibSocket} = ejabberd_zlib:enable_zlib( - State#state.sockmod, - State#state.socket), - ejabberd_receiver:compress(State#state.receiver, ZlibSocket), - catch (State#state.sockmod):send( - State#state.socket, Data), + {ok, ZlibSocket} = ejabberd_receiver:compress( + State#state.receiver, Data), Reply = ok, {reply, Reply, State#state{socket = ZlibSocket, sockmod = ejabberd_zlib}, ?HIBERNATE_TIMEOUT}; @@ -246,13 +233,7 @@ handle_call(close, _From, State) -> handle_call(sockname, _From, State) -> #state{sockmod = SockMod, socket = Socket} = State, - Reply = - case SockMod of - gen_tcp -> - inet:sockname(Socket); - _ -> - SockMod:sockname(Socket) - end, + Reply = peername(SockMod, Socket), {reply, Reply, State, ?HIBERNATE_TIMEOUT}; handle_call(peername, _From, State) -> @@ -266,6 +247,14 @@ handle_call(peername, _From, State) -> end, {reply, Reply, State, ?HIBERNATE_TIMEOUT}; +handle_call({setopts, Opts}, _From, State) -> + ejabberd_receiver:setopts(State#state.receiver, Opts), + {reply, ok, State, ?HIBERNATE_TIMEOUT}; + +handle_call({change_controller, Pid}, _From, State) -> + ejabberd_receiver:change_controller(State#state.receiver, Pid), + {reply, ok, State, ?HIBERNATE_TIMEOUT}; + handle_call(_Request, _From, State) -> Reply = ok, {reply, Reply, State, ?HIBERNATE_TIMEOUT}. @@ -318,10 +307,16 @@ check_starttls(SockMod, Socket, Receiver, Opts) -> end, Opts), if TLSEnabled -> - {ok, TLSSocket} = tls:tcp_to_tls(Socket, TLSOpts), - ejabberd_receiver:starttls(Receiver, TLSSocket), + {ok, TLSSocket} = ejabberd_receiver:starttls(Receiver, TLSOpts), {tls, TLSSocket}; true -> {SockMod, Socket} end. +peername(SockMod, Socket) -> + case SockMod of + gen_tcp -> + inet:peername(Socket); + _ -> + SockMod:peername(Socket) + end. diff --git a/src/ejabberd_local.erl b/src/ejabberd_local.erl index da1dadc0e..3c9f5d3da 100644 --- a/src/ejabberd_local.erl +++ b/src/ejabberd_local.erl @@ -125,7 +125,7 @@ route(From, To, Packet) -> route_iq(From, To, #iq{type = Type} = IQ, F) when is_function(F) -> Packet = if Type == set; Type == get -> - ID = randoms:get_string(), + ID = ejabberd_router:make_id(), Host = From#jid.lserver, register_iq_response_handler(Host, ID, undefined, F), jlib:iq_to_xml(IQ#iq{id = ID}); @@ -136,10 +136,10 @@ route_iq(From, To, #iq{type = Type} = IQ, F) when is_function(F) -> register_iq_response_handler(_Host, ID, Module, Function) -> TRef = erlang:start_timer(?IQ_TIMEOUT, ejabberd_local, ID), - mnesia:dirty_write(#iq_response{id = ID, - module = Module, - function = Function, - timer = TRef}). + ets:insert(iq_response, #iq_response{id = ID, + module = Module, + function = Function, + timer = TRef}). register_iq_handler(Host, XMLNS, Module, Fun) -> ejabberd_local ! {register_iq_handler, Host, XMLNS, Module, Fun}. @@ -181,11 +181,9 @@ init([]) -> ?MODULE, bounce_resource_packet, 100) end, ?MYHOSTS), catch ets:new(?IQTABLE, [named_table, public]), - update_table(), - mnesia:create_table(iq_response, - [{ram_copies, [node()]}, - {attributes, record_info(fields, iq_response)}]), - mnesia:add_table_copy(iq_response, node(), ram_copies), + mnesia:delete_table(iq_response), + catch ets:new(iq_response, [named_table, public, + {keypos, #iq_response.id}]), {ok, #state{}}. %%-------------------------------------------------------------------- @@ -257,7 +255,7 @@ handle_info(refresh_iq_handlers, State) -> end, ets:tab2list(?IQTABLE)), {noreply, State}; handle_info({timeout, _TRef, ID}, State) -> - process_iq_timeout(ID), + spawn(fun() -> process_iq_timeout(ID) end), {noreply, State}; handle_info(_Info, State) -> {noreply, State}. @@ -312,40 +310,22 @@ do_route(From, To, Packet) -> end end. -update_table() -> - case catch mnesia:table_info(iq_response, attributes) of - [id, module, function] -> - mnesia:delete_table(iq_response); - [id, module, function, timer] -> - ok; - {'EXIT', _} -> - ok - end. - get_iq_callback(ID) -> - case mnesia:dirty_read(iq_response, ID) of + case ets:lookup(iq_response, ID) of [#iq_response{module = Module, timer = TRef, function = Function}] -> cancel_timer(TRef), - mnesia:dirty_delete(iq_response, ID), + ets:delete(iq_response, ID), {ok, Module, Function}; _ -> error end. process_iq_timeout(ID) -> - spawn(fun process_iq_timeout/0) ! ID. - -process_iq_timeout() -> - receive - ID -> - case get_iq_callback(ID) of - {ok, undefined, Function} -> - Function(timeout); - _ -> - ok - end - after 5000 -> + case get_iq_callback(ID) of + {ok, undefined, Function} -> + Function(timeout); + _ -> ok end. diff --git a/src/ejabberd_node_groups.erl b/src/ejabberd_node_groups.erl index fc1b4ded5..055b96aef 100644 --- a/src/ejabberd_node_groups.erl +++ b/src/ejabberd_node_groups.erl @@ -31,6 +31,7 @@ %% API -export([start_link/0, + start/0, join/1, leave/1, get_members/1, @@ -40,7 +41,7 @@ -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). --record(state, {}). +-record(state, {groups = []}). %%==================================================================== %% API @@ -49,6 +50,15 @@ %% Function: start_link() -> {ok,Pid} | ignore | {error,Error} %% Description: Starts the server %%-------------------------------------------------------------------- +start() -> + ChildSpec = {?MODULE, + {?MODULE, start_link, []}, + permanent, + brutal_kill, + worker, + [?MODULE]}, + supervisor:start_child(ejabberd_sup, ChildSpec). + start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). @@ -81,30 +91,19 @@ get_closest_node(Name) -> %% Description: Initiates the server %%-------------------------------------------------------------------- init([]) -> - {FE, BE} = + Groups = case ejabberd_config:get_local_option(node_type) of frontend -> - {true, false}; + [frontend]; backend -> - {false, true}; + [backend]; generic -> - {true, true}; + [frontend, backend]; undefined -> - {true, true} + [frontend, backend] end, - if - FE -> - join(frontend); - true -> - ok - end, - if - BE -> - join(backend); - true -> - ok - end, - {ok, #state{}}. + lists:foreach(fun join/1, Groups), + {ok, #state{groups = Groups}}. %%-------------------------------------------------------------------- %% Function: %% handle_call(Request, From, State) -> {reply, Reply, State} | @@ -144,7 +143,8 @@ handle_info(_Info, State) -> %% cleaning up. When it returns, the gen_server terminates with Reason. %% The return value is ignored. %%-------------------------------------------------------------------- -terminate(_Reason, _State) -> +terminate(_Reason, #state{groups = Groups}) -> + lists:foreach(fun leave/1, Groups), ok. %%-------------------------------------------------------------------- diff --git a/src/ejabberd_receiver.erl b/src/ejabberd_receiver.erl index a3d0a8af8..eef82018a 100644 --- a/src/ejabberd_receiver.erl +++ b/src/ejabberd_receiver.erl @@ -36,8 +36,12 @@ change_shaper/2, reset_stream/1, starttls/2, + starttls/3, compress/2, + send/2, become_controller/2, + change_controller/2, + setopts/2, close/1]). %% gen_server callbacks @@ -52,6 +56,7 @@ c2s_pid, max_stanza_size, xml_stream_state, + tref, timeout}). -define(HIBERNATE_TIMEOUT, 90000). @@ -86,15 +91,32 @@ change_shaper(Pid, Shaper) -> reset_stream(Pid) -> gen_server:call(Pid, reset_stream). -starttls(Pid, TLSSocket) -> - gen_server:call(Pid, {starttls, TLSSocket}). +starttls(Pid, TLSOpts) -> + starttls(Pid, TLSOpts, undefined). -compress(Pid, ZlibSocket) -> - gen_server:call(Pid, {compress, ZlibSocket}). +starttls(Pid, TLSOpts, Data) -> + gen_server:call(Pid, {starttls, TLSOpts, Data}). + +compress(Pid, Data) -> + gen_server:call(Pid, {compress, Data}). become_controller(Pid, C2SPid) -> gen_server:call(Pid, {become_controller, C2SPid}). +change_controller(Pid, C2SPid) -> + gen_server:call(Pid, {change_controller, C2SPid}). + +setopts(Pid, Opts) -> + case lists:member({active, false}, Opts) of + true -> + gen_server:call(Pid, deactivate_socket); + false -> + ok + end. + +send(Pid, Data) -> + gen_server:call(Pid, {send, Data}). + close(Pid) -> gen_server:cast(Pid, close). @@ -132,10 +154,17 @@ init([Socket, SockMod, Shaper, MaxStanzaSize]) -> %% {stop, Reason, State} %% Description: Handling call messages %%-------------------------------------------------------------------- -handle_call({starttls, TLSSocket}, _From, +handle_call({starttls, TLSOpts, Data}, _From, #state{xml_stream_state = XMLStreamState, c2s_pid = C2SPid, + socket = Socket, max_stanza_size = MaxStanzaSize} = State) -> + {ok, TLSSocket} = tls:tcp_to_tls(Socket, TLSOpts), + if Data /= undefined -> + do_send(State, Data); + true -> + ok + end, close_stream(XMLStreamState), NewXMLStreamState = xml_stream:new(C2SPid, MaxStanzaSize), NewState = State#state{socket = TLSSocket, @@ -143,14 +172,23 @@ handle_call({starttls, TLSSocket}, _From, xml_stream_state = NewXMLStreamState}, case tls:recv_data(TLSSocket, "") of {ok, TLSData} -> - {reply, ok, process_data(TLSData, NewState), ?HIBERNATE_TIMEOUT}; + {reply, {ok, TLSSocket}, + process_data(TLSData, NewState), ?HIBERNATE_TIMEOUT}; {error, _Reason} -> {stop, normal, ok, NewState} end; -handle_call({compress, ZlibSocket}, _From, +handle_call({compress, Data}, _From, #state{xml_stream_state = XMLStreamState, c2s_pid = C2SPid, + socket = Socket, + sock_mod = SockMod, max_stanza_size = MaxStanzaSize} = State) -> + {ok, ZlibSocket} = ejabberd_zlib:enable_zlib(SockMod, Socket), + if Data /= undefined -> + do_send(State, Data); + true -> + ok + end, close_stream(XMLStreamState), NewXMLStreamState = xml_stream:new(C2SPid, MaxStanzaSize), NewState = State#state{socket = ZlibSocket, @@ -158,7 +196,8 @@ handle_call({compress, ZlibSocket}, _From, xml_stream_state = NewXMLStreamState}, case ejabberd_zlib:recv_data(ZlibSocket, "") of {ok, ZlibData} -> - {reply, ok, process_data(ZlibData, NewState), ?HIBERNATE_TIMEOUT}; + {reply, {ok, ZlibSocket}, + process_data(ZlibData, NewState), ?HIBERNATE_TIMEOUT}; {error, _Reason} -> {stop, normal, ok, NewState} end; @@ -172,12 +211,31 @@ handle_call(reset_stream, _From, {reply, Reply, State#state{xml_stream_state = NewXMLStreamState}, ?HIBERNATE_TIMEOUT}; handle_call({become_controller, C2SPid}, _From, State) -> + erlang:monitor(process, C2SPid), XMLStreamState = xml_stream:new(C2SPid, State#state.max_stanza_size), NewState = State#state{c2s_pid = C2SPid, xml_stream_state = XMLStreamState}, activate_socket(NewState), Reply = ok, {reply, Reply, NewState, ?HIBERNATE_TIMEOUT}; +handle_call({change_controller, C2SPid}, _From, State) -> + erlang:monitor(process, C2SPid), + NewXMLStreamState = xml_stream:change_callback_pid( + State#state.xml_stream_state, C2SPid), + NewState = State#state{c2s_pid = C2SPid, + xml_stream_state = NewXMLStreamState}, + activate_socket(NewState), + {reply, ok, NewState, ?HIBERNATE_TIMEOUT}; +handle_call({send, Data}, _From, State) -> + case do_send(State, Data) of + ok -> + {reply, ok, State, ?HIBERNATE_TIMEOUT}; + {error, _Reason} = Err -> + {stop, normal, Err, State} + end; +handle_call(deactivate_socket, _From, State) -> + deactivate_socket(State), + {reply, ok, State, ?HIBERNATE_TIMEOUT}; handle_call(_Request, _From, State) -> Reply = ok, {reply, Reply, State, ?HIBERNATE_TIMEOUT}. @@ -237,6 +295,9 @@ handle_info({Tag, _TCPSocket, Reason}, State) _ -> {stop, normal, State} end; +handle_info({'DOWN', _MRef, process, C2SPid, _}, + #state{c2s_pid = C2SPid} = State) -> + {stop, normal, State}; handle_info({timeout, _Ref, activate}, State) -> activate_socket(State), {noreply, State, ?HIBERNATE_TIMEOUT}; @@ -294,6 +355,17 @@ activate_socket(#state{socket = Socket, ok end. +deactivate_socket(#state{socket = Socket, + tref = TRef, + sock_mod = SockMod}) -> + cancel_timer(TRef), + case SockMod of + gen_tcp -> + inet:setopts(Socket, [{active, false}]); + _ -> + SockMod:setopts(Socket, [{active, false}]) + end. + %% Data processing for connectors directly generating xmlelement in %% Erlang data structure. %% WARNING: Shaper does not work with Erlang data structure. @@ -315,20 +387,23 @@ process_data([Element|Els], #state{c2s_pid = C2SPid} = State) %% Data processing for connectors receivind data as string. process_data(Data, #state{xml_stream_state = XMLStreamState, + tref = TRef, shaper_state = ShaperState, c2s_pid = C2SPid} = State) -> ?DEBUG("Received XML on stream = ~p", [binary_to_list(Data)]), XMLStreamState1 = xml_stream:parse(XMLStreamState, Data), {NewShaperState, Pause} = shaper:update(ShaperState, size(Data)), - if - C2SPid == undefined -> - ok; - Pause > 0 -> - erlang:start_timer(Pause, self(), activate); - true -> - activate_socket(State) - end, + NewTRef = if + C2SPid == undefined -> + TRef; + Pause > 0 -> + erlang:start_timer(Pause, self(), activate); + true -> + activate_socket(State), + TRef + end, State#state{xml_stream_state = XMLStreamState1, + tref = NewTRef, shaper_state = NewShaperState}. %% Element coming from XML parser are wrapped inside xmlstreamelement @@ -345,3 +420,21 @@ close_stream(undefined) -> ok; close_stream(XMLStreamState) -> xml_stream:close(XMLStreamState). + +do_send(State, Data) -> + (State#state.sock_mod):send(State#state.socket, Data). + +cancel_timer(TRef) when is_reference(TRef) -> + case erlang:cancel_timer(TRef) of + false -> + receive + {timeout, TRef, _} -> + ok + after 0 -> + ok + end; + _ -> + ok + end; +cancel_timer(_) -> + ok. diff --git a/src/ejabberd_router.erl b/src/ejabberd_router.erl index 87ba99094..ba4072cfa 100644 --- a/src/ejabberd_router.erl +++ b/src/ejabberd_router.erl @@ -38,7 +38,8 @@ unregister_route/1, unregister_routes/1, dirty_get_all_routes/0, - dirty_get_all_domains/0 + dirty_get_all_domains/0, + make_id/0 ]). -export([start_link/0]). @@ -53,6 +54,9 @@ -record(route, {domain, pid, local_hint}). -record(state, {}). +%% "rr" stands for Record-Route. +-define(ROUTE_PREFIX, "rr-"). + %%==================================================================== %% API %%==================================================================== @@ -65,7 +69,7 @@ start_link() -> route(From, To, Packet) -> - case catch do_route(From, To, Packet) of + case catch route_check_id(From, To, Packet) of {'EXIT', Reason} -> ?ERROR_MSG("~p~nwhen processing: ~p", [Reason, {From, To, Packet}]); @@ -192,6 +196,8 @@ dirty_get_all_routes() -> dirty_get_all_domains() -> lists:usort(mnesia:dirty_all_keys(route)). +make_id() -> + ?ROUTE_PREFIX ++ randoms:get_string() ++ "-" ++ ejabberd_cluster:node_id(). %%==================================================================== %% gen_server callbacks @@ -309,6 +315,32 @@ code_change(_OldVsn, State, _Extra) -> %%-------------------------------------------------------------------- %%% Internal functions %%-------------------------------------------------------------------- +route_check_id(From, To, {xmlelement, "iq", Attrs, _} = Packet) -> + case xml:get_attr_s("id", Attrs) of + ?ROUTE_PREFIX ++ Rest -> + Type = xml:get_attr_s("type", Attrs), + if Type == "error"; Type == "result" -> + case string:tokens(Rest, "-") of + [_, NodeID] -> + case ejabberd_cluster:get_node_by_id(NodeID) of + Node when Node == node() -> + do_route(From, To, Packet); + Node -> + {ejabberd_router, Node} ! + {route, From, To, Packet} + end; + _ -> + do_route(From, To, Packet) + end; + true -> + do_route(From, To, Packet) + end; + _ -> + do_route(From, To, Packet) + end; +route_check_id(From, To, Packet) -> + do_route(From, To, Packet). + do_route(OrigFrom, OrigTo, OrigPacket) -> ?DEBUG("route~n\tfrom ~p~n\tto ~p~n\tpacket ~p~n", [OrigFrom, OrigTo, OrigPacket]), @@ -413,4 +445,3 @@ update_tables() -> false -> ok end. - diff --git a/src/ejabberd_s2s.erl b/src/ejabberd_s2s.erl index 8ab520f56..3e5807eee 100644 --- a/src/ejabberd_s2s.erl +++ b/src/ejabberd_s2s.erl @@ -40,7 +40,8 @@ dirty_get_connections/0, allow_host/2, incoming_s2s_number/0, - outgoing_s2s_number/0 + outgoing_s2s_number/0, + migrate/1 ]). %% gen_server callbacks @@ -94,30 +95,63 @@ remove_connection(FromTo, Pid, Key) -> end. have_connection(FromTo) -> - case catch mnesia:dirty_read(s2s, FromTo) of - [_] -> - true; - _ -> - false + case ejabberd_cluster:get_node(FromTo) of + Node when Node == node() -> + case mnesia:dirty_read(s2s, FromTo) of + [_] -> + true; + _ -> + false + end; + Node -> + case catch rpc:call(Node, mnesia, dirty_read, + [s2s, FromTo], 5000) of + [_] -> + true; + _ -> + false + end end. has_key(FromTo, Key) -> - case mnesia:dirty_select(s2s, - [{#s2s{fromto = FromTo, key = Key, _ = '_'}, - [], - ['$_']}]) of - [] -> - false; - _ -> - true + Query = [{#s2s{fromto = FromTo, key = Key, _ = '_'}, + [], + ['$_']}], + case ejabberd_cluster:get_node(FromTo) of + Node when Node == node() -> + case mnesia:dirty_select(s2s, Query) of + [] -> + false; + _ -> + true + end; + Node -> + case catch rpc:call(Node, mnesia, dirty_select, + [s2s, Query], 5000) of + [_|_] -> + true; + _ -> + false + end end. get_connections_pids(FromTo) -> - case catch mnesia:dirty_read(s2s, FromTo) of - L when is_list(L) -> - [Connection#s2s.pid || Connection <- L]; - _ -> - [] + case ejabberd_cluster:get_node(FromTo) of + Node when Node == node() -> + case catch mnesia:dirty_read(s2s, FromTo) of + L when is_list(L) -> + [Connection#s2s.pid || Connection <- L]; + _ -> + [] + end; + Node -> + case catch rpc:call(Node, mnesia, dirty_read, + [s2s, FromTo], 5000) of + L when is_list(L) -> + [Connection#s2s.pid || Connection <- L]; + _ -> + [] + end end. try_register(FromTo) -> @@ -148,7 +182,33 @@ try_register(FromTo) -> end. dirty_get_connections() -> - mnesia:dirty_all_keys(s2s). + lists:flatmap( + fun(Node) when Node == node() -> + mnesia:dirty_all_keys(s2s); + (Node) -> + case catch rpc:call(Node, mnesia, dirty_all_keys, [s2s], 5000) of + L when is_list(L) -> + L; + _ -> + [] + end + end, ejabberd_cluster:get_nodes()). + +migrate(After) -> + Ss = mnesia:dirty_select( + s2s, + [{#s2s{fromto = '$1', pid = '$2', _ = '_'}, + [], + ['$$']}]), + lists:foreach( + fun([FromTo, Pid]) -> + case ejabberd_cluster:get_node_new(FromTo) of + Node when Node /= node() -> + ejabberd_s2s_out:stop_connection(Pid, After * 2); + _ -> + ok + end + end, Ss). %%==================================================================== %% gen_server callbacks @@ -163,10 +223,11 @@ dirty_get_connections() -> %%-------------------------------------------------------------------- init([]) -> update_tables(), - mnesia:create_table(s2s, [{ram_copies, [node()]}, {type, bag}, + mnesia:create_table(s2s, [{ram_copies, [node()]}, + {type, bag}, {local_content, true}, {attributes, record_info(fields, s2s)}]), mnesia:add_table_copy(s2s, node(), ram_copies), - mnesia:subscribe(system), + ejabberd_hooks:add(node_hash_update, ?MODULE, migrate, 100), ejabberd_commands:register_commands(commands()), {ok, #state{}}. @@ -198,9 +259,6 @@ handle_cast(_Msg, State) -> %% {stop, Reason, State} %% Description: Handling all non call/cast messages %%-------------------------------------------------------------------- -handle_info({mnesia_system_event, {mnesia_down, Node}}, State) -> - clean_table_from_bad_node(Node), - {noreply, State}; handle_info({route, From, To, Packet}, State) -> case catch do_route(From, To, Packet) of {'EXIT', Reason} -> @@ -221,6 +279,7 @@ handle_info(_Info, State) -> %% The return value is ignored. %%-------------------------------------------------------------------- terminate(_Reason, _State) -> + ejabberd_hooks:delete(node_hash_update, ?MODULE, migrate, 100), ejabberd_commands:unregister_commands(commands()), ok. @@ -234,22 +293,18 @@ code_change(_OldVsn, State, _Extra) -> %%-------------------------------------------------------------------- %%% Internal functions %%-------------------------------------------------------------------- -clean_table_from_bad_node(Node) -> - F = fun() -> - Es = mnesia:select( - s2s, - [{#s2s{pid = '$1', _ = '_'}, - [{'==', {node, '$1'}, Node}], - ['$_']}]), - lists:foreach(fun(E) -> - mnesia:delete_object(E) - end, Es) - end, - mnesia:async_dirty(F). - do_route(From, To, Packet) -> ?DEBUG("s2s manager~n\tfrom ~p~n\tto ~p~n\tpacket ~P~n", [From, To, Packet, 8]), + FromTo = {From#jid.lserver, To#jid.lserver}, + case ejabberd_cluster:get_node(FromTo) of + Node when Node == node() -> + do_route1(From, To, Packet); + Node -> + {?MODULE, Node} ! {route, From, To, Packet} + end. + +do_route1(From, To, Packet) -> case find_connection(From, To) of {atomic, Pid} when is_pid(Pid) -> ?DEBUG("sending to process ~p~n", [Pid]), @@ -482,6 +537,12 @@ update_tables() -> mnesia:delete_table(local_s2s); false -> ok + end, + case catch mnesia:table_info(s2s, local_content) of + false -> + mnesia:delete_table(s2s); + _ -> + ok end. %% Check if host is in blacklist or white list diff --git a/src/ejabberd_s2s_in.erl b/src/ejabberd_s2s_in.erl index 9b378338c..56086c9ef 100644 --- a/src/ejabberd_s2s_in.erl +++ b/src/ejabberd_s2s_in.erl @@ -48,6 +48,11 @@ -include("ejabberd.hrl"). -include("jlib.hrl"). +-ifdef(SSL40). +-include_lib("public_key/include/public_key.hrl"). +-define(PKIXEXPLICIT, 'OTP-PUB-KEY'). +-define(PKIXIMPLICIT, 'OTP-PUB-KEY'). +-else. -ifdef(SSL39). -include_lib("ssl/include/ssl_pkix.hrl"). -define(PKIXEXPLICIT, 'OTP-PKIX'). @@ -58,6 +63,7 @@ -define(PKIXEXPLICIT, 'PKIX1Explicit88'). -define(PKIXIMPLICIT, 'PKIX1Implicit88'). -endif. +-endif. -include("XmppAddr.hrl"). -define(DICT, dict). @@ -263,7 +269,7 @@ wait_for_feature_request({xmlstreamelement, El}, StateData) -> TLSOpts = StateData#state.tls_options, TLSSocket = (StateData#state.sockmod):starttls( Socket, TLSOpts, - xml:element_to_string( + xml:element_to_binary( {xmlelement, "proceed", [{"xmlns", ?NS_TLS}], []})), {next_state, wait_for_stream, StateData#state{socket = TLSSocket, @@ -618,7 +624,7 @@ send_text(StateData, Text) -> (StateData#state.sockmod):send(StateData#state.socket, Text). send_element(StateData, El) -> - send_text(StateData, xml:element_to_string(El)). + send_text(StateData, xml:element_to_binary(El)). change_shaper(StateData, Host, JID) -> diff --git a/src/ejabberd_s2s_out.erl b/src/ejabberd_s2s_out.erl index 69cbfdd22..28eb4f1ae 100644 --- a/src/ejabberd_s2s_out.erl +++ b/src/ejabberd_s2s_out.erl @@ -34,7 +34,8 @@ start_link/3, start_connection/1, terminate_if_waiting_delay/2, - stop_connection/1]). + stop_connection/1, + stop_connection/2]). %% p1_fsm callbacks (same as gen_fsm) -export([init/1, @@ -54,6 +55,7 @@ print_state/1, code_change/4, test_get_addr_port/1, + print_state/1, get_addr_port/1]). -include("ejabberd.hrl"). @@ -84,10 +86,11 @@ %% Module start with or without supervisor: -ifdef(NO_TRANSIENT_SUPERVISORS). --define(SUPERVISOR_START, p1_fsm:start(ejabberd_s2s_out, [From, Host, Type], - fsm_limit_opts() ++ ?FSMOPTS)). +-define(SUPERVISOR_START, rpc:call(Node, p1_fsm, start, + [ejabberd_s2s_out, [From, Host, Type], + fsm_limit_opts() ++ ?FSMOPTS])). -else. --define(SUPERVISOR_START, supervisor:start_child(ejabberd_s2s_out_sup, +-define(SUPERVISOR_START, supervisor:start_child({ejabberd_s2s_out_sup, Node}, [From, Host, Type])). -endif. @@ -126,6 +129,7 @@ %%% API %%%---------------------------------------------------------------------- start(From, Host, Type) -> + Node = ejabberd_cluster:get_node({From, Host}), ?SUPERVISOR_START. start_link(From, Host, Type) -> @@ -136,7 +140,10 @@ start_connection(Pid) -> p1_fsm:send_event(Pid, init). stop_connection(Pid) -> - p1_fsm:send_event(Pid, stop). + p1_fsm:send_event(Pid, closed). + +stop_connection(Pid, Timeout) -> + p1_fsm:send_all_state_event(Pid, {closed, Timeout}). %%%---------------------------------------------------------------------- %%% Callback functions from p1_fsm @@ -746,9 +753,15 @@ stream_established(closed, StateData) -> %% {next_state, NextStateName, NextStateData, Timeout} | %% {stop, Reason, NewStateData} %%---------------------------------------------------------------------- +handle_event({closed, Timeout}, StateName, StateData) -> + p1_fsm:send_event_after(Timeout, closed), + {next_state, StateName, StateData}; handle_event(_Event, StateName, StateData) -> {next_state, StateName, StateData, get_timeout_interval(StateName)}. +print_state(StateData) -> + StateData. + %%---------------------------------------------------------------------- %% Func: handle_sync_event/4 %% Returns: The associated StateData for this connection @@ -892,7 +905,7 @@ send_text(StateData, Text) -> ejabberd_socket:send(StateData#state.socket, Text). send_element(StateData, El) -> - send_text(StateData, xml:element_to_string(El)). + send_text(StateData, xml:element_to_binary(El)). send_queue(StateData, Q) -> case queue:out(Q) of diff --git a/src/ejabberd_service.erl b/src/ejabberd_service.erl index 44bca0b9e..bd07bfea8 100644 --- a/src/ejabberd_service.erl +++ b/src/ejabberd_service.erl @@ -347,7 +347,7 @@ handle_info({route, From, To, Packet}, StateName, StateData) -> Attrs2 = jlib:replace_from_to_attrs(jlib:jid_to_string(From), jlib:jid_to_string(To), Attrs), - Text = xml:element_to_string({xmlelement, Name, Attrs2, Els}), + Text = xml:element_to_binary({xmlelement, Name, Attrs2, Els}), send_text(StateData, Text); deny -> Err = jlib:make_error_reply(Packet, ?ERR_NOT_ALLOWED), @@ -391,7 +391,7 @@ send_text(StateData, Text) -> (StateData#state.sockmod):send(StateData#state.socket, Text). send_element(StateData, El) -> - send_text(StateData, xml:element_to_string(El)). + send_text(StateData, xml:element_to_binary(El)). new_id() -> randoms:get_string(). diff --git a/src/ejabberd_sm.erl b/src/ejabberd_sm.erl index 4fc8123e7..fc7d8802d 100644 --- a/src/ejabberd_sm.erl +++ b/src/ejabberd_sm.erl @@ -32,7 +32,10 @@ %% API -export([start_link/0, route/3, - open_session/5, close_session/4, + set_session/6, + open_session/5, + open_session/6, + close_session/4, check_in_subscription/6, bounce_offline_message/3, disconnect_removed_user/2, @@ -43,6 +46,7 @@ dirty_get_sessions_list/0, dirty_get_my_sessions_list/0, get_vh_session_list/1, + get_vh_my_session_list/1, get_vh_session_number/1, register_iq_handler/4, register_iq_handler/5, @@ -53,7 +57,8 @@ user_resources/2, get_session_pid/3, get_user_info/3, - get_user_ip/3 + get_user_ip/3, + migrate/1 ]). %% gen_server callbacks @@ -66,7 +71,6 @@ -include("mod_privacy.hrl"). -record(session, {sid, usr, us, priority, info}). --record(session_counter, {vhost, count}). -record(state, {}). %% default value for the maximum number of user connections @@ -92,9 +96,10 @@ route(From, To, Packet) -> end. open_session(SID, User, Server, Resource, Info) -> - set_session(SID, User, Server, Resource, undefined, Info), - mnesia:dirty_update_counter(session_counter, - jlib:nameprep(Server), 1), + open_session(SID, User, Server, Resource, undefined, Info). + +open_session(SID, User, Server, Resource, Priority, Info) -> + set_session(SID, User, Server, Resource, Priority, Info), check_for_sessions_to_replace(User, Server, Resource), JID = jlib:make_jid(User, Server, Resource), ejabberd_hooks:run(sm_register_connection_hook, JID#jid.lserver, @@ -106,9 +111,7 @@ close_session(SID, User, Server, Resource) -> [#session{info=I}] -> I end, F = fun() -> - mnesia:delete({session, SID}), - mnesia:dirty_update_counter(session_counter, - jlib:nameprep(Server), -1) + mnesia:delete({session, SID}) end, mnesia:sync_dirty(F), JID = jlib:make_jid(User, Server, Resource), @@ -138,11 +141,17 @@ get_user_resources(User, Server) -> LUser = jlib:nodeprep(User), LServer = jlib:nameprep(Server), US = {LUser, LServer}, - case catch mnesia:dirty_index_read(session, US, #session.us) of - {'EXIT', _Reason} -> - []; - Ss -> - [element(3, S#session.usr) || S <- clean_session_list(Ss)] + Ss = case ejabberd_cluster:get_node({LUser, LServer}) of + Node when Node == node() -> + catch mnesia:dirty_index_read(session, US, #session.us); + Node -> + catch rpc:call(Node, mnesia, dirty_index_read, + [session, US, #session.us], 5000) + end, + if is_list(Ss) -> + [element(3, S#session.usr) || S <- clean_session_list(Ss)]; + true -> + [] end. get_user_ip(User, Server, Resource) -> @@ -150,12 +159,18 @@ get_user_ip(User, Server, Resource) -> LServer = jlib:nameprep(Server), LResource = jlib:resourceprep(Resource), USR = {LUser, LServer, LResource}, - case mnesia:dirty_index_read(session, USR, #session.usr) of - [] -> - undefined; - Ss -> + Ss = case ejabberd_cluster:get_node({LUser, LServer}) of + Node when Node == node() -> + mnesia:dirty_index_read(session, USR, #session.usr); + Node -> + catch rpc:call(Node, mnesia, dirty_index_read, + [session, USR, #session.usr], 5000) + end, + if is_list(Ss), Ss /= [] -> Session = lists:max(Ss), - proplists:get_value(ip, Session#session.info) + proplists:get_value(ip, Session#session.info); + true -> + undefined end. get_user_info(User, Server, Resource) -> @@ -163,15 +178,21 @@ get_user_info(User, Server, Resource) -> LServer = jlib:nameprep(Server), LResource = jlib:resourceprep(Resource), USR = {LUser, LServer, LResource}, - case mnesia:dirty_index_read(session, USR, #session.usr) of - [] -> - offline; - Ss -> + Ss = case ejabberd_cluster:get_node({LUser, LServer}) of + Node when Node == node() -> + mnesia:dirty_index_read(session, USR, #session.usr); + Node -> + catch rpc:call(Node, mnesia, dirty_index_read, + [session, USR, #session.usr], 5000) + end, + if is_list(Ss), Ss /= [] -> Session = lists:max(Ss), - Node = node(element(2, Session#session.sid)), + N = node(element(2, Session#session.sid)), Conn = proplists:get_value(conn, Session#session.info), IP = proplists:get_value(ip, Session#session.info), - [{node, Node}, {conn, Conn}, {ip, IP}] + [{node, N}, {conn, Conn}, {ip, IP}]; + true -> + offline end. set_presence(SID, User, Server, Resource, Priority, Presence, Info) -> @@ -194,26 +215,37 @@ get_session_pid(User, Server, Resource) -> LServer = jlib:nameprep(Server), LResource = jlib:resourceprep(Resource), USR = {LUser, LServer, LResource}, - case catch mnesia:dirty_index_read(session, USR, #session.usr) of + Res = case ejabberd_cluster:get_node({LUser, LServer}) of + Node when Node == node() -> + mnesia:dirty_index_read(session, USR, #session.usr); + Node -> + catch rpc:call(Node, mnesia, dirty_index_read, + [session, USR, #session.usr], 5000) + end, + case Res of [#session{sid = {_, Pid}}] -> Pid; _ -> none end. dirty_get_sessions_list() -> - mnesia:dirty_select( - session, - [{#session{usr = '$1', _ = '_'}, - [], - ['$1']}]). + Match = [{#session{usr = '$1', _ = '_'}, [], ['$1']}], + lists:flatmap( + fun(Node) when Node == node() -> + mnesia:dirty_select(session, Match); + (Node) -> + case catch rpc:call(Node, mnesia, dirty_select, + [session, Match], 5000) of + Ss when is_list(Ss) -> + Ss; + _ -> + [] + end + end, ejabberd_cluster:get_nodes()). dirty_get_my_sessions_list() -> - mnesia:dirty_select( - session, - [{#session{sid = {'_', '$1'}, _ = '_'}, - [{'==', {node, '$1'}, node()}], - ['$_']}]). + mnesia:dirty_match_object(#session{_ = '_'}). -get_vh_session_list(Server) -> +get_vh_my_session_list(Server) -> LServer = jlib:nameprep(Server), mnesia:dirty_select( session, @@ -221,19 +253,24 @@ get_vh_session_list(Server) -> [{'==', {element, 2, '$1'}, LServer}], ['$1']}]). +get_vh_session_list(Server) -> + lists:flatmap( + fun(Node) when Node == node() -> + get_vh_my_session_list(Server); + (Node) -> + case catch rpc:call(Node, ?MODULE, get_vh_my_session_list, + [Server], 5000) of + Ss when is_list(Ss) -> + Ss; + _ -> + [] + end + end, ejabberd_cluster:get_nodes()). + get_vh_session_number(Server) -> - LServer = jlib:nameprep(Server), - Query = mnesia:dirty_select( - session_counter, - [{#session_counter{vhost = LServer, count = '$1'}, - [], - ['$1']}]), - case Query of - [Count] -> - Count; - _ -> 0 - end. - + %% TODO + length(get_vh_session_list(Server)). + register_iq_handler(Host, XMLNS, Module, Fun) -> ejabberd_sm ! {register_iq_handler, Host, XMLNS, Module, Fun}. @@ -243,6 +280,21 @@ register_iq_handler(Host, XMLNS, Module, Fun, Opts) -> unregister_iq_handler(Host, XMLNS) -> ejabberd_sm ! {unregister_iq_handler, Host, XMLNS}. +migrate(After) -> + Ss = mnesia:dirty_select( + session, + [{#session{us = '$1', sid = {'_', '$2'}, _ = '_'}, + [], + ['$$']}]), + lists:foreach( + fun([US, Pid]) -> + case ejabberd_cluster:get_node_new(US) of + Node when Node /= node() -> + ejabberd_c2s:migrate(Pid, Node, After); + _ -> + ok + end + end, Ss). %%==================================================================== %% gen_server callbacks @@ -259,16 +311,13 @@ init([]) -> update_tables(), mnesia:create_table(session, [{ram_copies, [node()]}, + {local_content, true}, {attributes, record_info(fields, session)}]), - mnesia:create_table(session_counter, - [{ram_copies, [node()]}, - {attributes, record_info(fields, session_counter)}]), mnesia:add_table_index(session, usr), mnesia:add_table_index(session, us), mnesia:add_table_copy(session, node(), ram_copies), - mnesia:add_table_copy(session_counter, node(), ram_copies), - mnesia:subscribe(system), ets:new(sm_iqtable, [named_table]), + ejabberd_hooks:add(node_hash_update, ?MODULE, migrate, 100), lists:foreach( fun(Host) -> ejabberd_hooks:add(roster_in_subscription, Host, @@ -319,9 +368,6 @@ handle_info({route, From, To, Packet}, State) -> ok end, {noreply, State}; -handle_info({mnesia_system_event, {mnesia_down, Node}}, State) -> - recount_session_table(Node), - {noreply, State}; handle_info({register_iq_handler, Host, XMLNS, Module, Function}, State) -> ets:insert(sm_iqtable, {{XMLNS, Host}, Module, Function}), {noreply, State}; @@ -348,6 +394,7 @@ handle_info(_Info, State) -> %% The return value is ignored. %%-------------------------------------------------------------------- terminate(_Reason, _State) -> + ejabberd_hooks:delete(node_hash_update, ?MODULE, migrate, 100), ejabberd_commands:unregister_commands(commands()), ok. @@ -377,38 +424,20 @@ set_session(SID, User, Server, Resource, Priority, Info) -> end, mnesia:sync_dirty(F). -%% Recalculates alive sessions when Node goes down -%% and updates session and session_counter tables -recount_session_table(Node) -> - F = fun() -> - Es = mnesia:select( - session, - [{#session{sid = {'_', '$1'}, _ = '_'}, - [{'==', {node, '$1'}, Node}], - ['$_']}]), - lists:foreach(fun(E) -> - mnesia:delete({session, E#session.sid}) - end, Es), - %% reset session_counter table with active sessions - mnesia:clear_table(session_counter), - lists:foreach(fun(Server) -> - LServer = jlib:nameprep(Server), - Hs = mnesia:select(session, - [{#session{usr = '$1', _ = '_'}, - [{'==', {element, 2, '$1'}, LServer}], - ['$1']}]), - mnesia:write( - #session_counter{vhost = LServer, - count = length(Hs)}) - end, ?MYHOSTS) - end, - mnesia:async_dirty(F). - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% do_route(From, To, Packet) -> ?DEBUG("session manager~n\tfrom ~p~n\tto ~p~n\tpacket ~P~n", [From, To, Packet, 8]), + {U, S, _} = jlib:jid_tolower(To), + case ejabberd_cluster:get_node({U, S}) of + Node when Node /= node() -> + {?MODULE, Node} ! {route, From, To, Packet}; + _ -> + do_route1(From, To, Packet) + end. + +do_route1(From, To, Packet) -> #jid{user = User, server = Server, luser = LUser, lserver = LServer, lresource = LResource} = To, {xmlelement, Name, Attrs, _Els} = Packet, @@ -795,4 +824,11 @@ update_tables() -> mnesia:delete_table(local_session); false -> ok + end, + mnesia:delete_table(session_counter), + case catch mnesia:table_info(session, local_content) of + false -> + mnesia:delete_table(session); + _ -> + ok end. diff --git a/src/ejabberd_socket.erl b/src/ejabberd_socket.erl index 25ff64c27..a6cf0d0fe 100644 --- a/src/ejabberd_socket.erl +++ b/src/ejabberd_socket.erl @@ -44,6 +44,7 @@ get_peer_certificate/1, get_verify_result/1, close/1, + change_controller/2, sockname/1, peername/1]). -include("ejabberd.hrl"). @@ -129,29 +130,19 @@ connect(Addr, Port, Opts, Timeout) -> end. starttls(SocketData, TLSOpts) -> - {ok, TLSSocket} = tls:tcp_to_tls(SocketData#socket_state.socket, TLSOpts), - ejabberd_receiver:starttls(SocketData#socket_state.receiver, TLSSocket), - SocketData#socket_state{socket = TLSSocket, sockmod = tls}. + starttls(SocketData, TLSOpts, undefined). starttls(SocketData, TLSOpts, Data) -> - {ok, TLSSocket} = tls:tcp_to_tls(SocketData#socket_state.socket, TLSOpts), - ejabberd_receiver:starttls(SocketData#socket_state.receiver, TLSSocket), - send(SocketData, Data), + {ok, TLSSocket} = ejabberd_receiver:starttls( + SocketData#socket_state.receiver, TLSOpts, Data), SocketData#socket_state{socket = TLSSocket, sockmod = tls}. compress(SocketData) -> - {ok, ZlibSocket} = ejabberd_zlib:enable_zlib( - SocketData#socket_state.sockmod, - SocketData#socket_state.socket), - ejabberd_receiver:compress(SocketData#socket_state.receiver, ZlibSocket), - SocketData#socket_state{socket = ZlibSocket, sockmod = ejabberd_zlib}. + compress(SocketData, undefined). compress(SocketData, Data) -> - {ok, ZlibSocket} = ejabberd_zlib:enable_zlib( - SocketData#socket_state.sockmod, - SocketData#socket_state.socket), - ejabberd_receiver:compress(SocketData#socket_state.receiver, ZlibSocket), - send(SocketData, Data), + {ok, ZlibSocket} = ejabberd_receiver:compress( + SocketData#socket_state.receiver, Data), SocketData#socket_state{socket = ZlibSocket, sockmod = ejabberd_zlib}. reset_stream(SocketData) when is_pid(SocketData#socket_state.receiver) -> @@ -160,10 +151,25 @@ reset_stream(SocketData) when is_atom(SocketData#socket_state.receiver) -> (SocketData#socket_state.receiver):reset_stream( SocketData#socket_state.socket). +change_controller(#socket_state{receiver = Recv}, Pid) when is_pid(Recv) -> + ejabberd_receiver:setopts(Recv, [{active, false}]), + sync_events(Pid), + ejabberd_receiver:change_controller(Recv, Pid); +change_controller(#socket_state{socket = Socket, receiver = Mod}, Pid) -> + Mod:setopts(Socket, [{active, false}]), + sync_events(Pid), + Mod:change_controller(Socket, Pid). + %% sockmod=gen_tcp|tls|ejabberd_zlib send(SocketData, Data) -> - case catch (SocketData#socket_state.sockmod):send( - SocketData#socket_state.socket, Data) of + Res = if node(SocketData#socket_state.receiver) == node() -> + catch (SocketData#socket_state.sockmod):send( + SocketData#socket_state.socket, Data); + true -> + catch ejabberd_receiver:send( + SocketData#socket_state.receiver, Data) + end, + case Res of ok -> ok; {error, timeout} -> ?INFO_MSG("Timeout on ~p:send",[SocketData#socket_state.sockmod]), @@ -225,3 +231,21 @@ peername(#socket_state{sockmod = SockMod, socket = Socket}) -> %%==================================================================== %% Internal functions %%==================================================================== +%% dirty hack to relay queued messages from +%% old owner to new owner. The idea is based +%% on code of gen_tcp:controlling_process/2. +sync_events(C2SPid) -> + receive + {'$gen_event', El} = Event when element(1, El) == xmlelement; + element(1, El) == xmlstreamstart; + element(1, El) == xmlstreamelement; + element(1, El) == xmlstreamend; + element(1, El) == xmlstreamerror -> + C2SPid ! Event, + sync_events(C2SPid); + closed -> + C2SPid ! closed, + sync_events(C2SPid) + after 0 -> + ok + end. diff --git a/src/ejabberd_sup.erl b/src/ejabberd_sup.erl index f0119326a..ff5d64782 100644 --- a/src/ejabberd_sup.erl +++ b/src/ejabberd_sup.erl @@ -42,13 +42,6 @@ init([]) -> brutal_kill, worker, [ejabberd_hooks]}, - NodeGroups = - {ejabberd_node_groups, - {ejabberd_node_groups, start_link, []}, - permanent, - brutal_kill, - worker, - [ejabberd_node_groups]}, SystemMonitor = {ejabberd_system_monitor, {ejabberd_system_monitor, start_link, []}, @@ -177,9 +170,16 @@ init([]) -> infinity, supervisor, [ejabberd_tmp_sup]}, + Cluster = + {ejabberd_cluster, + {ejabberd_cluster, start_link, []}, + permanent, + brutal_kill, + worker, + [ejabberd_cluster]}, {ok, {{one_for_one, 10, 1}, [Hooks, - NodeGroups, + Cluster, SystemMonitor, Router, SM, diff --git a/src/ejabberdctl.template b/src/ejabberdctl.template index 9ede77dfe..fecdecc86 100644 --- a/src/ejabberdctl.template +++ b/src/ejabberdctl.template @@ -82,7 +82,7 @@ else KERNEL_OPTS="-kernel inet_dist_listen_min ${FIREWALL_WINDOW%-*} inet_dist_listen_max ${FIREWALL_WINDOW#*-}" fi -ERLANG_OPTS="+K $POLL -smp $SMP +P $ERL_PROCESSES $ERL_OPTIONS $KERNEL_OPTS" +ERLANG_OPTS="+K $POLL -smp $SMP +P $ERL_PROCESSES $ERL_OPTIONS" # define additional environment variables if [ "$EJABBERDDIR" = "" ]; then @@ -141,6 +141,7 @@ start () -noinput -detached \ -pa $EJABBERD_EBIN_PATH \ -mnesia dir \"\\\"$SPOOLDIR\\\"\" \ + $KERNEL_OPTS \ -s ejabberd \ -sasl sasl_error_logger \\{file,\\\"$SASL_LOG_PATH\\\"\\} \ $ERLANG_OPTS $ARGS \"$@\"" @@ -174,6 +175,7 @@ debug () $NAME debug-${TTY}-${ERLANG_NODE} \ -remsh $ERLANG_NODE \ -hidden \ + $KERNEL_OPTS \ $ERLANG_OPTS $ARGS \"$@\"" } @@ -203,6 +205,7 @@ live () $NAME $ERLANG_NODE \ -pa $EJABBERD_EBIN_PATH \ -mnesia dir \"\\\"$SPOOLDIR\\\"\" \ + $KERNEL_OPTS \ -s ejabberd \ $ERLANG_OPTS $ARGS \"$@\"" } @@ -236,7 +239,7 @@ ctl () MAXCONNID=100 CONNLOCKDIR=@LOCALSTATEDIR@/lock/ejabberdctl FLOCK='/usr/bin/flock' - if [ ! -x "$FLOCK" ] ; then + if [ ! -x "$FLOCK" ] || [ ! -d "$CONNLOCKDIR" ] ; then JOT='/usr/bin/jot' if [ ! -x "$JOT" ] ; then # no flock or jot, simply invoke ctlexec() @@ -310,6 +313,7 @@ ctlexec () -noinput \ -hidden \ -pa $EJABBERD_EBIN_PATH \ + $KERNEL_OPTS \ -s ejabberd_ctl -extra $ERLANG_NODE $COMMAND" } diff --git a/src/mod_last.erl b/src/mod_last.erl index 73d908f8d..d3b561f60 100644 --- a/src/mod_last.erl +++ b/src/mod_last.erl @@ -127,7 +127,7 @@ process_sm_iq(From, To, #iq{type = Type, sub_el = SubEl} = IQ) -> [User, Server, UserListRecord, {From, To, {xmlelement, "presence", [], []}}, - out]) of + in]) of allow -> get_last(IQ, SubEl, User, Server); deny -> diff --git a/src/mod_last_odbc.erl b/src/mod_last_odbc.erl index 5d6aac2b1..7616c5020 100644 --- a/src/mod_last_odbc.erl +++ b/src/mod_last_odbc.erl @@ -119,7 +119,7 @@ process_sm_iq(From, To, #iq{type = Type, sub_el = SubEl} = IQ) -> [User, Server, UserListRecord, {From, To, {xmlelement, "presence", [], []}}, - out]) of + in]) of allow -> get_last(IQ, SubEl, User, Server); deny -> diff --git a/src/mod_muc/mod_muc.erl b/src/mod_muc/mod_muc.erl index f79f4cd24..89f815670 100644 --- a/src/mod_muc/mod_muc.erl +++ b/src/mod_muc/mod_muc.erl @@ -41,6 +41,9 @@ create_room/5, process_iq_disco_items/4, broadcast_service_message/2, + register_room/3, + migrate/1, + get_vh_rooms/1, can_use_nick/3]). %% gen_server callbacks @@ -109,7 +112,9 @@ room_destroyed(Host, Room, Pid, ServerHost) -> %% Else use the passed options as defined in mod_muc_room. create_room(Host, Name, From, Nick, Opts) -> Proc = gen_mod:get_module_proc(Host, ?PROCNAME), - gen_server:call(Proc, {create, Name, From, Nick, Opts}). + RoomHost = gen_mod:get_module_opt_host(Host, ?MODULE, "conference.@HOST@"), + Node = ejabberd_cluster:get_node({Name, RoomHost}), + gen_server:call({Proc, Node}, {create, Name, From, Nick, Opts}). store_room(Host, Name, Opts) -> F = fun() -> @@ -162,6 +167,22 @@ can_use_nick(Host, JID, Nick) -> U == LUS end. +migrate(After) -> + Rs = mnesia:dirty_select( + muc_online_room, + [{#muc_online_room{name_host = '$1', pid = '$2', _ = '_'}, + [], + ['$$']}]), + lists:foreach( + fun([NameHost, Pid]) -> + case ejabberd_cluster:get_node_new(NameHost) of + Node when Node /= node() -> + mod_muc_room:migrate(Pid, Node, After); + _ -> + ok + end + end, Rs). + %%==================================================================== %% gen_server callbacks %%==================================================================== @@ -174,6 +195,7 @@ can_use_nick(Host, JID, Nick) -> %% Description: Initiates the server %%-------------------------------------------------------------------- init([Host, Opts]) -> + update_muc_online_table(), mnesia:create_table(muc_room, [{disc_copies, [node()]}, {attributes, record_info(fields, muc_room)}]), @@ -182,14 +204,13 @@ init([Host, Opts]) -> {attributes, record_info(fields, muc_registered)}]), mnesia:create_table(muc_online_room, [{ram_copies, [node()]}, + {local_content, true}, {attributes, record_info(fields, muc_online_room)}]), mnesia:add_table_copy(muc_online_room, node(), ram_copies), catch ets:new(muc_online_users, [bag, named_table, public, {keypos, 2}]), MyHost = gen_mod:get_opt_host(Host, Opts, "conference.@HOST@"), update_tables(MyHost), - clean_table_from_bad_node(node(), MyHost), mnesia:add_table_index(muc_registered, nick), - mnesia:subscribe(system), Access = gen_mod:get_opt(access, Opts, all), AccessCreate = gen_mod:get_opt(access_create, Opts, all), AccessAdmin = gen_mod:get_opt(access_admin, Opts, none), @@ -198,6 +219,7 @@ init([Host, Opts]) -> DefRoomOpts = gen_mod:get_opt(default_room_options, Opts, []), RoomShaper = gen_mod:get_opt(room_shaper, Opts, none), ejabberd_router:register_route(MyHost), + ejabberd_hooks:add(node_hash_update, ?MODULE, migrate, 100), load_permanent_rooms(MyHost, Host, {Access, AccessCreate, AccessAdmin, AccessPersistent}, HistorySize, @@ -264,12 +286,19 @@ handle_info({route, From, To, Packet}, default_room_opts = DefRoomOpts, history_size = HistorySize, room_shaper = RoomShaper} = State) -> - case catch do_route(Host, ServerHost, Access, HistorySize, RoomShaper, - From, To, Packet, DefRoomOpts) of - {'EXIT', Reason} -> - ?ERROR_MSG("~p", [Reason]); - _ -> - ok + {U, S, _} = jlib:jid_tolower(To), + case ejabberd_cluster:get_node({U, S}) of + Node when Node == node() -> + case catch do_route(Host, ServerHost, Access, HistorySize, + RoomShaper, From, To, Packet, DefRoomOpts) of + {'EXIT', Reason} -> + ?ERROR_MSG("~p", [Reason]); + _ -> + ok + end; + Node -> + Proc = gen_mod:get_module_proc(ServerHost, ?PROCNAME), + {Proc, Node} ! {route, From, To, Packet} end, {noreply, State}; handle_info({room_destroyed, RoomHost, Pid}, State) -> @@ -277,10 +306,7 @@ handle_info({room_destroyed, RoomHost, Pid}, State) -> mnesia:delete_object(#muc_online_room{name_host = RoomHost, pid = Pid}) end, - mnesia:transaction(F), - {noreply, State}; -handle_info({mnesia_system_event, {mnesia_down, Node}}, State) -> - clean_table_from_bad_node(Node), + mnesia:async_dirty(F), {noreply, State}; handle_info(_Info, State) -> {noreply, State}. @@ -293,6 +319,7 @@ handle_info(_Info, State) -> %% The return value is ignored. %%-------------------------------------------------------------------- terminate(_Reason, State) -> + ejabberd_hooks:delete(node_hash_update, ?MODULE, migrate, 100), ejabberd_router:unregister_route(State#state.host), ok. @@ -532,17 +559,22 @@ load_permanent_rooms(Host, ServerHost, Access, HistorySize, RoomShaper) -> lists:foreach( fun(R) -> {Room, Host} = R#muc_room.name_host, - case mnesia:dirty_read(muc_online_room, {Room, Host}) of - [] -> - {ok, Pid} = mod_muc_room:start( - Host, - ServerHost, - Access, - Room, - HistorySize, - RoomShaper, - R#muc_room.opts), - register_room(Host, Room, Pid); + case ejabberd_cluster:get_node({Room, Host}) of + Node when Node == node() -> + case mnesia:dirty_read(muc_online_room, {Room, Host}) of + [] -> + {ok, Pid} = mod_muc_room:start( + Host, + ServerHost, + Access, + Room, + HistorySize, + RoomShaper, + R#muc_room.opts), + register_room(Host, Room, Pid); + _ -> + ok + end; _ -> ok end @@ -568,11 +600,10 @@ start_new_room(Host, ServerHost, Access, Room, register_room(Host, Room, Pid) -> F = fun() -> - mnesia:write(#muc_online_room{name_host = {Room, Host}, - pid = Pid}) - end, - mnesia:transaction(F). - + mnesia:write(#muc_online_room{name_host = {Room, Host}, + pid = Pid}) + end, + mnesia:async_dirty(F). iq_disco_info(Lang) -> [{xmlelement, "identity", @@ -601,7 +632,7 @@ iq_disco_items(Host, From, Lang, none) -> _ -> false end - end, get_vh_rooms(Host)); + end, get_vh_rooms_all_nodes(Host)); iq_disco_items(Host, From, Lang, Rsm) -> {Rooms, RsmO} = get_vh_rooms(Host, Rsm), @@ -621,19 +652,9 @@ iq_disco_items(Host, From, Lang, Rsm) -> end, Rooms) ++ RsmOut. get_vh_rooms(Host, #rsm_in{max=M, direction=Direction, id=I, index=Index})-> - AllRooms = lists:sort(get_vh_rooms(Host)), + AllRooms = get_vh_rooms_all_nodes(Host), Count = erlang:length(AllRooms), - Guard = case Direction of - _ when Index =/= undefined -> [{'==', {element, 2, '$1'}, Host}]; - aft -> [{'==', {element, 2, '$1'}, Host}, {'>=',{element, 1, '$1'} ,I}]; - before when I =/= []-> [{'==', {element, 2, '$1'}, Host}, {'=<',{element, 1, '$1'} ,I}]; - _ -> [{'==', {element, 2, '$1'}, Host}] - end, - L = lists:sort( - mnesia:dirty_select(muc_online_room, - [{#muc_online_room{name_host = '$1', _ = '_'}, - Guard, - ['$_']}])), + L = get_vh_rooms_direction(Direction, I, Index, AllRooms), L2 = if Index == undefined andalso Direction == before -> lists:reverse(lists:sublist(lists:reverse(L), 1, M)); @@ -656,6 +677,27 @@ get_vh_rooms(Host, #rsm_in{max=M, direction=Direction, id=I, index=Index})-> {L2, #rsm_out{first=F, last=Last, count=Count, index=NewIndex}} end. +get_vh_rooms_direction(_Direction, _I, Index, AllRooms) when Index =/= undefined -> + AllRooms; +get_vh_rooms_direction(aft, I, _Index, AllRooms) -> + {_Before, After} = + lists:splitwith( + fun(#muc_online_room{name_host = {Na, _}}) -> + Na < I end, AllRooms), + case After of + [] -> []; + [#muc_online_room{name_host = {I, _Host}} | AfterTail] -> AfterTail; + _ -> After + end; +get_vh_rooms_direction(before, I, _Index, AllRooms) when I =/= []-> + {Before, _} = + lists:splitwith( + fun(#muc_online_room{name_host = {Na, _}}) -> + Na < I end, AllRooms), + Before; +get_vh_rooms_direction(_Direction, _I, _Index, AllRooms) -> + AllRooms. + %% @doc Return the position of desired room in the list of rooms. %% The room must exist in the list. The count starts in 0. %% @spec (Desired::muc_online_room(), Rooms::[muc_online_room()]) -> integer() @@ -813,7 +855,22 @@ broadcast_service_message(Host, Msg) -> fun(#muc_online_room{pid = Pid}) -> gen_fsm:send_all_state_event( Pid, {service_message, Msg}) - end, get_vh_rooms(Host)). + end, get_vh_rooms_all_nodes(Host)). + +get_vh_rooms_all_nodes(Host) -> + Rooms = lists:foldl( + fun(Node, Acc) when Node == node() -> + get_vh_rooms(Host) ++ Acc; + (Node, Acc) -> + case catch rpc:call(Node, ?MODULE, get_vh_rooms, + [Host], 5000) of + Res when is_list(Res) -> + Res ++ Acc; + _ -> + Acc + end + end, [], ejabberd_cluster:get_nodes()), + lists:ukeysort(#muc_online_room.name_host, Rooms). get_vh_rooms(Host) -> mnesia:dirty_select(muc_online_room, @@ -821,39 +878,18 @@ get_vh_rooms(Host) -> [{'==', {element, 2, '$1'}, Host}], ['$_']}]). - -clean_table_from_bad_node(Node) -> - F = fun() -> - Es = mnesia:select( - muc_online_room, - [{#muc_online_room{pid = '$1', _ = '_'}, - [{'==', {node, '$1'}, Node}], - ['$_']}]), - lists:foreach(fun(E) -> - mnesia:delete_object(E) - end, Es) - end, - mnesia:async_dirty(F). - -clean_table_from_bad_node(Node, Host) -> - F = fun() -> - Es = mnesia:select( - muc_online_room, - [{#muc_online_room{pid = '$1', - name_host = {'_', Host}, - _ = '_'}, - [{'==', {node, '$1'}, Node}], - ['$_']}]), - lists:foreach(fun(E) -> - mnesia:delete_object(E) - end, Es) - end, - mnesia:async_dirty(F). - update_tables(Host) -> update_muc_room_table(Host), update_muc_registered_table(Host). +update_muc_online_table() -> + case catch mnesia:table_info(muc_online_room, local_content) of + false -> + mnesia:delete_table(muc_online_room); + _ -> + ok + end. + update_muc_room_table(Host) -> Fields = record_info(fields, muc_room), case mnesia:table_info(muc_room, attributes) of diff --git a/src/mod_muc/mod_muc_log.erl b/src/mod_muc/mod_muc_log.erl index f1c57eac0..fbc2d5cbe 100644 --- a/src/mod_muc/mod_muc_log.erl +++ b/src/mod_muc/mod_muc_log.erl @@ -73,11 +73,11 @@ %% Description: Starts the server %%-------------------------------------------------------------------- start_link(Host, Opts) -> - Proc = gen_mod:get_module_proc(Host, ?PROCNAME), - gen_server:start_link({local, Proc}, ?MODULE, [Host, Opts], []). + Proc = get_proc_name(Host), + gen_server:start_link(Proc, ?MODULE, [Host, Opts], []). start(Host, Opts) -> - Proc = gen_mod:get_module_proc(Host, ?PROCNAME), + Proc = get_proc_name(Host), ChildSpec = {Proc, {?MODULE, start_link, [Host, Opts]}, @@ -88,7 +88,7 @@ start(Host, Opts) -> supervisor:start_child(ejabberd_sup, ChildSpec). stop(Host) -> - Proc = gen_mod:get_module_proc(Host, ?PROCNAME), + Proc = get_proc_name(Host), gen_server:call(Proc, stop), supervisor:delete_child(ejabberd_sup, Proc). @@ -860,7 +860,9 @@ roomconfig_to_string(Options, Lang, FileFormat) -> T -> case Opt of password -> "
" ++ OptText ++ "
"; - title -> "
" ++ ?T("Room title") ++ ": \"" ++ htmlize(T, FileFormat) ++ "\"
"; + max_users -> "
" ++ OptText ++ ": \"" ++ htmlize(integer_to_list(T), FileFormat) ++ "\"
"; + title -> "
" ++ OptText ++ ": \"" ++ htmlize(T, FileFormat) ++ "\"
"; + description -> "
" ++ OptText ++ ": \"" ++ htmlize(T, FileFormat) ++ "\"
"; _ -> "\"" ++ T ++ "\"" end end, @@ -876,7 +878,7 @@ get_roomconfig_text(public) -> "Make room public searchable"; get_roomconfig_text(public_list) -> "Make participants list public"; get_roomconfig_text(password_protected) -> "Make room password protected"; get_roomconfig_text(password) -> "Password"; -get_roomconfig_text(anonymous) -> "Make room semianonymous"; +get_roomconfig_text(anonymous) -> "This room is not anonymous"; get_roomconfig_text(members_only) -> "Make room members-only"; get_roomconfig_text(moderated) -> "Make room moderated"; get_roomconfig_text(members_by_default) -> "Default users as participants"; @@ -885,6 +887,13 @@ get_roomconfig_text(allow_private_messages) -> "Allow users to send private mess get_roomconfig_text(allow_query_users) -> "Allow users to query other users"; get_roomconfig_text(allow_user_invites) -> "Allow users to send invites"; get_roomconfig_text(logging) -> "Enable logging"; +get_roomconfig_text(allow_visitor_nickchange) -> "Allow visitors to change nickname"; +get_roomconfig_text(allow_visitor_status) -> "Allow visitors to send status text in presence updates"; +get_roomconfig_text(captcha_protected) -> "Make room captcha protected"; +get_roomconfig_text(description) -> "Room description"; +%% get_roomconfig_text(subject) -> "Subject"; +%% get_roomconfig_text(subject_author) -> "Subject author"; +get_roomconfig_text(max_users) -> "Maximum Number of Occupants"; get_roomconfig_text(_) -> undefined. %% Users = [{JID, Nick, Role}] @@ -941,7 +950,8 @@ get_room_state(RoomPid) -> {ok, R} = gen_fsm:sync_send_all_state_event(RoomPid, get_state), R. -get_proc_name(Host) -> gen_mod:get_module_proc(Host, ?PROCNAME). +get_proc_name(Host) -> + {global, gen_mod:get_module_proc(Host, ?PROCNAME)}. calc_hour_offset(TimeHere) -> TimeZero = calendar:now_to_universal_time(now()), diff --git a/src/mod_muc/mod_muc_room.erl b/src/mod_muc/mod_muc_room.erl index 8798ace2d..cd358fcdf 100644 --- a/src/mod_muc/mod_muc_room.erl +++ b/src/mod_muc/mod_muc_room.erl @@ -27,14 +27,19 @@ -module(mod_muc_room). -author('alexey@process-one.net'). --behaviour(gen_fsm). +-define(GEN_FSM, p1_fsm). + +-behaviour(?GEN_FSM). %% External exports -export([start_link/9, start_link/7, + start_link/2, start/9, start/7, + start/2, + migrate/3, route/4]). %% gen_fsm callbacks @@ -44,6 +49,7 @@ handle_sync_event/4, handle_info/3, terminate/3, + print_state/1, code_change/4]). -include("ejabberd.hrl"). @@ -63,16 +69,12 @@ %% Module start with or without supervisor: -ifdef(NO_TRANSIENT_SUPERVISORS). --define(SUPERVISOR_START, - gen_fsm:start(?MODULE, [Host, ServerHost, Access, Room, HistorySize, - RoomShaper, Creator, Nick, DefRoomOpts], - ?FSMOPTS)). +-define(SUPERVISOR_START(Args), + ?GEN_FSM:start(?MODULE, Args, ?FSMOPTS)). -else. --define(SUPERVISOR_START, +-define(SUPERVISOR_START(Args), Supervisor = gen_mod:get_module_proc(ServerHost, ejabberd_mod_muc_sup), - supervisor:start_child( - Supervisor, [Host, ServerHost, Access, Room, HistorySize, RoomShaper, - Creator, Nick, DefRoomOpts])). + supervisor:start_child(Supervisor, Args)). -endif. %%%---------------------------------------------------------------------- @@ -80,7 +82,8 @@ %%%---------------------------------------------------------------------- start(Host, ServerHost, Access, Room, HistorySize, RoomShaper, Creator, Nick, DefRoomOpts) -> - ?SUPERVISOR_START. + ?SUPERVISOR_START([Host, ServerHost, Access, Room, HistorySize, + RoomShaper, Creator, Nick, DefRoomOpts]). start(Host, ServerHost, Access, Room, HistorySize, RoomShaper, Opts) -> Supervisor = gen_mod:get_module_proc(ServerHost, ejabberd_mod_muc_sup), @@ -88,16 +91,26 @@ start(Host, ServerHost, Access, Room, HistorySize, RoomShaper, Opts) -> Supervisor, [Host, ServerHost, Access, Room, HistorySize, RoomShaper, Opts]). +start(StateName, StateData) -> + ServerHost = StateData#state.server_host, + ?SUPERVISOR_START([StateName, StateData]). + start_link(Host, ServerHost, Access, Room, HistorySize, RoomShaper, Creator, Nick, DefRoomOpts) -> - gen_fsm:start_link(?MODULE, [Host, ServerHost, Access, Room, HistorySize, - RoomShaper, Creator, Nick, DefRoomOpts], - ?FSMOPTS). + ?GEN_FSM:start_link(?MODULE, [Host, ServerHost, Access, Room, HistorySize, + RoomShaper, Creator, Nick, DefRoomOpts], + ?FSMOPTS). start_link(Host, ServerHost, Access, Room, HistorySize, RoomShaper, Opts) -> - gen_fsm:start_link(?MODULE, [Host, ServerHost, Access, Room, HistorySize, - RoomShaper, Opts], - ?FSMOPTS). + ?GEN_FSM:start_link(?MODULE, [Host, ServerHost, Access, Room, HistorySize, + RoomShaper, Opts], + ?FSMOPTS). + +start_link(StateName, StateData) -> + ?GEN_FSM:start_link(?MODULE, [StateName, StateData], ?FSMOPTS). + +migrate(FsmRef, Node, After) -> + ?GEN_FSM:send_all_state_event(FsmRef, {migrate, Node, After}). %%%---------------------------------------------------------------------- %%% Callback functions from gen_fsm @@ -139,7 +152,11 @@ init([Host, ServerHost, Access, Room, HistorySize, RoomShaper, Opts]) -> jid = jlib:make_jid(Room, Host, ""), room_shaper = Shaper}), add_to_log(room_existence, started, State), - {ok, normal_state, State}. + {ok, normal_state, State}; +init([StateName, #state{room = Room, host = Host} = StateData]) -> + process_flag(trap_exit, true), + mod_muc:register_room(Host, Room, self()), + {ok, StateName, StateData}. %%---------------------------------------------------------------------- %% Func: StateName/2 @@ -162,7 +179,7 @@ normal_state({route, From, "", trunc(gen_mod:get_module_opt( StateData#state.server_host, mod_muc, min_message_interval, 0) * 1000000), - Size = iolist_size(xml:element_to_string(Packet)), + Size = element_size(Packet), {MessageShaper, MessageShaperInterval} = shaper:update(Activity#activity.message_shaper, Size), if @@ -580,6 +597,9 @@ handle_event(destroy, StateName, StateData) -> handle_event({set_affiliations, Affiliations}, StateName, StateData) -> {next_state, StateName, StateData#state{affiliations = Affiliations}}; +handle_event({migrate, Node, After}, StateName, StateData) when Node /= node() -> + {migrate, StateData, + {Node, ?MODULE, start, [StateName, StateData]}, After * 2}; handle_event(_Event, StateName, StateData) -> {next_state, StateName, StateData}. @@ -612,6 +632,9 @@ handle_sync_event(_Event, _From, StateName, StateData) -> code_change(_OldVsn, StateName, StateData, _Extra) -> {ok, StateName, StateData}. +print_state(StateData) -> + StateData. + %%---------------------------------------------------------------------- %% Func: handle_info/3 %% Returns: {next_state, NextStateName, NextStateData} | @@ -701,6 +724,13 @@ handle_info(_Info, StateName, StateData) -> %% Purpose: Shutdown the fsm %% Returns: any %%---------------------------------------------------------------------- +terminate({migrated, Clone}, _StateName, StateData) -> + ?INFO_MSG("Migrating room ~s@~s to ~p on node ~p", + [StateData#state.room, StateData#state.host, + Clone, node(Clone)]), + mod_muc:room_destroyed(StateData#state.host, StateData#state.room, + self(), StateData#state.server_host), + ok; terminate(Reason, _StateName, StateData) -> ?INFO_MSG("Stopping MUC room ~s@~s", [StateData#state.room, StateData#state.host]), @@ -739,7 +769,7 @@ terminate(Reason, _StateName, StateData) -> %%%---------------------------------------------------------------------- route(Pid, From, ToNick, Packet) -> - gen_fsm:send_event(Pid, {route, From, ToNick, Packet}). + ?GEN_FSM:send_event(Pid, {route, From, ToNick, Packet}). process_groupchat_message(From, {xmlelement, "message", Attrs, _Els} = Packet, StateData) -> @@ -1394,7 +1424,7 @@ prepare_room_queue(StateData) -> {{value, {message, From}}, _RoomQueue} -> Activity = get_user_activity(From, StateData), Packet = Activity#activity.message, - Size = iolist_size(xml:element_to_string(Packet)), + Size = element_size(Packet), {RoomShaper, RoomShaperInterval} = shaper:update(StateData#state.room_shaper, Size), erlang:send_after( @@ -1405,7 +1435,7 @@ prepare_room_queue(StateData) -> {{value, {presence, From}}, _RoomQueue} -> Activity = get_user_activity(From, StateData), {_Nick, Packet} = Activity#activity.presence, - Size = iolist_size(xml:element_to_string(Packet)), + Size = element_size(Packet), {RoomShaper, RoomShaperInterval} = shaper:update(StateData#state.room_shaper, Size), erlang:send_after( @@ -1625,13 +1655,12 @@ add_new_user(From, Nick, {xmlelement, _, Attrs, Els} = Packet, StateData) -> From, Err), StateData; captcha_required -> - ID = randoms:get_string(), SID = xml:get_attr_s("id", Attrs), RoomJID = StateData#state.jid, To = jlib:jid_replace_resource(RoomJID, Nick), case ejabberd_captcha:create_captcha( - ID, SID, RoomJID, To, Lang, From) of - {ok, CaptchaEls} -> + SID, RoomJID, To, Lang, From) of + {ok, ID, CaptchaEls} -> MsgPkt = {xmlelement, "message", [{"id", ID}], CaptchaEls}, Robots = ?DICT:store(From, {Nick, Packet}, StateData#state.robots), @@ -2068,7 +2097,7 @@ add_message_to_history(FromNick, FromJID, Packet, StateData) -> jlib:jid_replace_resource(StateData#state.jid, FromNick), StateData#state.jid, TSPacket), - Size = iolist_size(xml:element_to_string(SPacket)), + Size = element_size(SPacket), Q1 = lqueue_in({FromNick, TSPacket, HaveSubject, TimeStamp, Size}, StateData#state.history), add_to_log(text, {FromNick, Packet}, StateData), @@ -3582,3 +3611,6 @@ tab_count_user(JID) -> _ -> 0 end. + +element_size(El) -> + size(xml:element_to_binary(El)). diff --git a/src/mod_offline_odbc.erl b/src/mod_offline_odbc.erl index c89beda4e..063ea709e 100644 --- a/src/mod_offline_odbc.erl +++ b/src/mod_offline_odbc.erl @@ -123,8 +123,7 @@ loop(Host, AccessMaxOfflineMsgs) -> M#offline_msg.timestamp))]}, XML = ejabberd_odbc:escape( - lists:flatten( - xml:element_to_string(Packet))), + xml:element_to_binary(Packet)), odbc_queries:add_spool_sql(Username, XML) end, Msgs), case catch odbc_queries:add_spool(Host, Query) of diff --git a/src/mod_proxy65/mod_proxy65_sm.erl b/src/mod_proxy65/mod_proxy65_sm.erl index 569458f6a..bdd1b5bb8 100644 --- a/src/mod_proxy65/mod_proxy65_sm.erl +++ b/src/mod_proxy65/mod_proxy65_sm.erl @@ -71,7 +71,9 @@ start_link(Host, Opts) -> gen_server:start_link({local, Proc}, ?MODULE, [Opts], []). init([Opts]) -> + update_tables(), mnesia:create_table(bytestream, [{ram_copies, [node()]}, + {local_content, true}, {attributes, record_info(fields, bytestream)}]), mnesia:add_table_copy(bytestream, node(), ram_copies), MaxConnections = gen_mod:get_opt(max_connections, Opts, infinity), @@ -179,3 +181,11 @@ activate_stream(SHA1, IJid, TJid, Host) when is_list(SHA1) -> _ -> error end. + +update_tables() -> + case catch mnesia:table_info(bytestream, local_content) of + false -> + mnesia:delete_table(bytestream); + _ -> + ok + end. diff --git a/src/odbc/ejabberd_odbc.erl b/src/odbc/ejabberd_odbc.erl index d7cdd0371..1b07fd6d9 100644 --- a/src/odbc/ejabberd_odbc.erl +++ b/src/odbc/ejabberd_odbc.erl @@ -178,6 +178,7 @@ init([Host, StartInterval]) -> end, [DBType | _] = db_opts(Host), ?GEN_FSM:send_event(self(), connect), + ejabberd_odbc_sup:add_pid(Host, self()), {ok, connecting, #state{db_type = DBType, host = Host, max_pending_requests_len = max_fsm_queue(), @@ -274,6 +275,7 @@ handle_info(Info, StateName, State) -> {next_state, StateName, State}. terminate(_Reason, _StateName, State) -> + ejabberd_odbc_sup:remove_pid(State#state.host, self()), case State#state.db_type of mysql -> %% old versions of mysql driver don't have the stop function diff --git a/src/odbc/ejabberd_odbc_sup.erl b/src/odbc/ejabberd_odbc_sup.erl index d828449ec..45ede1835 100644 --- a/src/odbc/ejabberd_odbc_sup.erl +++ b/src/odbc/ejabberd_odbc_sup.erl @@ -30,6 +30,8 @@ %% API -export([start_link/1, init/1, + add_pid/2, + remove_pid/2, get_pids/1, get_random_pid/1 ]). @@ -44,7 +46,19 @@ -define(CONNECT_TIMEOUT, 500). % milliseconds +-record(sql_pool, {host, pid}). + start_link(Host) -> + mnesia:create_table(sql_pool, + [{ram_copies, [node()]}, + {type, bag}, + {local_content, true}, + {attributes, record_info(fields, sql_pool)}]), + mnesia:add_table_copy(local_config, node(), ram_copies), + F = fun() -> + mnesia:delete({sql_pool, Host}) + end, + mnesia:ets(F), supervisor:start_link({local, gen_mod:get_module_proc(Host, ?MODULE)}, ?MODULE, [Host]). @@ -86,16 +100,25 @@ init([Host]) -> end, lists:seq(1, PoolSize))}}. get_pids(Host) -> - Proc = gen_mod:get_module_proc(Host, ?MODULE), - - % throw an exception if supervisor is not ready (i.e. if it cannot - % start its children, if the database is down for example) - sys:get_status(Proc, ?CONNECT_TIMEOUT), - - [Child || - {_Id, Child, _Type, _Modules} <- supervisor:which_children(Proc), - Child /= undefined]. + Rs = mnesia:dirty_read(sql_pool, Host), + [R#sql_pool.pid || R <- Rs]. get_random_pid(Host) -> Pids = get_pids(Host), lists:nth(erlang:phash(now(), length(Pids)), Pids). + +add_pid(Host, Pid) -> + F = fun() -> + mnesia:write( + #sql_pool{host = Host, + pid = Pid}) + end, + mnesia:ets(F). + +remove_pid(Host, Pid) -> + F = fun() -> + mnesia:delete_object( + #sql_pool{host = Host, + pid = Pid}) + end, + mnesia:ets(F). diff --git a/src/p1_fsm.erl b/src/p1_fsm.erl index 03ff7f8ce..9ca924112 100644 --- a/src/p1_fsm.erl +++ b/src/p1_fsm.erl @@ -517,6 +517,25 @@ print_event(Dev, return, {Name, StateName}) -> io:format(Dev, "*DBG* ~p switched to state ~w~n", [Name, StateName]). +relay_messages(MRef, TRef, Clone, Queue) -> + lists:foreach( + fun(Msg) -> Clone ! Msg end, + queue:to_list(Queue)), + relay_messages(MRef, TRef, Clone). + +relay_messages(MRef, TRef, Clone) -> + receive + {'DOWN', MRef, process, Clone, Reason} -> + Reason; + {'EXIT', _Parent, _Reason} -> + {migrated, Clone}; + {timeout, TRef, timeout} -> + {migrated, Clone}; + Msg -> + Clone ! Msg, + relay_messages(MRef, TRef, Clone) + end. + handle_msg(Msg, Parent, Name, StateName, StateData, Mod, _Time, Limits, Queue, QueueLen) -> %No debug here From = from(Msg), @@ -535,6 +554,23 @@ handle_msg(Msg, Parent, Name, StateName, StateData, Mod, _Time, reply(From, Reply), loop(Parent, Name, NStateName, NStateData, Mod, Time1, [], Limits, Queue, QueueLen); + {migrate, NStateData, {Node, M, F, A}, Time1} -> + Reason = case catch rpc:call(Node, M, F, A, 5000) of + {badrpc, _} = Err -> + {migration_error, Err}; + {'EXIT', _} = Err -> + {migration_error, Err}; + {error, _} = Err -> + {migration_error, Err}; + {ok, Clone} -> + process_flag(trap_exit, true), + MRef = erlang:monitor(process, Clone), + TRef = erlang:start_timer(Time1, self(), timeout), + relay_messages(MRef, TRef, Clone, Queue); + Reply -> + {migration_error, {bad_reply, Reply}} + end, + terminate(Reason, Name, Msg, Mod, StateName, NStateData, []); {stop, Reason, NStateData} -> terminate(Reason, Name, Msg, Mod, StateName, NStateData, []); {stop, Reason, Reply, NStateData} when From =/= undefined -> @@ -571,6 +607,23 @@ handle_msg(Msg, Parent, Name, StateName, StateData, Debug1 = reply(Name, From, Reply, Debug, NStateName), loop(Parent, Name, NStateName, NStateData, Mod, Time1, Debug1, Limits, Queue, QueueLen); + {migrate, NStateData, {Node, M, F, A}, Time1} -> + Reason = case catch rpc:call(Node, M, F, A, Time1) of + {badrpc, R} -> + {migration_error, R}; + {'EXIT', R} -> + {migration_error, R}; + {error, R} -> + {migration_error, R}; + {ok, Clone} -> + process_flag(trap_exit, true), + MRef = erlang:monitor(process, Clone), + TRef = erlang:start_timer(Time1, self(), timeout), + relay_messages(MRef, TRef, Clone, Queue); + Reply -> + {migration_error, {bad_reply, Reply}} + end, + terminate(Reason, Name, Msg, Mod, StateName, NStateData, Debug); {stop, Reason, NStateData} -> terminate(Reason, Name, Msg, Mod, StateName, NStateData, Debug); {stop, Reason, Reply, NStateData} when From =/= undefined -> @@ -633,12 +686,10 @@ terminate(Reason, Name, Msg, Mod, StateName, StateData, Debug) -> %% Priority shutdown should be considered as %% shutdown by SASL exit(shutdown); - {process_limit, Limit} -> - %% Priority shutdown should be considered as - %% shutdown by SASL - error_logger:error_msg("FSM limit reached (~p): ~p~n", - [self(), Limit]), - exit(shutdown); + {process_limit, _Limit} -> + exit(Reason); + {migrated, _Clone} -> + exit(normal); _ -> error_info(Mod, Reason, Name, Msg, StateName, StateData, Debug), exit(Reason) @@ -705,7 +756,12 @@ get_msg(Msg) -> Msg. format_status(Opt, StatusData) -> [PDict, SysState, Parent, Debug, [Name, StateName, StateData, Mod, _Time]] = StatusData, - Header = lists:concat(["Status for state machine ", Name]), + NameTag = if is_pid(Name) -> + pid_to_list(Name); + is_atom(Name) -> + Name + end, + Header = lists:concat(["Status for state machine ", NameTag]), Log = sys:get_debug(log, Debug, []), Specfic = case erlang:function_exported(Mod, format_status, 2) of diff --git a/src/p1_prof.erl b/src/p1_prof.erl new file mode 100644 index 000000000..a7edbe139 --- /dev/null +++ b/src/p1_prof.erl @@ -0,0 +1,337 @@ +%%%------------------------------------------------------------------- +%%% File : p1_prof.erl +%%% Author : Evgeniy Khramtsov +%%% Description : Handy wrapper around eprof and fprof +%%% +%%% Created : 23 Jan 2010 by Evgeniy Khramtsov +%%% +%%% +%%% ejabberd, Copyright (C) 2002-2010 ProcessOne +%%% +%%% This program is free software; you can redistribute it and/or +%%% modify it under the terms of the GNU General Public License as +%%% published by the Free Software Foundation; either version 2 of the +%%% License, or (at your option) any later version. +%%% +%%% This program is distributed in the hope that it will be useful, +%%% but WITHOUT ANY WARRANTY; without even the implied warranty of +%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +%%% General Public License for more details. +%%% +%%% You should have received a copy of the GNU General Public License +%%% along with this program; if not, write to the Free Software +%%% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +%%% 02111-1307 USA +%%% +%%%------------------------------------------------------------------- +-module(p1_prof). + +%% API +-export([eprof_start/0, eprof_stop/0, + fprof_start/0, fprof_start/1, + fprof_stop/0, fprof_analyze/0, + queue/0, queue/1, memory/0, memory/1, + reds/0, reds/1, trace/1, help/0, + q/0, m/0, r/0, q/1, m/1, r/1]). + +-define(APPS, [ejabberd, mnesia]). + +%%==================================================================== +%% API +%%==================================================================== +eprof_start() -> + eprof:start(), + case lists:keyfind(running, 1, application:info()) of + {_, Apps} -> + case get_procs(?APPS, Apps) of + [] -> + {error, no_procs_found}; + Procs -> + eprof:start_profiling(Procs) + end; + _ -> + {error, no_app_info} + end. + +fprof_start() -> + fprof_start(0). + +fprof_start(Duration) -> + case lists:keyfind(running, 1, application:info()) of + {_, Apps} -> + case get_procs(?APPS, Apps) of + [] -> + {error, no_procs_found}; + Procs -> + fprof:trace([start, {procs, Procs}]), + io:format("Profiling started~n"), + if Duration > 0 -> + timer:sleep(Duration*1000), + fprof:trace([stop]), + fprof:stop(); + true-> + ok + end + end; + _ -> + {error, no_app_info} + end. + +fprof_stop() -> + fprof:trace([stop]), + fprof:profile(), + fprof:analyse([totals, no_details, {sort, own}, + no_callers, {dest, "fprof.analysis"}]), + fprof:stop(), + format_fprof_analyze(). + +fprof_analyze() -> + fprof_stop(). + +eprof_stop() -> + eprof:stop_profiling(), + case erlang:function_exported(eprof, analyse, 0) of + true -> + eprof:analyse(); + false -> + eprof:analyze() + end. + +help() -> + M = ?MODULE, + io:format("Brief help:~n" + "~p:queue(N) - show top N pids sorted by queue length~n" + "~p:queue() - shorthand for ~p:queue(10)~n" + "~p:memory(N) - show top N pids sorted by memory usage~n" + "~p:memory() - shorthand for ~p:memory(10)~n" + "~p:reds(N) - show top N pids sorted by reductions~n" + "~p:reds() - shorthand for ~p:reds(10)~n" + "~p:q(N)|~p:q() - same as ~p:queue(N)|~p:queue()~n" + "~p:m(N)|~p:m() - same as ~p:memory(N)|~p:memory()~n" + "~p:r(N)|~p:r() - same as ~p:reds(N)|~p:reds()~n" + "~p:trace(Pid) - trace Pid; to stop tracing close " + "Erlang shell with Ctrl+C~n" + "~p:eprof_start() - start eprof on all available pids; " + "DO NOT use on production system!~n" + "~p:eprof_stop() - stop eprof and print result~n" + "~p:fprof_start() - start fprof on all available pids; " + "DO NOT use on production system!~n" + "~p:fprof_stop() - stop eprof and print formatted result~n" + "~p:fprof_start(N) - start and run fprof for N seconds; " + "use ~p:fprof_analyze() to analyze collected statistics and " + "print formatted result; use on production system with CARE~n" + "~p:fprof_analyze() - analyze previously collected statistics " + "using ~p:fprof_start(N) and print formatted result~n" + "~p:help() - print this help~n", + lists:duplicate(31, M)). + +q() -> + queue(). + +q(N) -> + queue(N). + +m() -> + memory(). + +m(N) -> + memory(N). + +r() -> + reds(). + +r(N) -> + reds(N). + +queue() -> + queue(10). + +memory() -> + memory(10). + +reds() -> + reds(10). + +queue(N) -> + dump(N, lists:reverse(lists:ukeysort(1, all_pids(queue)))). + +memory(N) -> + dump(N, lists:reverse(lists:ukeysort(2, all_pids(memory)))). + +reds(N) -> + dump(N, lists:reverse(lists:ukeysort(3, all_pids(reductions)))). + +trace(Pid) -> + erlang:trace(Pid, true, [send, 'receive']), + trace_loop(). + +trace_loop() -> + receive + M -> + io:format("~p~n", [M]), + trace_loop() + end. + +%%==================================================================== +%% Internal functions +%%==================================================================== +get_procs(Apps, AppList) -> + io:format("Searching for processes to profile...~n", []), + Procs = lists:flatmap( + fun({App, Leader}) when is_pid(Leader) -> + case lists:member(App, Apps) of + true -> + get_procs(Leader); + false -> + [] + end; + (_) -> + [] + end, AppList), + io:format("Found ~p processes~n", [length(Procs)]), + Procs. + +get_procs(Leader) -> + lists:filter( + fun(Pid) -> + case process_info(Pid, group_leader) of + {_, Leader} -> + true; + _ -> + false + end + end, processes()). + +format_fprof_analyze() -> + case file:consult("fprof.analysis") of + {ok, [_, [{totals, _, _, TotalOWN}] | Rest]} -> + OWNs = lists:flatmap( + fun({MFA, _, _, OWN}) -> + Percent = OWN*100/TotalOWN, + case round(Percent) of + 0 -> + []; + _ -> + [{mfa_to_list(MFA), Percent}] + end + end, Rest), + ACCs = collect_accs(Rest), + MaxACC = find_max(ACCs), + MaxOWN = find_max(OWNs), + io:format("=== Sorted by OWN:~n"), + lists:foreach( + fun({MFA, Per}) -> + L = length(MFA), + S = lists:duplicate(MaxOWN - L + 2, $ ), + io:format("~s~s~.2f%~n", [MFA, S, Per]) + end, lists:reverse(lists:keysort(2, OWNs))), + io:format("~n=== Sorted by ACC:~n"), + lists:foreach( + fun({MFA, Per}) -> + L = length(MFA), + S = lists:duplicate(MaxACC - L + 2, $ ), + io:format("~s~s~.2f%~n", [MFA, S, Per]) + end, lists:reverse(lists:keysort(2, ACCs))); + Err -> + Err + end. + +mfa_to_list({M, F, A}) -> + atom_to_list(M) ++ ":" ++ atom_to_list(F) ++ "/" ++ integer_to_list(A); +mfa_to_list(F) when is_atom(F) -> + atom_to_list(F). + +find_max(List) -> + find_max(List, 0). + +find_max([{V, _}|Tail], Acc) -> + find_max(Tail, lists:max([length(V), Acc])); +find_max([], Acc) -> + Acc. + +collect_accs(List) -> + List1 = lists:filter( + fun({MFA, _, _, _}) -> + case MFA of + {sys, _, _} -> + false; + suspend -> + false; + {gen_fsm, _, _} -> + false; + {p1_fsm, _, _} -> + false; + {gen, _, _} -> + false; + {gen_server, _, _} -> + false; + {proc_lib, _, _} -> + false; + _ -> + true + end + end, List), + TotalACC = lists:sum([A || {_, _, A, _} <- List1]), + lists:flatmap( + fun({MFA, _, ACC, _}) -> + Percent = ACC*100/TotalACC, + case round(Percent) of + 0 -> + []; + _ -> + [{mfa_to_list(MFA), Percent}] + end + end, List1). + +all_pids(Type) -> + lists:foldl( + fun(P, Acc) when P == self() -> + %% exclude ourself from statistics + Acc; + (P, Acc) -> + case catch process_info( + P, + [message_queue_len, + memory, + reductions, + dictionary, + current_function, + registered_name]) of + [{_, Len}, {_, Memory}, {_, Reds}, + {_, Dict}, {_, CurFun}, {_, RegName}] -> + if Type == queue andalso Len == 0 -> + Acc; + true -> + [{Len, Memory, Reds, Dict, CurFun, P, RegName}|Acc] + end; + _ -> + Acc + end + end, [], processes()). + +dump(N, Rs) -> + lists:foreach( + fun({MsgQLen, Memory, Reds, Dict, CurFun, Pid, RegName}) -> + PidStr = pid_to_list(Pid), + [_, Maj, Min] = string:tokens( + string:substr( + PidStr, 2, length(PidStr) - 2), "."), + io:format("** pid(0,~s,~s)~n" + "** registered name: ~p~n" + "** memory: ~p~n" + "** reductions: ~p~n" + "** message queue len: ~p~n" + "** current_function: ~p~n" + "** dictionary: ~p~n~n", + [Maj, Min, RegName, Memory, Reds, MsgQLen, CurFun, Dict]) + end, nthhead(N, Rs)). + +nthhead(N, L) -> + lists:reverse(nthhead(N, L, [])). + +nthhead(0, _L, Acc) -> + Acc; +nthhead(N, [H|T], Acc) -> + nthhead(N-1, T, [H|Acc]); +nthhead(_N, [], Acc) -> + Acc. diff --git a/src/tls/Makefile.in b/src/tls/Makefile.in index b29e1ae29..445879657 100644 --- a/src/tls/Makefile.in +++ b/src/tls/Makefile.in @@ -21,6 +21,7 @@ ifeq ($(shell uname),SunOs) DYNAMIC_LIB_CFLAGS = -KPIC -G -z text endif +EFLAGS += @ERLANG_SSLVER@ EFLAGS += -I .. EFLAGS += -pz .. diff --git a/src/tls/tls.erl b/src/tls/tls.erl index 9aee54cfb..9c921b36f 100644 --- a/src/tls/tls.erl +++ b/src/tls/tls.erl @@ -61,6 +61,13 @@ -define(GET_VERIFY_RESULT, 8). -define(VERIFY_NONE, 16#10000). +-ifdef(SSL40). +-define(CERT_DECODE, {public_key, pkix_decode_cert, plain}). +-else. +-define(CERT_DECODE, {ssl_pkix, decode_cert, [pkix]}). +-endif. + + -record(tlssock, {tcpsock, tlsport}). start() -> @@ -232,7 +239,8 @@ close(#tlssock{tcpsock = TCPSocket, tlsport = Port}) -> get_peer_certificate(#tlssock{tlsport = Port}) -> case port_control(Port, ?GET_PEER_CERTIFICATE, []) of <<0, BCert/binary>> -> - case catch ssl_pkix:decode_cert(BCert, [pkix]) of + {CertMod, CertFun, CertSecondArg} = ?CERT_DECODE, + case catch apply(CertMod, CertFun, [BCert, CertSecondArg]) of {ok, Cert} -> {ok, Cert}; _ -> diff --git a/src/web/Makefile.in b/src/web/Makefile.in index 519314ef7..77f801410 100644 --- a/src/web/Makefile.in +++ b/src/web/Makefile.in @@ -9,7 +9,7 @@ LIBS = @LIBS@ ERLANG_CFLAGS = @ERLANG_CFLAGS@ ERLANG_LIBS = @ERLANG_LIBS@ -EFLAGS += @ERLANG_SSL39@ +EFLAGS += @ERLANG_SSLVER@ EFLAGS += -I .. EFLAGS += -pz .. diff --git a/src/web/ejabberd_http_bind.erl b/src/web/ejabberd_http_bind.erl index 80ddaf3ea..a1dbc570a 100644 --- a/src/web/ejabberd_http_bind.erl +++ b/src/web/ejabberd_http_bind.erl @@ -27,6 +27,7 @@ setopts/2, controlling_process/2, become_controller/2, + change_controller/2, custom_receiver/1, reset_stream/1, change_shaper/2, @@ -121,9 +122,19 @@ start(XMPPDomain, Sid, Key, IP) -> ?DEBUG("Starting session", []), case catch supervisor:start_child(ejabberd_http_bind_sup, [Sid, Key, IP]) of - {ok, Pid} -> {ok, Pid}; - _ -> check_bind_module(XMPPDomain), - {error, "Cannot start HTTP bind session"} + {ok, Pid} -> + {ok, Pid}; + {error, _} = Err -> + case check_bind_module(XMPPDomain) of + false -> + {error, "Cannot start HTTP bind session"}; + true -> + ?ERROR_MSG("Cannot start HTTP bind session: ~p", [Err]), + Err + end; + Exit -> + ?ERROR_MSG("Cannot start HTTP bind session: ~p", [Exit]), + {error, Exit} end. start_link(Sid, Key, IP) -> @@ -140,7 +151,13 @@ setopts({http_bind, FsmRef, _IP}, Opts) -> true -> gen_fsm:send_all_state_event(FsmRef, {activate, self()}); _ -> - ok + case lists:member({active, false}, Opts) of + true -> + gen_fsm:sync_send_all_state_event( + FsmRef, deactivate_socket); + _ -> + ok + end end. controlling_process(_Socket, _Pid) -> @@ -152,6 +169,9 @@ custom_receiver({http_bind, FsmRef, _IP}) -> become_controller(FsmRef, C2SPid) -> gen_fsm:send_all_state_event(FsmRef, {become_controller, C2SPid}). +change_controller({http_bind, FsmRef, _IP}, C2SPid) -> + become_controller(FsmRef, C2SPid). + reset_stream({http_bind, _FsmRef, _IP}) -> ok. @@ -170,7 +190,6 @@ sockname(_Socket) -> peername({http_bind, _FsmRef, IP}) -> {ok, IP}. - %% Entry point for data coming from client through ejabberd HTTP server: process_request(Data, IP) -> Opts1 = ejabberd_c2s_config:get_c2s_limits(), @@ -192,12 +211,12 @@ process_request(Data, IP) -> "xmlns='" ++ ?NS_HTTP_BIND ++ "'/>"}; XmppDomain -> %% create new session - Sid = sha:sha(term_to_binary({now(), make_ref()})), + Sid = make_sid(), case start(XmppDomain, Sid, "", IP) of {error, _} -> - {200, ?HEADER, "BOSH module not started"}; + "xmlns='" ++ ?NS_HTTP_BIND ++ "'>Internal Server Error"}; {ok, Pid} -> handle_session_start( Pid, XmppDomain, Sid, Rid, Attrs, @@ -223,10 +242,10 @@ process_request(Data, IP) -> handle_http_put(Sid, Rid, Attrs, Payload2, PayloadSize, StreamStart, IP); {size_limit, Sid} -> - case mnesia:dirty_read({http_bind, Sid}) of - [] -> + case get_session(Sid) of + {error, _} -> {404, ?HEADER, ""}; - [#http_bind{pid = FsmRef}] -> + {ok, #http_bind{pid = FsmRef}} -> gen_fsm:sync_send_all_state_event(FsmRef, {stop, close}), {200, ?HEADER, " mnesia:write( #http_bind{id = Sid, @@ -340,6 +359,7 @@ init([Sid, Key, IP]) -> %% {stop, Reason, NewStateData} %%---------------------------------------------------------------------- handle_event({become_controller, C2SPid}, StateName, StateData) -> + erlang:monitor(process, C2SPid), case StateData#state.input of cancel -> {next_state, StateName, StateData#state{ @@ -404,6 +424,14 @@ handle_sync_event({stop,close}, _From, _StateName, StateData) -> handle_sync_event({stop,stream_closed}, _From, _StateName, StateData) -> Reply = ok, {stop, normal, Reply, StateData}; +handle_sync_event(deactivate_socket, _From, StateName, StateData) -> + %% Input = case StateData#state.input of + %% cancel -> + %% queue:new(); + %% Q -> + %% Q + %% end, + {reply, ok, StateName, StateData#state{waiting_input = false}}; handle_sync_event({stop,Reason}, _From, _StateName, StateData) -> ?DEBUG("Closing bind session ~p - Reason: ~p", [StateData#state.id, Reason]), Reply = ok, @@ -537,6 +565,9 @@ handle_info({timeout, ShaperTimer, _}, StateName, #state{shaper_timer = ShaperTimer} = StateData) -> {next_state, StateName, StateData#state{shaper_timer = undefined}}; +handle_info({'DOWN', _MRef, process, C2SPid, _}, _StateName, + #state{waiting_input = C2SPid} = StateData) -> + {stop, normal, StateData}; handle_info(_, StateName, StateData) -> {next_state, StateName, StateData}. @@ -790,7 +821,7 @@ handle_http_put(Sid, Rid, Attrs, Payload, PayloadSize, StreamStart, IP) -> ?DEBUG("Trafic Shaper: Delaying request ~p", [Rid]), timer:sleep(Pause), %{200, ?HEADER, - % xml:element_to_string( + % xml:element_to_binary( % {xmlelement, "body", % [{"xmlns", ?NS_HTTP_BIND}, % {"type", "error"}], []})}; @@ -804,10 +835,10 @@ handle_http_put(Sid, Rid, Attrs, Payload, PayloadSize, StreamStart, IP) -> http_put(Sid, Rid, Attrs, Payload, PayloadSize, StreamStart, IP) -> ?DEBUG("Looking for session: ~p", [Sid]), - case mnesia:dirty_read({http_bind, Sid}) of - [] -> + case get_session(Sid) of + {error, _} -> {error, not_exists}; - [#http_bind{pid = FsmRef, hold=Hold, to={To, StreamVersion}}=Sess] -> + {ok, #http_bind{pid = FsmRef, hold=Hold, to={To, StreamVersion}}=Sess}-> NewStream = case StreamStart of true -> @@ -827,21 +858,21 @@ handle_http_put_error(Reason, #http_bind{pid=FsmRef, version=Version}) case Reason of not_exists -> {200, ?HEADER, - xml:element_to_string( + xml:element_to_binary( {xmlelement, "body", [{"xmlns", ?NS_HTTP_BIND}, {"type", "terminate"}, {"condition", "item-not-found"}], []})}; bad_key -> {200, ?HEADER, - xml:element_to_string( + xml:element_to_binary( {xmlelement, "body", [{"xmlns", ?NS_HTTP_BIND}, {"type", "terminate"}, {"condition", "item-not-found"}], []})}; polling_too_frequently -> {200, ?HEADER, - xml:element_to_string( + xml:element_to_binary( {xmlelement, "body", [{"xmlns", ?NS_HTTP_BIND}, {"type", "terminate"}, @@ -986,7 +1017,7 @@ prepare_outpacket_response(#http_bind{id=Sid, wait=Wait, MaxInactivity = get_max_inactivity(To, ?MAX_INACTIVITY), MaxPause = get_max_pause(To), {200, ?HEADER, - xml:element_to_string( + xml:element_to_binary( {xmlelement,"body", [{"xmlns", ?NS_HTTP_BIND}, @@ -1041,7 +1072,7 @@ send_outpacket(#http_bind{pid = FsmRef}, OutPacket) -> true -> TypedEls = [check_default_xmlns(OEl) || {xmlstreamelement, OEl} <- OutPacket], - Body = xml:element_to_string( + Body = xml:element_to_binary( {xmlelement,"body", [{"xmlns", ?NS_HTTP_BIND}], @@ -1075,7 +1106,7 @@ send_outpacket(#http_bind{pid = FsmRef}, OutPacket) -> StreamTail] end, {200, ?HEADER, - xml:element_to_string( + xml:element_to_binary( {xmlelement,"body", [{"xmlns", ?NS_HTTP_BIND}], @@ -1191,7 +1222,7 @@ set_inactivity_timer(_Pause, MaxInactivity) -> elements_to_string([]) -> []; elements_to_string([El | Els]) -> - xml:element_to_string(El) ++ elements_to_string(Els). + [xml:element_to_binary(El)|elements_to_string(Els)]. %% @spec (To, Default::integer()) -> integer() %% where To = [] | {Host::string(), Version::string()} @@ -1225,7 +1256,36 @@ check_default_xmlns({xmlelement, Name, Attrs, Els} = El) -> %% Print a warning in log file if this is not the case. check_bind_module(XmppDomain) -> case gen_mod:is_loaded(XmppDomain, mod_http_bind) of - true -> ok; + true -> true; false -> ?ERROR_MSG("You are trying to use BOSH (HTTP Bind), but the module mod_http_bind is not started.~n" - "Check your 'modules' section in your ejabberd configuration file.",[]) + "Check your 'modules' section in your ejabberd configuration file.",[]), + false + end. + +make_sid() -> + sha:sha(term_to_binary({now(), make_ref()})) + ++ "-" ++ ejabberd_cluster:node_id(). + +get_session(SID) -> + case string:tokens(SID, "-") of + [_, NodeID] -> + case ejabberd_cluster:get_node_by_id(NodeID) of + Node when Node == node() -> + case mnesia:dirty_read({http_bind, SID}) of + [] -> + {error, enoent}; + [Session] -> + {ok, Session} + end; + Node -> + case catch rpc:call(Node, mnesia, dirty_read, + [{http_bind, SID}], 5000) of + [Session] -> + {ok, Session}; + _ -> + {error, enoent} + end + end; + _ -> + {error, enoent} end. diff --git a/src/web/ejabberd_http_poll.erl b/src/web/ejabberd_http_poll.erl index 0bdbc6287..1a26418ea 100644 --- a/src/web/ejabberd_http_poll.erl +++ b/src/web/ejabberd_http_poll.erl @@ -77,9 +77,12 @@ %%% API %%%---------------------------------------------------------------------- start(ID, Key, IP) -> + update_tables(), mnesia:create_table(http_poll, [{ram_copies, [node()]}, + {local_content, true}, {attributes, record_info(fields, http_poll)}]), + mnesia:add_table_copy(http_poll, node(), ram_copies), supervisor:start_child(ejabberd_http_poll_sup, [ID, Key, IP]). start_link(ID, Key, IP) -> @@ -115,9 +118,9 @@ process([], #request{data = Data, {ok, ID1, Key, NewKey, Packet} -> ID = if (ID1 == "0") or (ID1 == "mobile") -> - NewID = sha:sha(term_to_binary({now(), make_ref()})), + NewID = make_sid(), {ok, Pid} = start(NewID, "", IP), - mnesia:transaction( + mnesia:async_dirty( fun() -> mnesia:write(#http_poll{id = NewID, pid = Pid}) @@ -350,7 +353,7 @@ handle_info(_, StateName, StateData) -> %% Returns: any %%---------------------------------------------------------------------- terminate(_Reason, _StateName, StateData) -> - mnesia:transaction( + mnesia:async_dirty( fun() -> mnesia:delete({http_poll, StateData#state.id}) end), @@ -375,19 +378,19 @@ terminate(_Reason, _StateName, StateData) -> %%%---------------------------------------------------------------------- http_put(ID, Key, NewKey, Packet) -> - case mnesia:dirty_read({http_poll, ID}) of - [] -> + case get_session(ID) of + {error, _} -> {error, not_exists}; - [#http_poll{pid = FsmRef}] -> + {ok, #http_poll{pid = FsmRef}} -> gen_fsm:sync_send_all_state_event( FsmRef, {http_put, Key, NewKey, Packet}) end. http_get(ID) -> - case mnesia:dirty_read({http_poll, ID}) of - [] -> + case get_session(ID) of + {error, _} -> {error, not_exists}; - [#http_poll{pid = FsmRef}] -> + {ok, #http_poll{pid = FsmRef}} -> gen_fsm:sync_send_all_state_event(FsmRef, http_get) end. @@ -446,3 +449,39 @@ get_jid(Type, ParsedPacket) -> false -> jlib:make_jid("","","") end. + +update_tables() -> + case catch mnesia:table_info(http_poll, local_content) of + false -> + mnesia:delete_table(http_poll); + _ -> + ok + end. + +make_sid() -> + sha:sha(term_to_binary({now(), make_ref()})) + ++ "-" ++ ejabberd_cluster:node_id(). + +get_session(SID) -> + case string:tokens(SID, "-") of + [_, NodeID] -> + case ejabberd_cluster:get_node_by_id(NodeID) of + Node when Node == node() -> + case mnesia:dirty_read({http_poll, SID}) of + [] -> + {error, enoent}; + [Session] -> + {ok, Session} + end; + Node -> + case catch rpc:call(Node, mnesia, dirty_read, + [{http_poll, SID}], 5000) of + [Session] -> + {ok, Session}; + _ -> + {error, enoent} + end + end; + _ -> + {error, enoent} + end. diff --git a/src/web/mod_http_bind.erl b/src/web/mod_http_bind.erl index 586b8eaaf..ad0c8f09e 100644 --- a/src/web/mod_http_bind.erl +++ b/src/web/mod_http_bind.erl @@ -134,7 +134,9 @@ setup_database() -> migrate_database(), mnesia:create_table(http_bind, [{ram_copies, [node()]}, - {attributes, record_info(fields, http_bind)}]). + {local_content, true}, + {attributes, record_info(fields, http_bind)}]), + mnesia:add_table_copy(http_bind, node(), ram_copies). migrate_database() -> case catch mnesia:table_info(http_bind, attributes) of @@ -144,4 +146,10 @@ migrate_database() -> %% Since the stored information is not important, instead %% of actually migrating data, let's just destroy the table mnesia:delete_table(http_bind) + end, + case catch mnesia:table_info(http_bind, local_content) of + false -> + mnesia:delete_table(http_bind); + _ -> + ok end. diff --git a/src/web/mod_http_fileserver.erl b/src/web/mod_http_fileserver.erl index 4f683ea91..ab4e1a5bd 100644 --- a/src/web/mod_http_fileserver.erl +++ b/src/web/mod_http_fileserver.erl @@ -66,11 +66,15 @@ headers }). +-ifdef(SSL40). +-define(STRING2LOWER, string). +-else. -ifdef(SSL39). -define(STRING2LOWER, string). -else. -define(STRING2LOWER, httpd_util). -endif. +-endif. -record(state, {host, docroot, accesslog, accesslogfd, directory_indices, custom_headers, default_content_type, content_types = []}). diff --git a/src/xml.c b/src/xml.c new file mode 100644 index 000000000..d1b2b7f44 --- /dev/null +++ b/src/xml.c @@ -0,0 +1,230 @@ +#include +#include +#include + +struct buf { + int limit; + int len; + unsigned char *b; +}; + +static int make_element(ErlNifEnv* env, struct buf *rbuf, ERL_NIF_TERM el); + +static struct buf *init_buf(ErlNifEnv* env) +{ + struct buf *rbuf = enif_alloc(env, sizeof(struct buf)); + rbuf->limit = 1024; + rbuf->len = 0; + rbuf->b = enif_alloc(env, rbuf->limit); + return rbuf; +} + +static void destroy_buf(ErlNifEnv* env, struct buf *rbuf) +{ + if (rbuf) { + if (rbuf->b) { + enif_free(env, rbuf->b); + }; + enif_free(env, rbuf); + }; +} + +inline void resize_buf(ErlNifEnv* env, struct buf *rbuf, int len_to_add) +{ + int new_len = rbuf->len + len_to_add; + + if (new_len >= rbuf->limit) { + rbuf->limit = ((new_len / 1024) + 1) * 1024; + rbuf->b = enif_realloc(env, rbuf->b, rbuf->limit); + }; +} + +static void buf_add_char(ErlNifEnv* env, struct buf *rbuf, unsigned char c) +{ + resize_buf(env, rbuf, 1); + (rbuf->b)[rbuf->len] = c; + rbuf->len += 1; +} + +static void buf_add_str(ErlNifEnv* env, struct buf *rbuf, char *data, int len) +{ + resize_buf(env, rbuf, len); + memcpy(rbuf->b + rbuf->len, data, len); + rbuf->len += len; +} + +inline void crypt(ErlNifEnv* env, struct buf *rbuf, unsigned char *data, int len) +{ + int i; + + for (i = 0; i < len; i++) { + switch (data[i]) { + case '&': + buf_add_str(env, rbuf, "&", 5); + break; + case '<': + buf_add_str(env, rbuf, "<", 4); + break; + case '>': + buf_add_str(env, rbuf, ">", 4); + break; + case '"': + buf_add_str(env, rbuf, """, 6); + break; + case '\'': + buf_add_str(env, rbuf, "'", 6); + break; + default: + buf_add_char(env, rbuf, data[i]); + break; + }; + }; +} + +static int make_elements(ErlNifEnv* env, struct buf *rbuf, ERL_NIF_TERM els) +{ + ERL_NIF_TERM head, tail; + int ret = 0; + + while (enif_get_list_cell(env, els, &head, &tail)) { + ret = make_element(env, rbuf, head); + if (ret) { + els = tail; + } else { + break; + }; + }; + + return ret; +} + +static int make_attrs(ErlNifEnv* env, struct buf *rbuf, ERL_NIF_TERM attrs) +{ + ErlNifBinary name, data; + ERL_NIF_TERM head, tail; + const ERL_NIF_TERM *tuple; + int arity, ret = 1; + + while (enif_get_list_cell(env, attrs, &head, &tail)) { + if (enif_get_tuple(env, head, &arity, &tuple)) { + if (arity == 2) { + if (enif_inspect_iolist_as_binary(env, tuple[0], &name) && + enif_inspect_iolist_as_binary(env, tuple[1], &data)) { + buf_add_char(env, rbuf, ' '); + buf_add_str(env, rbuf, (char *)name.data, name.size); + buf_add_str(env, rbuf, "='", 2); + crypt(env, rbuf, data.data, data.size); + buf_add_char(env, rbuf, '\''); + attrs = tail; + } else { + ret = 0; + break; + }; + } else { + ret = 0; + break; + }; + } else { + ret = 0; + break; + }; + }; + + return ret; +} + +static int make_element(ErlNifEnv* env, struct buf *rbuf, ERL_NIF_TERM el) +{ + ErlNifBinary cdata, name; + const ERL_NIF_TERM *tuple; + int arity, ret = 0; + + if (enif_get_tuple(env, el, &arity, &tuple)) { + if (arity == 2) { + if (!enif_compare(env, tuple[0], enif_make_atom(env, "xmlcdata"))) { + if (enif_inspect_iolist_as_binary(env, tuple[1], &cdata)) { + crypt(env, rbuf, cdata.data, cdata.size); + ret = 1; + }; + }; + }; + if (arity == 4) { + if (!enif_compare(env, tuple[0], enif_make_atom(env, "xmlelement"))) { + if (enif_inspect_iolist_as_binary(env, tuple[1], &name)) { + buf_add_char(env, rbuf, '<'); + buf_add_str(env, rbuf, (char *)name.data, name.size); + ret = make_attrs(env, rbuf, tuple[2]); + if (ret) { + if (enif_is_empty_list(env, tuple[3])) { + buf_add_str(env, rbuf, "/>", 2); + } else { + buf_add_char(env, rbuf, '>'); + ret = make_elements(env, rbuf, tuple[3]); + if (ret) { + buf_add_str(env, rbuf, "'); + }; + }; + }; + }; + }; + }; + }; + + return ret; +} + +static ERL_NIF_TERM element_to(ErlNifEnv* env, int argc, + const ERL_NIF_TERM argv[], + int as_string) +{ + ErlNifBinary output; + ERL_NIF_TERM result; + struct buf *rbuf; + + if (argc == 1) { + rbuf = init_buf(env); + if (make_element(env, rbuf, argv[0])) { + if (as_string) { + (rbuf->b)[rbuf->len] = 0; + result = enif_make_string(env, (char *) rbuf->b, ERL_NIF_LATIN1); + destroy_buf(env, rbuf); + return result; + } else { + if (enif_alloc_binary(env, rbuf->len, &output)) { + memcpy(output.data, rbuf->b, rbuf->len); + result = enif_make_binary(env, &output); + destroy_buf(env, rbuf); + return result; + }; + }; + }; + destroy_buf(env, rbuf); + }; + + return enif_make_badarg(env); +} + +/* static ERL_NIF_TERM element_to_string(ErlNifEnv* env, int argc, */ +/* const ERL_NIF_TERM argv[]) */ +/* { */ +/* return element_to(env, argc, argv, 1); */ +/* } */ + +static ERL_NIF_TERM element_to_binary(ErlNifEnv* env, int argc, + const ERL_NIF_TERM argv[]) +{ + return element_to(env, argc, argv, 0); +} + +static ErlNifFunc nif_funcs[] = + { + /* Stupid Erlang bug with enif_make_string() is fixed + in R14A only (OTP-8685), so we can't use + element_to_string yet.*/ + /* {"element_to_string", 1, element_to_string}, */ + {"element_to_binary", 1, element_to_binary} + }; + +ERL_NIF_INIT(xml, nif_funcs, NULL, NULL, NULL, NULL) diff --git a/src/xml.erl b/src/xml.erl index 9a9a7f833..22746b10a 100644 --- a/src/xml.erl +++ b/src/xml.erl @@ -37,8 +37,11 @@ get_subtag/2, get_subtag_cdata/2, append_subtags/2, get_path_s/2, + start/0, replace_tag_attr/3]). +-include("ejabberd.hrl"). + %% Select at compile time how to escape characters in binary text %% nodes. %% Can be choosen with ./configure --enable-full-xml @@ -48,6 +51,22 @@ -define(ESCAPE_BINARY(CData), crypt(CData)). -endif. +%% Replace element_to_binary/1 with NIF +%% Can be choosen with ./configure --enable-nif +-ifdef(NIF). +start() -> + SOPath = filename:join(ejabberd:get_so_path(), "xml"), + case catch erlang:load_nif(SOPath, 0) of + ok -> + ok; + Err -> + ?WARNING_MSG("unable to load xml NIF: ~p", [Err]) + end. +-else. +start() -> + ok. +-endif. + element_to_binary(El) -> iolist_to_binary(element_to_string(El)). diff --git a/src/xml_stream.erl b/src/xml_stream.erl index e97a61476..b98e3291b 100644 --- a/src/xml_stream.erl +++ b/src/xml_stream.erl @@ -31,6 +31,7 @@ new/2, parse/2, close/1, + change_callback_pid/2, parse_element/1]). -define(XML_START, 0). @@ -106,6 +107,8 @@ new(CallbackPid, MaxSize) -> size = 0, maxsize = MaxSize}. +change_callback_pid(State, CallbackPid) -> + State#xml_stream_state{callback_pid = CallbackPid}. parse(#xml_stream_state{callback_pid = CallbackPid, port = Port, From 987d796439094dfb3e7b420c99468fe46775e201 Mon Sep 17 00:00:00 2001 From: Christophe Romain Date: Tue, 13 Jul 2010 12:48:52 +0200 Subject: [PATCH 02/85] fix duplicated function --- src/ejabberd_s2s_out.erl | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/ejabberd_s2s_out.erl b/src/ejabberd_s2s_out.erl index 28eb4f1ae..5decc9408 100644 --- a/src/ejabberd_s2s_out.erl +++ b/src/ejabberd_s2s_out.erl @@ -52,7 +52,6 @@ handle_sync_event/4, handle_info/3, terminate/3, - print_state/1, code_change/4, test_get_addr_port/1, print_state/1, @@ -759,9 +758,6 @@ handle_event({closed, Timeout}, StateName, StateData) -> handle_event(_Event, StateName, StateData) -> {next_state, StateName, StateData, get_timeout_interval(StateName)}. -print_state(StateData) -> - StateData. - %%---------------------------------------------------------------------- %% Func: handle_sync_event/4 %% Returns: The associated StateData for this connection From 4862251f3467278648a4b92964125642b3520a09 Mon Sep 17 00:00:00 2001 From: Christophe Romain Date: Tue, 13 Jul 2010 13:32:56 +0200 Subject: [PATCH 03/85] Add gitignore --- .gitignore | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..5b89fb9d5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,31 @@ +Makefile +archives +.gitignore +contrib/extract_translations/extract_translations.beam +doc/contributed_modules.tex +doc/features.aux +doc/features.log +doc/features.out +doc/features.pdf +doc/guide.aux +doc/guide.idx +doc/guide.ilg +doc/guide.ind +doc/guide.log +doc/guide.out +doc/guide.pdf +doc/guide.toc +doc/version.aux +src/*.beam +src/*.so +src/eldap/eldap_filter_yecc.erl +src/XmppAddr.asn1db +src/XmppAddr.erl +src/XmppAddr.hrl +src/config.log +src/config.status +src/eldap/ELDAPv3.asn1db +src/eldap/ELDAPv3.beam +src/eldap/ELDAPv3.erl +src/eldap/ELDAPv3.hrl +src/epam From cc0503fd5ef9e5064008debbc89784fa28eeeb39 Mon Sep 17 00:00:00 2001 From: Christophe Romain Date: Tue, 13 Jul 2010 18:28:07 +0200 Subject: [PATCH 04/85] Add module to dump c2s connection --- src/ejabberd_c2s.erl | 101 +++++++++-------------- src/ejabberd_c2s.hrl | 62 ++++++++++++++ src/mod_c2s_debug.erl | 175 ++++++++++++++++++++++++++++++++++++++++ src/mod_caps.erl | 7 +- src/mod_ping.erl | 4 +- src/mod_privacy.hrl | 2 + src/mod_service_log.erl | 9 +-- 7 files changed, 289 insertions(+), 71 deletions(-) create mode 100644 src/ejabberd_c2s.hrl create mode 100644 src/mod_c2s_debug.erl diff --git a/src/ejabberd_c2s.erl b/src/ejabberd_c2s.erl index b25b0df83..afd3dd6ad 100644 --- a/src/ejabberd_c2s.erl +++ b/src/ejabberd_c2s.erl @@ -63,42 +63,7 @@ -include("ejabberd.hrl"). -include("jlib.hrl"). -include("mod_privacy.hrl"). - --define(SETS, gb_sets). --define(DICT, dict). - -%% pres_a contains all the presence available send (either through roster mechanism or directed). -%% Directed presence unavailable remove user from pres_a. --record(state, {socket, - sockmod, - socket_monitor, - xml_socket, - streamid, - sasl_state, - access, - shaper, - zlib = false, - tls = false, - tls_required = false, - tls_enabled = false, - tls_options = [], - authenticated = false, - jid, - user = "", server = ?MYNAME, resource = "", - sid, - pres_t = ?SETS:new(), - pres_f = ?SETS:new(), - pres_a = ?SETS:new(), - pres_i = ?SETS:new(), - pres_last, pres_pri, - pres_timestamp, - pres_invis = false, - privacy_list = #userlist{}, - conn = unknown, - auth_module = unknown, - ip, - fsm_limit_opts, - lang}). +-include("ejabberd_c2s.hrl"). %-define(DBGFSM, true). @@ -224,21 +189,21 @@ init([{SockMod, Socket}, Opts, FSMLimitOpts]) -> Socket end, SocketMonitor = SockMod:monitor(Socket1), - {ok, wait_for_stream, #state{socket = Socket1, - sockmod = SockMod, - socket_monitor = SocketMonitor, - xml_socket = XMLSocket, - zlib = Zlib, - tls = TLS, - tls_required = StartTLSRequired, - tls_enabled = TLSEnabled, - tls_options = TLSOpts, - streamid = new_id(), - access = Access, - shaper = Shaper, - ip = IP, - fsm_limit_opts = FSMLimitOpts}, - ?C2S_OPEN_TIMEOUT} + StateData = #state{socket = Socket1, + sockmod = SockMod, + socket_monitor = SocketMonitor, + xml_socket = XMLSocket, + zlib = Zlib, + tls = TLS, + tls_required = StartTLSRequired, + tls_enabled = TLSEnabled, + tls_options = TLSOpts, + streamid = new_id(), + access = Access, + shaper = Shaper, + ip = IP, + fsm_limit_opts = FSMLimitOpts}, + {ok, wait_for_stream, StateData, ?C2S_OPEN_TIMEOUT} end; init([StateName, StateData, _FSMLimitOpts]) -> MRef = (StateData#state.sockmod):monitor(StateData#state.socket), @@ -534,8 +499,7 @@ wait_for_auth({xmlstreamelement, El}, StateData) -> privacy_get_user_list, StateData#state.server, #userlist{}, [U, StateData#state.server]), - NewStateData = - StateData#state{ + NewStateData = StateData#state{ user = U, resource = R, jid = JID, @@ -545,7 +509,11 @@ wait_for_auth({xmlstreamelement, El}, StateData) -> pres_f = ?SETS:from_list(Fs1), pres_t = ?SETS:from_list(Ts1), privacy_list = PrivList}, - maybe_migrate(session_established, NewStateData); + DebugFlag = ejabberd_hooks:run_fold(c2s_debug_start_hook, + NewStateData#state.server, + false, + [self(), NewStateData]), + maybe_migrate(session_established, NewStateData#state{debug=DebugFlag}); _ -> ?INFO_MSG( "(~w) Failed legacy authentication for ~s", @@ -910,7 +878,11 @@ wait_for_session({xmlstreamelement, El}, StateData) -> pres_f = ?SETS:from_list(Fs1), pres_t = ?SETS:from_list(Ts1), privacy_list = PrivList}, - maybe_migrate(session_established, NewStateData); + DebugFlag = ejabberd_hooks:run_fold(c2s_debug_start_hook, + NewStateData#state.server, + false, + [self(), NewStateData]), + maybe_migrate(session_established, NewStateData#state{debug=DebugFlag}); _ -> ejabberd_hooks:run(forbidden_session_hook, StateData#state.server, [JID]), @@ -1026,7 +998,7 @@ session_established2(El, StateData) -> ejabberd_hooks:run( user_send_packet, Server, - [FromJID, ToJID, PresenceEl]), + [StateData#state.debug, FromJID, ToJID, PresenceEl]), case ToJID of #jid{user = User, server = Server, @@ -1042,13 +1014,17 @@ session_established2(El, StateData) -> "iq" -> case jlib:iq_query_info(NewEl) of #iq{xmlns = ?NS_PRIVACY} = IQ -> + ejabberd_hooks:run( + user_send_packet, + Server, + [StateData#state.debug, FromJID, ToJID, NewEl]), process_privacy_iq( FromJID, ToJID, IQ, StateData); _ -> ejabberd_hooks:run( user_send_packet, Server, - [FromJID, ToJID, NewEl]), + [StateData#state.debug, FromJID, ToJID, NewEl]), ejabberd_router:route( FromJID, ToJID, NewEl), StateData @@ -1056,7 +1032,7 @@ session_established2(El, StateData) -> "message" -> ejabberd_hooks:run(user_send_packet, Server, - [FromJID, ToJID, NewEl]), + [StateData#state.debug, FromJID, ToJID, NewEl]), check_privacy_route(FromJID, StateData, FromJID, ToJID, NewEl), StateData; @@ -1361,7 +1337,7 @@ handle_info({route, From, To, Packet}, StateName, StateData) -> send_element(StateData, FixedPacket), ejabberd_hooks:run(user_receive_packet, StateData#state.server, - [StateData#state.jid, From, To, FixedPacket]), + [StateData#state.debug, StateData#state.jid, From, To, FixedPacket]), ejabberd_hooks:run(c2s_loop_debug, [{route, From, To, Packet}]), fsm_next_state(StateName, NewState); true -> @@ -1419,13 +1395,16 @@ print_state(State = #state{pres_t = T, pres_f = F, pres_a = A, pres_i = I}) -> pres_a = {pres_a, ?SETS:size(A)}, pres_i = {pres_i, ?SETS:size(I)} }. - + %%---------------------------------------------------------------------- %% Func: terminate/3 %% Purpose: Shutdown the fsm %% Returns: any %%---------------------------------------------------------------------- terminate({migrated, ClonePid}, StateName, StateData) -> + ejabberd_hooks:run(c2s_debug_stop_hook, + StateData#state.server, + [self(), StateData]), if StateName == session_established -> ?INFO_MSG("(~w) Migrating ~s to ~p on node ~p", [StateData#state.socket, @@ -2149,7 +2128,7 @@ resend_offline_messages(#state{user = User, send_element(StateData, FixedPacket), ejabberd_hooks:run(user_receive_packet, StateData#state.server, - [StateData#state.jid, + [StateData#state.debug, StateData#state.jid, From, To, FixedPacket]); true -> ok diff --git a/src/ejabberd_c2s.hrl b/src/ejabberd_c2s.hrl new file mode 100644 index 000000000..485a6e400 --- /dev/null +++ b/src/ejabberd_c2s.hrl @@ -0,0 +1,62 @@ +%%%---------------------------------------------------------------------- +%%% +%%% ejabberd, Copyright (C) 2002-2010 ProcessOne +%%% +%%% This program is free software; you can redistribute it and/or +%%% modify it under the terms of the GNU General Public License as +%%% published by the Free Software Foundation; either version 2 of the +%%% License, or (at your option) any later version. +%%% +%%% This program is distributed in the hope that it will be useful, +%%% but WITHOUT ANY WARRANTY; without even the implied warranty of +%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +%%% General Public License for more details. +%%% +%%% You should have received a copy of the GNU General Public License +%%% along with this program; if not, write to the Free Software +%%% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +%%% 02111-1307 USA +%%% +%%%---------------------------------------------------------------------- + + +-ifndef(mod_privacy_hrl). +-include("mod_privacy.hrl"). +-endif. + +-define(SETS, gb_sets). +-define(DICT, dict). + +%% pres_a contains all the presence available send (either through roster mechanism or directed). +%% Directed presence unavailable remove user from pres_a. +-record(state, {socket, + sockmod, + socket_monitor, + xml_socket, + streamid, + sasl_state, + access, + shaper, + zlib = false, + tls = false, + tls_required = false, + tls_enabled = false, + tls_options = [], + authenticated = false, + jid, + user = "", server = ?MYNAME, resource = "", + sid, + pres_t = ?SETS:new(), + pres_f = ?SETS:new(), + pres_a = ?SETS:new(), + pres_i = ?SETS:new(), + pres_last, pres_pri, + pres_timestamp, + pres_invis = false, + privacy_list = #userlist{}, + conn = unknown, + auth_module = unknown, + ip, + fsm_limit_opts, + lang, + debug=false}). diff --git a/src/mod_c2s_debug.erl b/src/mod_c2s_debug.erl new file mode 100644 index 000000000..6bd2e6e76 --- /dev/null +++ b/src/mod_c2s_debug.erl @@ -0,0 +1,175 @@ +%% Usage: +%% In config file: +%% {mod_c2s_debug, [{logdir, "/tmp/xmpplogs"}]}, +%% From Erlang shell: +%% mod_c2s_debug:start("localhost", []). +%% mod_c2s_debug:stop("localhost"). +%% +%% Warning: Only one module for the debug handler can be defined. +-module(mod_c2s_debug). +-author('mremond@process-one.net'). + +-behaviour(gen_mod). +-behavior(gen_server). + +-export([start/2, start_link/2, stop/1, + debug_start/3, debug_stop/2, log_packet/4, log_packet/5]). +%% gen_server callbacks +-export([init/1, handle_call/3, handle_cast/2, handle_info/2, + terminate/2, code_change/3]). + +-include("ejabberd.hrl"). +-include("jlib.hrl"). +-include("ejabberd_c2s.hrl"). + +-record(modstate, {host, logdir, pid, iodevice}). +-record(clientinfo, {pid, jid, auth_module, ip}). + +-define(SUPERVISOR, ejabberd_sup). +-define(PROCNAME, c2s_debug). + +%%==================================================================== +%% gen_mod callbacks +%%==================================================================== +start(Host, Opts) -> + Proc = gen_mod:get_module_proc(Host, ?PROCNAME), + Spec = {Proc, {?MODULE, start_link, [Host, Opts]}, + transient, 2000, worker, [?MODULE]}, + supervisor:start_child(?SUPERVISOR, Spec). + +stop(Host) -> + Proc = gen_mod:get_module_proc(Host, ?PROCNAME), + gen_server:call(Proc, stop), + supervisor:delete_child(?SUPERVISOR, Proc). + +start_link(Host, Opts) -> + Proc = gen_mod:get_module_proc(Host, ?PROCNAME), + gen_server:start_link({local, Proc}, ?MODULE, [Host, Opts], []). + +%%==================================================================== +%% Hooks +%%==================================================================== + +%% Debug handled by another module... Do nothing: +debug_start(_Status, Pid, C2SState) -> + Host = C2SState#state.server, + Proc = gen_mod:get_module_proc(Host, ?PROCNAME), + + JID = jlib:jid_to_string(C2SState#state.jid), + AuthModule = C2SState#state.auth_module, + IP = C2SState#state.ip, + ClientInfo = #clientinfo{pid = Pid, jid = JID, auth_module = AuthModule, ip = IP}, + + gen_server:call(Proc, {debug_start, ClientInfo}). + +debug_stop(Pid, C2SState) -> + Host = C2SState#state.server, + Proc = gen_mod:get_module_proc(Host, ?PROCNAME), + gen_server:cast(Proc, {debug_stop, Pid}). + +log_packet(false, _FromJID, _ToJID, _Packet) -> + ok; +log_packet(true, FromJID, ToJID, Packet) -> + Host = FromJID#jid.lserver, + Proc = gen_mod:get_module_proc(Host, ?PROCNAME), + gen_server:cast(Proc, {addlog, {"Send", FromJID, ToJID, Packet}}). +log_packet(false, _JID, _FromJID, _ToJID, _Packet) -> + ok; +log_packet(true, JID, FromJID, ToJID, Packet) -> + Host = JID#jid.lserver, + Proc = gen_mod:get_module_proc(Host, ?PROCNAME), + gen_server:cast(Proc, {addlog, {"Receive", FromJID, ToJID, Packet}}). + +%%==================================================================== +%% gen_server callbacks +%%==================================================================== +init([Host, Opts]) -> + ?INFO_MSG("Starting c2s debug module for: ~p", [Host]), + MyHost = gen_mod:get_opt_host(Host, Opts, "c2s_debug.@HOST@"), + ejabberd_hooks:add(c2s_debug_start_hook, Host, + ?MODULE, debug_start, 50), + ejabberd_hooks:add(c2s_debug_stop_hook, Host, + ?MODULE, debug_stop, 50), + ejabberd_hooks:add(user_send_packet, Host, ?MODULE, log_packet, 50), + ejabberd_hooks:add(user_receive_packet, Host, ?MODULE, log_packet, 50), + + Logdir = gen_mod:get_opt(logdir, Opts, "/tmp/xmpplogs/"), + make_dir_rec(Logdir), + {ok, #modstate{host = MyHost, logdir = Logdir}}. + +terminate(_Reason, #modstate{host = Host}) -> + ?INFO_MSG("Stopping c2s debug module for: ~s", [Host]), + ejabberd_hooks:delete(c2s_debug_start_hook, Host, + ?MODULE, debug_start, 50), + ejabberd_hooks:delete(c2s_debug_stop_hook, Host, + ?MODULE, debug_stop, 50), + ejabberd_hooks:delete(user_send_packet, Host, ?MODULE, log_packet, 50). + +handle_call({debug_start, ClientInfo}, _From, #modstate{pid=undefined} = State) -> + Pid = ClientInfo#clientinfo.pid, + ?INFO_MSG("Debug started for PID:~p", [Pid]), + + JID = ClientInfo#clientinfo.jid, + AuthModule = ClientInfo#clientinfo.auth_module, + IP = ClientInfo#clientinfo.ip, + + {ok, IOD} = file:open(filename(State#modstate.logdir), [append]), + Line = io_lib:format("~s - Session open~nJID: ~s~nAuthModule: ~p~nIP: ~p~n", + [timestamp(), JID, AuthModule, IP]), + file:write(IOD, Line), + + {reply, true, State#modstate{pid = Pid, iodevice = IOD}}; +handle_call({debug_start, _ClientInfo}, _From, State) -> + {reply, false, State}; +handle_call(stop, _From, State) -> + {stop, normal, ok, State}; +handle_call(_Req, _From, State) -> + {reply, {error, badarg}, State}. + +handle_cast({addlog, _}, #modstate{iodevice=undefined} = State) -> + {noreply, State}; +handle_cast({addlog, {Direction, FromJID, ToJID, Packet}}, #modstate{iodevice=IOD} = State) -> + LogEntry = io_lib:format("=====~n~s - ~s~nFrom: ~s~nTo: ~s~n~s~n", [timestamp(), Direction, + jlib:jid_to_string(FromJID), + jlib:jid_to_string(ToJID), + xml:element_to_string(Packet)]), + file:write(IOD, LogEntry), + {noreply, State}; +handle_cast({debug_stop, Pid}, #modstate{pid=Pid, iodevice=IOD} = State) -> + Line = io_lib:format("=====~n~s - Session closed~n", + [timestamp()]), + file:write(IOD, Line), + + file:close(IOD), + {noreply, State#modstate{pid = undefined, iodevice=undefined}}; +handle_cast(_Msg, State) -> + {noreply, State}. + +handle_info(_Info, State) -> + {noreply, State}. + +code_change(_OldVsn, State, _Extra) -> + {ok, State}. + +%% Generate filename +filename(LogDir) -> + Filename = lists:flatten(timestamp()) ++ "-c2s.log", + filename:join([LogDir, Filename]). + +%% Generate timestamp +timestamp() -> + {Y,Mo,D} = erlang:date(), + {H,Mi,S} = erlang:time(), + io_lib:format("~4.4.0w~2.2.0w~2.2.0w-~2.2.0w~2.2.0w~2.2.0w", [Y,Mo,D,H,Mi,S]). + +%% Create dir recusively +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. diff --git a/src/mod_caps.erl b/src/mod_caps.erl index 7fb011ef9..dcd4145fe 100644 --- a/src/mod_caps.erl +++ b/src/mod_caps.erl @@ -53,7 +53,7 @@ ]). %% hook handlers --export([user_send_packet/3]). +-export([user_send_packet/4]). -include("ejabberd.hrl"). -include("jlib.hrl"). @@ -141,7 +141,8 @@ read_caps([], Result) -> %%==================================================================== %% Hooks %%==================================================================== -user_send_packet(#jid{luser = User, lserver = Server} = From, +user_send_packet(_DebugFlag, + #jid{luser = User, lserver = Server} = From, #jid{luser = User, lserver = Server, lresource = ""}, {xmlelement, "presence", Attrs, Els}) -> Type = xml:get_attr_s("type", Attrs), @@ -155,7 +156,7 @@ user_send_packet(#jid{luser = User, lserver = Server} = From, true -> ok end; -user_send_packet(_From, _To, _Packet) -> +user_send_packet(_DebugFlag, _From, _To, _Packet) -> ok. caps_stream_features(Acc, MyHost) -> diff --git a/src/mod_ping.erl b/src/mod_ping.erl index 80b6dac72..37b06dc98 100644 --- a/src/mod_ping.erl +++ b/src/mod_ping.erl @@ -51,7 +51,7 @@ handle_info/2, code_change/3]). %% Hook callbacks --export([iq_ping/3, user_online/3, user_offline/3, user_send/3]). +-export([iq_ping/3, user_online/3, user_offline/3, user_send/4]). -record(state, {host = "", send_pings = ?DEFAULT_SEND_PINGS, @@ -193,7 +193,7 @@ user_online(_SID, JID, _Info) -> user_offline(_SID, JID, _Info) -> stop_ping(JID#jid.lserver, JID). -user_send(JID, _From, _Packet) -> +user_send(_DebugFlag, JID, _From, _Packet) -> start_ping(JID#jid.lserver, JID). %%==================================================================== diff --git a/src/mod_privacy.hrl b/src/mod_privacy.hrl index 0e0b02b21..3f4489b10 100644 --- a/src/mod_privacy.hrl +++ b/src/mod_privacy.hrl @@ -19,6 +19,8 @@ %%% %%%---------------------------------------------------------------------- +-define(mod_privacy_hrl, true). + -record(privacy, {us, default = none, lists = []}). diff --git a/src/mod_service_log.erl b/src/mod_service_log.erl index 8d33ac4d8..44fcfd25c 100644 --- a/src/mod_service_log.erl +++ b/src/mod_service_log.erl @@ -31,8 +31,8 @@ -export([start/2, stop/1, - log_user_send/3, - log_user_receive/4]). + log_user_send/4, + log_user_receive/5]). -include("ejabberd.hrl"). -include("jlib.hrl"). @@ -51,10 +51,10 @@ stop(Host) -> ?MODULE, log_user_receive, 50), ok. -log_user_send(From, To, Packet) -> +log_user_send(_DebugFlag, From, To, Packet) -> log_packet(From, To, Packet, From#jid.lserver). -log_user_receive(_JID, From, To, Packet) -> +log_user_receive(_DebugFlag, _JID, From, To, Packet) -> log_packet(From, To, Packet, To#jid.lserver). @@ -74,4 +74,3 @@ log_packet(From, To, {xmlelement, Name, Attrs, Els}, Host) -> luser = "", lserver = Logger, lresource = ""}, {xmlelement, "route", [], [FixedPacket]}) end, Loggers). - From 091b4568d5e65b826f40ab56c3b73a7e395106ca Mon Sep 17 00:00:00 2001 From: Christophe Romain Date: Tue, 13 Jul 2010 18:40:16 +0200 Subject: [PATCH 05/85] Add module to log informations when Mnesia is overloaded, and also supports rate limitation --- src/mod_mnesia_mngt.erl | 147 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 147 insertions(+) create mode 100644 src/mod_mnesia_mngt.erl diff --git a/src/mod_mnesia_mngt.erl b/src/mod_mnesia_mngt.erl new file mode 100644 index 000000000..0c5ad1d36 --- /dev/null +++ b/src/mod_mnesia_mngt.erl @@ -0,0 +1,147 @@ +%% Usage: +%% In config file: +%% {mod_mnesia_mgmt, [{logdir, "/tmp/xmpplogs/"}]}, +%% From Erlang shell: +%% mod_mnesia_mgmt:start("localhost", []). +%% mod_mnesia_mgmt:stop("localhost"). + +-module(mod_mnesia_mngt). +-author('mremond@process-one.net'). + +-behaviour(gen_mod). +-behavior(gen_server). + +-export([start/2, start_link/2, stop/1]). + +%% gen_server callbacks +-export([init/1, handle_call/3, handle_cast/2, handle_info/2, + terminate/2, code_change/3]). + +-include("ejabberd.hrl"). +-include("jlib.hrl"). + +-record(modstate, {host, logdir, iodevice, timer}). + +-define(SUPERVISOR, ejabberd_sup). +-define(PROCNAME, mod_mnesia_mgmt). + +-define(STANDARD_ACCEPT_INTERVAL, 20). %% accept maximum one new connection every 20ms +-define(ACCEPT_INTERVAL, 200). %% This is used when Mnesia is overloaded +-define(RATE_LIMIT_DURATION, 120000). %% Time during which the rate limitation need to be maintained + +%%==================================================================== +%% gen_mod callbacks +%%==================================================================== +start(Host, Opts) -> + Proc = gen_mod:get_module_proc(Host, ?PROCNAME), + Spec = {Proc, {?MODULE, start_link, [Host, Opts]}, + transient, 2000, worker, [?MODULE]}, + supervisor:start_child(?SUPERVISOR, Spec). + +stop(Host) -> + Proc = gen_mod:get_module_proc(Host, ?PROCNAME), + gen_server:call(Proc, stop), + supervisor:delete_child(?SUPERVISOR, Proc). + +start_link(Host, Opts) -> + Proc = gen_mod:get_module_proc(Host, ?PROCNAME), + gen_server:start_link({local, Proc}, ?MODULE, [Host, Opts], []). + +%%==================================================================== +%% gen_server callbacks +%%==================================================================== +init([Host, Opts]) -> + ?INFO_MSG("Starting mod_mnesia_mgmt for: ~p", [Host]), + ejabberd_listener:rate_limit([5222, 5223], ?STANDARD_ACCEPT_INTERVAL), + MyHost = gen_mod:get_opt_host(Host, Opts, "mnesia_mngt.@HOST@"), + + Logdir = gen_mod:get_opt(logdir, Opts, "/tmp/xmpplogs/"), + make_dir_rec(Logdir), + {ok, IOD} = file:open(filename(Logdir), [append]), + + mnesia:subscribe(system), + + {ok, #modstate{host = MyHost, logdir = Logdir, iodevice = IOD}}. + +terminate(_Reason, #modstate{host = Host, iodevice = IOD}) -> + ?INFO_MSG("Stopping mod_mnesia_mgmt for: ~s", [Host]), + mnesia:unsubscribe(system), + file:close(IOD). + +handle_call(stop, _From, State) -> + {stop, normal, ok, State}; +handle_call(_Req, _From, State) -> + {reply, {error, badarg}, State}. + +handle_cast(_Msg, State) -> + {noreply, State}. + +handle_info({mnesia_system_event,{mnesia_overload, {mnesia_tm, message_queue_len, Values}}}, + #modstate{iodevice = IOD, timer = Timer} = State) -> + Line = io_lib:format("~s - Mnesia overload due to message queue length (~p)", + [timestamp(), Values]), + file:write(IOD, Line), + reset_timer(Timer), + + {messages, Messages} = process_info(whereis(mnesia_tm), messages), + log_messages(IOD, Messages, 20), + {noreply, State#modstate{timer = undefined}}; +handle_info({mnesia_system_event,{mnesia_overload, Details}}, + #modstate{iodevice = IOD, timer = Timer} = State) -> + Line = io_lib:format("~s - Mnesia overload: ~p", + [timestamp(), Details]), + file:write(IOD, Line), + reset_timer(Timer), + {noreply, State}; +handle_info({mnesia_system_event, _Event}, State) -> + %% TODO: More event to handle + {noreply, State}; +handle_info(_Info, State) -> + {noreply, State}. + +code_change(_OldVsn, State, _Extra) -> + {ok, State}. + +%% Generate filename +filename(LogDir) -> + Filename = lists:flatten(timestamp()) ++ "-mnesia.log", + filename:join([LogDir, Filename]). + +%% Generate timestamp +timestamp() -> + {Y,Mo,D} = erlang:date(), + {H,Mi,S} = erlang:time(), + io_lib:format("~4.4.0w~2.2.0w~2.2.0w-~2.2.0w~2.2.0w~2.2.0w", [Y,Mo,D,H,Mi,S]). + +%% Create dir recusively +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. + +%% Write first messages to log file +log_messages(_IOD, _Messages, 0) -> + ok; +log_messages(_IOD, [], _N) -> + ok; +log_messages(IOD, [Message|Messages], N) -> + Line = io_lib:format("** ~w", + [Message]), + file:write(IOD, Line), + log_messages(IOD, Messages, N-1). + +reset_timer(Timer) -> + cancel_timer(Timer), + ejabberd_listener:rate_limit([5222, 5223], ?ACCEPT_INTERVAL), + timer:apply_after(?RATE_LIMIT_DURATION, ejabberd_listener, rate_limit, [[5222, 5223], ?STANDARD_ACCEPT_INTERVAL]). + +cancel_timer(undefined) -> + ok; +cancel_timer(Timer) -> + timer:cancel(Timer). From 7d37715f8be9441b9bdd402794bc26980fa53601 Mon Sep 17 00:00:00 2001 From: Christophe Romain Date: Tue, 13 Jul 2010 19:00:49 +0200 Subject: [PATCH 06/85] Add rate limit command to ejabberd_listener. You can now limit the max number of TCP connects per second on a given port. (thanks to Mickael Remond) --- src/ejabberd_listener.erl | 46 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 43 insertions(+), 3 deletions(-) diff --git a/src/ejabberd_listener.erl b/src/ejabberd_listener.erl index a179dfda4..0465dedba 100644 --- a/src/ejabberd_listener.erl +++ b/src/ejabberd_listener.erl @@ -35,7 +35,8 @@ stop_listener/2, parse_listener_portip/2, add_listener/3, - delete_listener/2 + delete_listener/2, + rate_limit/2 ]). -include("ejabberd.hrl"). @@ -225,6 +226,9 @@ get_ip_tuple(IPOpt, _IPVOpt) -> IPOpt. accept(ListenSocket, Module, Opts) -> + accept(ListenSocket, Module, Opts, 0). +accept(ListenSocket, Module, Opts, Interval) -> + NewInterval = check_rate_limit(Interval), case gen_tcp:accept(ListenSocket) of {ok, Socket} -> case {inet:sockname(Socket), inet:peername(Socket)} of @@ -239,11 +243,11 @@ accept(ListenSocket, Module, Opts) -> false -> ejabberd_socket end, CallMod:start(strip_frontend(Module), gen_tcp, Socket, Opts), - accept(ListenSocket, Module, Opts); + accept(ListenSocket, Module, Opts, NewInterval); {error, Reason} -> ?INFO_MSG("(~w) Failed TCP accept: ~w", [ListenSocket, Reason]), - accept(ListenSocket, Module, Opts) + accept(ListenSocket, Module, Opts, NewInterval) end. udp_recv(Socket, Module, Opts) -> @@ -471,3 +475,39 @@ format_error(Reason) -> ReasonStr -> ReasonStr end. + +%% Set interval between two accepts on given port +rate_limit([], _Interval) -> + ok; +rate_limit([Port|Ports], Interval) -> + rate_limit(Port, Interval), + rate_limit(Ports, Interval); +rate_limit(Port, Interval) -> + case get_listener_pid_by_port(Port) of + undefined -> no_listener; + Pid -> Pid ! {rate_limit, Interval}, ok + end. + +get_listener_pid_by_port(Port) -> + ListenerPids = [Pid || {{P,_,_},Pid,_,_} <- + supervisor:which_children(erlang:whereis(ejabberd_listeners)), + P == Port], + ListenerPid = case ListenerPids of + [] -> undefined; + [LPid|_] -> LPid + end, + ListenerPid. + +check_rate_limit(Interval) -> + NewInterval = receive + {rate_limit, AcceptInterval} -> + AcceptInterval + after 0 -> + Interval + end, + case NewInterval of + 0 -> ok; + Ms -> + timer:sleep(Ms) + end, + NewInterval. From cc1839a250adca6be32b510e143eee88b97076e8 Mon Sep 17 00:00:00 2001 From: Christophe Romain Date: Tue, 13 Jul 2010 19:06:12 +0200 Subject: [PATCH 07/85] Try forcing usage of cache for all MySQL sessions, and add correct timeout on odbc driver query. (thanks to Mickael Remond) --- src/odbc/ejabberd_odbc.erl | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/odbc/ejabberd_odbc.erl b/src/odbc/ejabberd_odbc.erl index 1b07fd6d9..7a5a25955 100644 --- a/src/odbc/ejabberd_odbc.erl +++ b/src/odbc/ejabberd_odbc.erl @@ -39,7 +39,8 @@ sql_bloc/2, escape/1, escape_like/1, - keep_alive/1]). + keep_alive/1, + sql_query_on_all_connections/2]). %% gen_fsm callbacks -export([init/1, @@ -97,6 +98,13 @@ start_link(Host, StartInterval) -> sql_query(Host, Query) -> sql_call(Host, {sql_query, Query}). +%% Issue an SQL query on all the connections +sql_query_on_all_connections(Host, Query) -> + F = fun(Pid) -> ?GEN_FSM:sync_send_event(Pid, {sql_cmd, + {sql_query, Query}, + erlang:now()}, ?TRANSACTION_TIMEOUT) end, + lists:map(F, ejabberd_odbc_sup:get_pids(Host)). + %% SQL transaction based on a list of queries %% This function automatically sql_transaction(Host, Queries) when is_list(Queries) -> @@ -420,13 +428,15 @@ sql_query_internal(Query) -> State = get(?STATE_KEY), Res = case State#state.db_type of odbc -> - odbc:sql_query(State#state.db_ref, Query); + odbc:sql_query(State#state.db_ref, Query, ?TRANSACTION_TIMEOUT - 1000); pgsql -> + %% TODO: We need to propagate the TRANSACTION_TIMEOUT to pgsql driver, but no yet supported in driver. + %% See EJAB-1266 pgsql_to_odbc(pgsql:squery(State#state.db_ref, Query)); mysql -> ?DEBUG("MySQL, Send query~n~p~n", [Query]), R = mysql_to_odbc(mysql_conn:fetch(State#state.db_ref, - Query, self())), + Query, self(), ?TRANSACTION_TIMEOUT - 1000)), %% ?INFO_MSG("MySQL, Received result~n~p~n", [R]), R end, @@ -500,6 +510,7 @@ mysql_connect(Server, Port, DB, Username, Password) -> case mysql_conn:start(Server, Port, Username, Password, DB, fun log/3) of {ok, Ref} -> mysql_conn:fetch(Ref, ["set names 'utf8';"], self()), + mysql_conn:fetch(Ref, ["SET SESSION query_cache_type=1;"], self()), {ok, Ref}; Err -> Err From d0b7cd599be00f02b62d16aa28f9a72bc62fa374 Mon Sep 17 00:00:00 2001 From: Christophe Romain Date: Tue, 13 Jul 2010 21:48:36 +0200 Subject: [PATCH 08/85] Make chat room destroy and create being sync_dirty to limit mnesia overload. (thanks to Mickael Remond) --- src/mod_muc/mod_muc.erl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/mod_muc/mod_muc.erl b/src/mod_muc/mod_muc.erl index 89f815670..c2af1ff83 100644 --- a/src/mod_muc/mod_muc.erl +++ b/src/mod_muc/mod_muc.erl @@ -306,7 +306,7 @@ handle_info({room_destroyed, RoomHost, Pid}, State) -> mnesia:delete_object(#muc_online_room{name_host = RoomHost, pid = Pid}) end, - mnesia:async_dirty(F), + mnesia:sync_dirty(F), {noreply, State}; handle_info(_Info, State) -> {noreply, State}. @@ -603,7 +603,7 @@ register_room(Host, Room, Pid) -> mnesia:write(#muc_online_room{name_host = {Room, Host}, pid = Pid}) end, - mnesia:async_dirty(F). + mnesia:sync_dirty(F). iq_disco_info(Lang) -> [{xmlelement, "identity", From 28c4c8795661051c0a557ecfa732da4dd4e09e1a Mon Sep 17 00:00:00 2001 From: Christophe Romain Date: Tue, 13 Jul 2010 21:54:46 +0200 Subject: [PATCH 09/85] Added catches to reset_stream calls to avoid errors during a race condition (thanks to Aleksey Shchepin) --- src/ejabberd_c2s.erl | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/ejabberd_c2s.erl b/src/ejabberd_c2s.erl index afd3dd6ad..3bb12dc4b 100644 --- a/src/ejabberd_c2s.erl +++ b/src/ejabberd_c2s.erl @@ -580,8 +580,8 @@ wait_for_feature_request({xmlstreamelement, El}, StateData) -> Mech, ClientIn) of {ok, Props} -> - (StateData#state.sockmod):reset_stream( - StateData#state.socket), + catch (StateData#state.sockmod):reset_stream( + StateData#state.socket), send_element(StateData, {xmlelement, "success", [{"xmlns", ?NS_SASL}], []}), @@ -716,8 +716,8 @@ wait_for_sasl_response({xmlstreamelement, El}, StateData) -> case cyrsasl:server_step(StateData#state.sasl_state, ClientIn) of {ok, Props} -> - (StateData#state.sockmod):reset_stream( - StateData#state.socket), + catch (StateData#state.sockmod):reset_stream( + StateData#state.socket), send_element(StateData, {xmlelement, "success", [{"xmlns", ?NS_SASL}], []}), From bf63d09d802ab277fa227b714b9d237e8daa32e4 Mon Sep 17 00:00:00 2001 From: Christophe Romain Date: Fri, 16 Jul 2010 16:50:50 +0200 Subject: [PATCH 10/85] Add etop command to ejabberdctl (TECH-1109) --- src/ejabberdctl.template | 8 +++ src/etop_tr.erl | 130 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 138 insertions(+) create mode 100644 src/etop_tr.erl diff --git a/src/ejabberdctl.template b/src/ejabberdctl.template index fecdecc86..9b292da20 100644 --- a/src/ejabberdctl.template +++ b/src/ejabberdctl.template @@ -210,6 +210,13 @@ live () $ERLANG_OPTS $ARGS \"$@\"" } +etop() +{ + $EXEC_CMD "$ERL \ + $NAME debug-${TTY}-${ERLANG_NODE} \ + -hidden -s etop -s erlang halt -output text -node $ERLANG_NODE" +} + help () { echo "" @@ -359,6 +366,7 @@ case $ARGS in ' start') start;; ' debug') debug;; ' live') live;; + ' etop') etop;; ' started') wait_for_status 0 30 2;; # wait 30x2s before timeout ' stopped') wait_for_status 3 15 2; stop_epmd;; # wait 15x2s before timeout *) ctl $ARGS;; diff --git a/src/etop_tr.erl b/src/etop_tr.erl new file mode 100644 index 000000000..c5ae79cc0 --- /dev/null +++ b/src/etop_tr.erl @@ -0,0 +1,130 @@ +%% +%% %CopyrightBegin% +%% +%% Copyright Ericsson AB 2002-2009. All Rights Reserved. +%% +%% The contents of this file are subject to the Erlang Public License, +%% Version 1.1, (the "License"); you may not use this file except in +%% compliance with the License. You should have received a copy of the +%% Erlang Public License along with this software. If not, it can be +%% retrieved online at http://www.erlang.org/. +%% +%% Software distributed under the License is distributed on an "AS IS" +%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See +%% the License for the specific language governing rights and limitations +%% under the License. +%% +%% %CopyrightEnd% +%% +-module(etop_tr). +-author('siri@erix.ericsson.se'). + +%%-compile(export_all). +-export([setup_tracer/1,stop_tracer/1,reader/1]). +-import(etop,[getopt/2]). + +-include("etop_defs.hrl"). + +setup_tracer(Config) -> + TraceNode = getopt(node,Config), + RHost = rpc:call(TraceNode, net_adm, localhost, []), + Store = ets:new(?MODULE, [set, public]), + + %% We can only trace one process anyway kill the old one. + case erlang:whereis(dbg) of + undefined -> + case rpc:call(TraceNode, erlang, whereis, [dbg]) of + undefined -> fine; + Pid -> + exit(Pid, kill) + end; + Pid -> + exit(Pid,kill) + end, + + dbg:tracer(TraceNode,port,dbg:trace_port(ip,{getopt(port,Config),5000})), + dbg:p(all,[running,timestamp]), + T = dbg:get_tracer(TraceNode), + Config#opts{tracer=T,host=RHost,store=Store}. + +stop_tracer(_Config) -> + dbg:p(all,clear), + dbg:stop(), + ok. + + + +reader(Config) -> + Host = getopt(host, Config), + Port = getopt(port, Config), + + {ok, Sock} = gen_tcp:connect(Host, Port, [{active, false}]), + spawn_link(fun() -> reader_init(Sock,getopt(store,Config),nopid) end). + + +%%%%%%%%%%%%%% Socket reader %%%%%%%%%%%%%%%%%%%%%%%%%%% + +reader_init(Sock, Store, Last) -> + process_flag(priority, high), + reader(Sock, Store, Last). + +reader(Sock, Store, Last) -> + Data = get_data(Sock), + New = handle_data(Last, Data, Store), + reader(Sock, Store, New). + +handle_data(_, {_, Pid, in, _, Time}, _) -> + {Pid,Time}; +handle_data({Pid,Time1}, {_, Pid, out, _, Time2}, Store) -> + Elapsed = elapsed(Time1, Time2), + case ets:member(Store,Pid) of + true -> ets:update_counter(Store, Pid, Elapsed); + false -> ets:insert(Store,{Pid,Elapsed}) + end, + nopid; +handle_data(_W, {drop, D}, _) -> %% Error case we are missing data here! + io:format("Erlang top dropped data ~p~n", [D]), + nopid; +handle_data(nopid, {_, _, out, _, _}, _Store) -> + %% ignore - there was probably just a 'drop' + nopid; +handle_data(_, G, _) -> + %% io:format("Erlang top got garbage ~p~n", [G]), + nopid. + +elapsed({Me1, S1, Mi1}, {Me2, S2, Mi2}) -> + Me = (Me2 - Me1) * 1000000, + S = (S2 - S1 + Me) * 1000000, + Mi2 - Mi1 + S. + + +%%%%%% Socket helpers %%%% +get_data(Sock) -> + [Op | BESiz] = my_ip_read(Sock, 5), + Siz = get_be(BESiz), + case Op of + 0 -> + B = list_to_binary(my_ip_read(Sock, Siz)), + binary_to_term(B); + 1 -> + {drop, Siz}; + Else -> + exit({'bad trace tag', Else}) + end. + +get_be([A,B,C,D]) -> + A * 16777216 + B * 65536 + C * 256 + D. + +my_ip_read(Sock,N) -> + case gen_tcp:recv(Sock, N) of + {ok, Data} -> + case length(Data) of + N -> + Data; + X -> + Data ++ my_ip_read(Sock, N - X) + end; + _Else -> + exit(eof) + end. + From 2ee764281615604ad7fc3ce65ccf417e1d53d4cf Mon Sep 17 00:00:00 2001 From: Christophe Romain Date: Fri, 16 Jul 2010 18:57:00 +0200 Subject: [PATCH 11/85] add missing hrl --- src/etop_defs.hrl | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 src/etop_defs.hrl diff --git a/src/etop_defs.hrl b/src/etop_defs.hrl new file mode 100644 index 000000000..664de6197 --- /dev/null +++ b/src/etop_defs.hrl @@ -0,0 +1,29 @@ +%% +%% %CopyrightBegin% +%% +%% Copyright Ericsson AB 2002-2009. All Rights Reserved. +%% +%% The contents of this file are subject to the Erlang Public License, +%% Version 1.1, (the "License"); you may not use this file except in +%% compliance with the License. You should have received a copy of the +%% Erlang Public License along with this software. If not, it can be +%% retrieved online at http://www.erlang.org/. +%% +%% Software distributed under the License is distributed on an "AS IS" +%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See +%% the License for the specific language governing rights and limitations +%% under the License. +%% +%% %CopyrightEnd% +%% +-define(SYSFORM, + " ~-72w~10s~n" + " Load: cpu ~8w Memory: total ~8w binary ~8w~n" + " procs~8w processes~8w code ~8w~n" + " runq ~8w atom ~8w ets ~8w~n"). + +-record(opts, {node=node(), port = 8415, accum = false, intv = 5000, lines = 10, + width = 700, height = 340, sort = runtime, tracing = on, + %% Other state information + out_mod=etop_gui, out_proc, server, host, tracer, store, + accum_tab, remote}). From 3aaebe98f4a38236ad2cee4d75e0e4e95307c65c Mon Sep 17 00:00:00 2001 From: Christophe Romain Date: Tue, 20 Jul 2010 14:06:48 +0200 Subject: [PATCH 12/85] add ejabberdctl ability to check epmd names (TECH-1121) --- src/ejabberdctl.template | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/ejabberdctl.template b/src/ejabberdctl.template index 9b292da20..a1e7902c7 100644 --- a/src/ejabberdctl.template +++ b/src/ejabberdctl.template @@ -136,6 +136,7 @@ export EXEC_CMD # start server start () { + check_start $EXEC_CMD "$ERL \ $NAME $ERLANG_NODE \ -noinput -detached \ @@ -182,6 +183,7 @@ debug () # start interactive server live () { + check_start echo "--------------------------------------------------------------------" echo "" echo "IMPORTANT: ejabberd is going to start in LIVE (interactive) mode." @@ -337,6 +339,26 @@ stop_epmd() epmd -names | grep -q name || epmd -kill } +# make sure node not already running and node name unregistered +check_start() +{ + epmd -names | grep -q $NODE && { + ps ux | grep -q $ERLANG_NODE && { + echo "ejabberd is already running." + exit 4 + } || { + ps ux | grep beam | grep -v "grep beam" && { + echo "ejabberd node is registered, but no ejabberd process has been found." + echo "can not kill epmd as other erlang nodes are running." + echo "please stop all erlang nodes, and call 'epmd -kill'." + exit 5 + } || { + epmd -kill + } + } + } +} + # allow sync calls wait_for_status() { From 2d1c416dafc5fe18b725eaaabb1241d89324311f Mon Sep 17 00:00:00 2001 From: Christophe Romain Date: Thu, 22 Jul 2010 11:03:07 +0200 Subject: [PATCH 13/85] Allow roster change from external component (TECH-1001) --- src/ejabberd_c2s.erl | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/src/ejabberd_c2s.erl b/src/ejabberd_c2s.erl index 3bb12dc4b..f48f897e9 100644 --- a/src/ejabberd_c2s.erl +++ b/src/ejabberd_c2s.erl @@ -42,6 +42,9 @@ get_presence/1, get_subscribed/1]). +%% API: +-export([add_rosteritem/3, del_rosteritem/2]). + %% gen_fsm callbacks -export([init/1, wait_for_stream/2, @@ -127,6 +130,12 @@ socket_type() -> get_presence(FsmRef) -> ?GEN_FSM:sync_send_all_state_event(FsmRef, {get_presence}, 1000). +add_rosteritem(FsmRef, IJID, ISubscription) -> + ?GEN_FSM:send_all_state_event(FsmRef, {add_rosteritem, IJID, ISubscription}). + +del_rosteritem(FsmRef, IJID) -> + ?GEN_FSM:send_all_state_event(FsmRef, {del_rosteritem, IJID}). + stop(FsmRef) -> ?GEN_FSM:send_event(FsmRef, closed). @@ -1066,6 +1075,15 @@ session_established2(El, StateData) -> %%---------------------------------------------------------------------- handle_event({migrate, Node, After}, StateName, StateData) when Node /= node() -> fsm_migrate(StateName, StateData, Node, After * 2); + +handle_event({add_rosteritem, IJID, ISubscription}, StateName, StateData) -> + NewStateData = roster_change(IJID, ISubscription, StateData), + fsm_next_state(StateName, NewStateData); + +handle_event({del_rosteritem, IJID}, StateName, StateData) -> + NewStateData = roster_change(IJID, none, StateData), + fsm_next_state(StateName, NewStateData); + handle_event(_Event, StateName, StateData) -> fsm_next_state(StateName, StateData). @@ -1978,7 +1996,8 @@ roster_change(IJID, ISubscription, StateData) -> P -> ?DEBUG("roster changed for ~p~n", [StateData#state.user]), From = StateData#state.jid, - To = jlib:make_jid(IJID), +% To = jlib:make_jid(IJID) + To = IJID, Cond1 = (not StateData#state.pres_invis) and IsFrom and (not OldIsFrom), Cond2 = (not IsFrom) and OldIsFrom From 59ae9bea7635157ecf8653c17f1211a551c2a563 Mon Sep 17 00:00:00 2001 From: Christophe Romain Date: Thu, 5 Aug 2010 14:23:26 +0200 Subject: [PATCH 14/85] added p1 modules --- src/http_p1.erl | 337 +++++++++++ src/mod_admin_p1.erl | 1166 ++++++++++++++++++++++++++++++++++++++ src/mod_ip_blacklist.erl | 2 +- src/mod_xmlrpc.erl | 875 ++++++++++++++++++++++++++++ 4 files changed, 2379 insertions(+), 1 deletion(-) create mode 100644 src/http_p1.erl create mode 100644 src/mod_admin_p1.erl create mode 100644 src/mod_xmlrpc.erl diff --git a/src/http_p1.erl b/src/http_p1.erl new file mode 100644 index 000000000..1a8a1e630 --- /dev/null +++ b/src/http_p1.erl @@ -0,0 +1,337 @@ +%%%---------------------------------------------------------------------- +%%% File : http_p1.erl +%%% Author : Emilio Bustos +%%% Purpose : Provide a common API for inets / lhttpc / ibrowse +%%% Created : 29 Jul 2010 by Emilio Bustos +%%% +%%% +%%% ejabberd, Copyright (C) 2002-2010 ProcessOne +%%% +%%% This program is free software; you can redistribute it and/or +%%% modify it under the terms of the GNU General Public License as +%%% published by the Free Software Foundation; either version 2 of the +%%% License, or (at your option) any later version. +%%% +%%% This program is distributed in the hope that it will be useful, +%%% but WITHOUT ANY WARRANTY; without even the implied warranty of +%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +%%% General Public License for more details. +%%% +%%% You should have received a copy of the GNU General Public License +%%% along with this program; if not, write to the Free Software +%%% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +%%% 02111-1307 USA +%%% +%%%---------------------------------------------------------------------- + +-module(http_p1). +-author('ebustos@process-one.net'). + +-export([ + start/0, + stop/0, + get/1, + get/2, + post/2, + post/3, + request/3, + request/4, + request/5 +]). + +% -define(USE_INETS, 1). +% -define(USE_LHTTPC, 1). +% -define(USE_IBROWSE, 1). +% inets used as default if none specified + +-ifdef(USE_IBROWSE). + -define(start(), start_ibrowse()). + -define(request(M, U, H, B, O), request_ibrowse(M, U, H, B, O)). + -define(stop(), stop_ibrowse()). +-else. + -ifdef(USE_LHTTPC). + -define(start(), start_lhttpc()). + -define(request(M, U, H, B, O), request_lhttpc(M, U, H, B, O)). + -define(stop(), stop_lhttpc()). + -else. + -define(start(), start_inets()). + -define(request(M, U, H, B, O), request_inets(M, U, H, B, O)). + -define(stop(), stop_inets()). + -endif. +-endif. + +-type header() :: {string() | atom(), string()}. +-type headers() :: [header()]. + +-type option() :: + {connect_timeout, timeout()} | + {timeout, timeout()} | + + {send_retry, non_neg_integer()} | + {partial_upload, non_neg_integer() | infinity} | + {partial_download, pid(), non_neg_integer() | infinity}. + +-type options() :: [option()]. + +-type result() :: {ok, {{pos_integer(), string()}, headers(), string()}} | + {error, atom()}. + +%% @spec () -> ok | {error, Reason} +%% Reason = term() +%% @doc +%% Start the application. +%% This is a helper function that will start the corresponding backend. +%% It allows the library to be started using the `-s' flag. +%% For instance: +%% `$ erl -s http_p1' +%% +%% @end +-spec start() -> ok | {error, any()}. +start() -> + ?start(). + +start_inets()-> + inets:start(), + ssl:start(). + +start_lhttpc()-> + application:start(crypto), + application:start(ssl), + lhttpc:start(). + +start_ibrowse()-> + ibrowse:start(), + ssl:start(). + +%% @spec () -> ok | {error, Reason} +%% Reason = term() +%% @doc +%% Stops the application. +%% This is a helper function that will stop the corresponding backend. +%% +%% @end +-spec stop() -> ok | {error, any()}. +stop() -> + ?stop(). + +stop_inets()-> + inets:stop(), + ssl:stop(). + +stop_lhttpc()-> + lhttpc:stop(), + application:stop(ssl). + +stop_ibrowse()-> + ibrowse:stop(). + +%% @spec (URL) -> Result +%% URL = string() +%% Result = {ok, StatusCode, Hdrs, ResponseBody} +%% | {error, Reason} +%% StatusCode = integer() +%% ResponseBody = string() +%% Reason = connection_closed | connect_timeout | timeout +%% @doc Sends a GET request. +%% Would be the same as calling `request(get, URL, [])', +%% that is {@link request/3} with an empty header list. +%% @end +%% @see request/3 +-spec get(string()) -> result(). +get(URL) -> + request(get, URL, []). + +%% @spec (URL, Hdrs) -> Result +%% URL = string() +%% Hdrs = [{Header, Value}] +%% Header = string() +%% Value = string() +%% Result = {ok, StatusCode, Hdrs, ResponseBody} +%% | {error, Reason} +%% StatusCode = integer() +%% ResponseBody = string() +%% Reason = connection_closed | connect_timeout | timeout +%% @doc Sends a GET request. +%% Would be the same as calling `request(get, URL, Hdrs)'. +%% @end +%% @see request/3 +-spec get(string(), headers()) -> result(). +get(URL, Hdrs) -> + request(get, URL, Hdrs). + +%% @spec (URL, RequestBody) -> Result +%% URL = string() +%% RequestBody = string() +%% Result = {ok, StatusCode, Hdrs, ResponseBody} +%% | {error, Reason} +%% StatusCode = integer() +%% ResponseBody = string() +%% Reason = connection_closed | connect_timeout | timeout +%% @doc Sends a POST request with form data. +%% Would be the same as calling +%% `request(post, URL, [{"content-type", "x-www-form-urlencoded"}], Body)'. +%% @end +%% @see request/4 +-spec post(string(), string()) -> result(). +post(URL, Body) -> + request(post, URL, [{"content-type", "x-www-form-urlencoded"}], Body). + +%% @spec (URL, Hdrs, RequestBody) -> Result +%% URL = string() +%% Hdrs = [{Header, Value}] +%% Header = string() +%% Value = string() +%% RequestBody = string() +%% Result = {ok, StatusCode, Hdrs, ResponseBody} +%% | {error, Reason} +%% StatusCode = integer() +%% ResponseBody = string() +%% Reason = connection_closed | connect_timeout | timeout +%% @doc Sends a POST request. +%% Would be the same as calling +%% `request(post, URL, Hdrs, Body)'. +%% @end +%% @see request/4 +-spec post(string(), headers(), string()) -> result(). +post(URL, Hdrs, Body) -> + NewHdrs = case [X || {X,_}<-Hdrs, string:to_lower(X) == "content-type"] of + [] -> + [{"content-type", "x-www-form-urlencoded"} | Hdrs]; + _ -> + Hdrs + end, + request(post, URL, NewHdrs, Body). + +%% @spec (Method, URL, Hdrs) -> Result +%% Method = atom() +%% URL = string() +%% Hdrs = [{Header, Value}] +%% Header = string() +%% Value = string() +%% Result = {ok, StatusCode, Hdrs, ResponseBody} +%% | {error, Reason} +%% StatusCode = integer() +%% ResponseBody = string() +%% Reason = connection_closed | connect_timeout | timeout +%% @doc Sends a request without a body. +%% Would be the same as calling `request(Method, URL, Hdrs, [], [])', +%% that is {@link request/5} with an empty body. +%% @end +%% @see request/5 +-spec request(atom(), string(), headers()) -> result(). +request(Method, URL, Hdrs) -> + request(Method, URL, Hdrs, [], []). + +%% @spec (Method, URL, Hdrs, RequestBody) -> Result +%% Method = atom() +%% URL = string() +%% Hdrs = [{Header, Value}] +%% Header = string() +%% Value = string() +%% RequestBody = string() +%% Result = {ok, StatusCode, Hdrs, ResponseBody} +%% | {error, Reason} +%% StatusCode = integer() +%% ResponseBody = string() +%% Reason = connection_closed | connect_timeout | timeout +%% @doc Sends a request with a body. +%% Would be the same as calling +%% `request(Method, URL, Hdrs, Body, [])', that is {@link request/5} +%% with no options. +%% @end +%% @see request/5 +-spec request(atom(), string(), headers(), string()) -> result(). +request(Method, URL, Hdrs, Body) -> + request(Method, URL, Hdrs, Body, []). + +%% @spec (Method, URL, Hdrs, RequestBody, Options) -> Result +%% Method = atom() +%% URL = string() +%% Hdrs = [{Header, Value}] +%% Header = string() +%% Value = string() +%% RequestBody = string() +%% Options = [Option] +%% Option = {timeout, Milliseconds | infinity} | +%% {connect_timeout, Milliseconds | infinity} | +%% {socket_options, [term()]} | + +%% Milliseconds = integer() +%% Result = {ok, StatusCode, Hdrs, ResponseBody} +%% | {error, Reason} +%% StatusCode = integer() +%% ResponseBody = string() +%% Reason = connection_closed | connect_timeout | timeout +%% @doc Sends a request with a body. +%% Would be the same as calling +%% `request(Method, URL, Hdrs, Body, [])', that is {@link request/5} +%% with no options. +%% @end +%% @see request/5 +-spec request(atom(), string(), headers(), string(), options()) -> result(). +request(Method, URL, Hdrs, Body, Opts) -> +% ?DEBUG("Making request with headers: ~p~n~n", [Hdrs]), +% Headers = lists:map(fun({H, V}) -> +% H2 = if +% is_atom(H) -> +% string:to_lower(atom_to_list(H)); +% is_list(H) -> +% string:to_lower(H); +% true -> +% H +% end, +% {H2, V} +% end, Hdrs), + ?request(Method, URL, Hdrs, Body, Opts). + +request_inets(Method, URL, Hdrs, Body, Opts) -> + Request = case Method of + get -> + {URL, Hdrs}; + head -> + {URL, Hdrs}; + _ -> % post, etc. + {URL, Hdrs, proplists:get_value("content-type", Hdrs, []), Body} + end, + Options = case proplists:get_value(timeout, Opts, infinity) of + infinity -> + proplists:delete(timeout, Opts); + _ -> + Opts + end, + case http:request(Method, Request, Options, []) of + {ok, {{_, Status, _}, Headers, Response}} -> + {ok, Status, Headers, Response}; + {error, Reason} -> + {error, Reason} + end. + +request_lhttpc(Method, URL, Hdrs, Body, Opts) -> + TimeOut = proplists:get_value(timeout, Opts, infinity), + SockOpt = proplists:get_value(socket_options, Opts, []), + Options = [{connect_options, SockOpt} | proplists:delete(timeout, Opts)], + case lhttpc:request(URL, Method, Hdrs, Body, TimeOut, Options) of + {ok, {{Status, _Reason}, Headers, Response}} -> + {ok, Status, Headers, binary_to_list(Response)}; + {error, Reason} -> + {error, Reason} + end. + +request_ibrowse(Method, URL, Hdrs, Body, Opts) -> + TimeOut = proplists:get_value(timeout, Opts, infinity), + Options = [{inactivity_timeout, TimeOut} | proplists:delete(timeout, Opts)], + case ibrowse:send_req(URL, Hdrs, Method, Body, Options) of + {ok, Status, Headers, Response} -> + {ok, list_to_integer(Status), Headers, Response}; + {error, Reason} -> + {error, Reason} + end. + +% ibrowse {response_format, response_format()} | +% Options - [option()] +% Option - {sync, boolean()} | {stream, StreamTo} | {body_format, body_format()} | {full_result, +% boolean()} | {headers_as_is, boolean()} +%body_format() = string() | binary() +% The body_format option is only valid for the synchronous request and the default is string. +% When making an asynchronous request the body will always be received as a binary. +% lhttpc: always binary diff --git a/src/mod_admin_p1.erl b/src/mod_admin_p1.erl new file mode 100644 index 000000000..bcfc8232c --- /dev/null +++ b/src/mod_admin_p1.erl @@ -0,0 +1,1166 @@ +%%%------------------------------------------------------------------- +%%% File : mod_admin_p1.erl +%%% Author : Badlop / Mickael Remond / Christophe Romain +%%% Purpose : Administrative functions and commands for ProcessOne customers +%%% Created : 21 May 2008 by Badlop +%%% +%%% +%%% ejabberd, Copyright (C) 2002-2008 ProcessOne +%%% +%%% This program is free software; you can redistribute it and/or +%%% modify it under the terms of the GNU General Public License as +%%% published by the Free Software Foundation; either version 2 of the +%%% License, or (at your option) any later version. +%%% +%%% This program is distributed in the hope that it will be useful, +%%% but WITHOUT ANY WARRANTY; without even the implied warranty of +%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +%%% General Public License for more details. +%%% +%%% You should have received a copy of the GNU General Public License +%%% along with this program; if not, write to the Free Software +%%% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +%%% 02111-1307 USA +%%% +%%%------------------------------------------------------------------- + +%%% @doc Administrative functions and commands for ProcessOne customers +%%% +%%% This ejabberd module defines and registers many ejabberd commands +%%% that can be used for performing administrative tasks in ejabberd. +%%% +%%% The documentation of all those commands can be read using ejabberdctl +%%% in the shell. +%%% +%%% The commands can be executed using any frontend to ejabberd commands. +%%% Currently ejabberd_xmlrpc and ejabberdctl. Using ejabberd_xmlrpc it is possible +%%% to call any ejabberd command. However using ejabberdctl not all commands +%%% can be called. + +%%% Changelog: +%%% +%%% 0.8 - 26 September 2008 - badlop +%%% - added patch for parameter 'Push' +%%% +%%% 0.7 - 20 August 2008 - badlop +%%% - module converted to ejabberd commands +%%% +%%% 0.6 - 02 June 2008 - cromain +%%% - add user existance checking +%%% - improve parameter checking +%%% - allow orderless parameter +%%% +%%% 0.5 - 17 March 2008 - cromain +%%% - add user changing and higher level methods +%%% +%%% 0.4 - 18 February 2008 - cromain +%%% - add roster handling +%%% - add message sending +%%% - code and api clean-up +%%% +%%% 0.3 - 18 October 2007 - cromain +%%% - presence improvement +%%% - add new functionality +%%% +%%% 0.2 - 4 March 2006 - mremond +%%% - Code clean-up +%%% - Made it compatible with current ejabberd SVN version +%%% +%%% 0.1.2 - 28 December 2005 +%%% - Now compatible with ejabberd 1.0.0 +%%% - The XMLRPC server is started only once, not once for every virtual host +%%% - Added comments for handlers. Every available handler must be explained +%%% + +-module(mod_admin_p1). +-author('ProcessOne'). + +-export([start/2, stop/1, + %% Erlang + restart_module/2, + %% Accounts + create_account/3, + delete_account/2, + change_password/3, + rename_account/4, + check_users_registration/1, + %% Sessions + get_presence/2, + get_resources/2, + %% Vcard + set_nickname/3, + %% Roster + add_rosteritem/6, + delete_rosteritem/3, + link_contacts/4, + unlink_contacts/2, + link_contacts/5, unlink_contacts/3, % Versions with Push parameter + get_roster/2, + get_roster_with_presence/2, + add_contacts/3, + remove_contacts/3, + %% PubSub + update_status/4, + delete_status/3, + %% Transports + transport_register/5, + %% Stanza + send_chat/3, + send_message/4, + send_notification/6, %% ON + send_stanza/3 + ]). + +-include("ejabberd.hrl"). +-include("ejabberd_commands.hrl"). +-include("mod_roster.hrl"). +-include("jlib.hrl"). + +-ifdef(EJABBERD1). +-record(session, {sid, usr, us, priority}). %% ejabberd 1.1.x +-else. +-record(session, {sid, usr, us, priority, info}). %% ejabberd 2.x.x +-endif. + +start(_Host, _Opts) -> + ejabberd_commands:register_commands(commands()). + +stop(_Host) -> + ejabberd_commands:unregister_commands(commands()). + +%%% +%%% Register commands +%%% + +commands() -> + [ + #ejabberd_commands{name = restart_module, tags = [erlang], + desc = "Stop an ejabberd module, reload code and start", + module = ?MODULE, function = restart_module, + args = [{module, string}, {host, string}], + result = {res, rescode}}, + + %% Similar to ejabberd_admin register + #ejabberd_commands{name = create_account, tags = [accounts], + desc = "Create an ejabberd user account", + longdesc = "This command is similar to 'register'.", + module = ?MODULE, function = create_account, + args = [{user, string}, {server, string}, + {password, string}], + result = {res, integer}}, + + %% Similar to ejabberd_admin unregister + #ejabberd_commands{name = delete_account, tags = [accounts], + desc = "Remove an account from the server", + longdesc = "This command is similar to 'unregister'.", + module = ?MODULE, function = delete_account, + args = [{user, string}, {server, string}], + result = {res, integer}}, + + #ejabberd_commands{name = rename_account, tags = [accounts], + desc = "Change an acount name", + longdesc = "Creates a new account " + "and copies the roster from the old one. " + "Offline messages and private storage are lost.", + module = ?MODULE, function = rename_account, + args = [{user, string}, {server, string}, + {newuser, string}, {newserver, string}], + result = {res, integer}}, + + %% This command is also implemented in mod_admin_contrib + #ejabberd_commands{name = change_password, tags = [accounts], + desc = "Change the password on behalf of the given user", + module = ?MODULE, function = change_password, + args = [{user, string}, {server, string}, + {newpass, string}], + result = {res, integer}}, + + %% This command is also implemented in mod_admin_contrib + #ejabberd_commands{name = set_nickname, tags = [vcard], + desc = "Define user nickname", + longdesc = "Set/updated nickname in the user Vcard. " + "Other informations are unchanged.", + module = ?MODULE, function = set_nickname, + args = [{user, string}, {server, string}, {nick,string}], + result = {res, integer}}, + + %% This command is also implemented in mod_admin_contrib + #ejabberd_commands{name = add_rosteritem, tags = [roster], + desc = "Add an entry in a user's roster", + longdesc = "Some arguments are:\n" + " - jid: the JabberID of the user you would " + "like to add in user roster on the server.\n" + " - subs: the state of the roster item subscription.\n\n" + "The allowed values of the 'subs' argument are: both, to, from or none.\n" + " - none: presence packets are not sent between parties.\n" + " - both: presence packets are sent in both direction.\n" + " - to: the user sees the presence of the given JID.\n" + " - from: the JID specified sees the user presence.\n\n" + "Don't forget that roster items should keep symmetric: " + "when adding a roster item for a user, " + "you have to do the symmetric roster item addition.\n\n", + module = ?MODULE, function = add_rosteritem, + args = [{user, string}, {server, string}, {jid, string}, + {group, string}, {nick, string}, {subs, string}], + result = {res, integer}}, + + %% This command is also implemented in mod_admin_contrib + #ejabberd_commands{name = delete_rosteritem, tags = [roster], + desc = "Remove an entry for a user roster", + longdesc = "Roster items should be kept symmetric: " + "when removing a roster item for a user you have to do " + "the symmetric roster item removal. \n\n" + "This mechanism bypass the standard roster approval " + "addition mechanism and should only be used for server " + "administration or server integration purpose.", + module = ?MODULE, function = delete_rosteritem, + args = [{user, string}, {server, string}, {jid, string}], + result = {res, integer}}, + + #ejabberd_commands{name = link_contacts, tags = [roster], + desc = "Add a symmetrical entry in two users roster", + longdesc = "jid1 is the JabberID of the user1 you would " + "like to add in user2 roster on the server.\n" + "nick1 is the nick of user1.\n" + "jid2 is the JabberID of the user2 you would like to " + "add in user1 roster on the server.\n" + "nick2 is the nick of user2.\n\n" + "This mechanism bypass the standard roster approval " + "addition mechanism " + "and should only be userd for server administration or " + "server integration purpose.", + module = ?MODULE, function = link_contacts, + args = [{jid1, string}, {nick1, string}, {jid2, string}, {nick2, string}], + result = {res, integer}}, + + #ejabberd_commands{name = unlink_contacts, tags = [roster], + desc = "Remove a symmetrical entry in two users roster", + longdesc = "jid1 is the JabberID of the user1.\n" + "jid2 is the JabberID of the user2.\n\n" + "This mechanism bypass the standard roster approval " + "addition mechanism " + "and should only be userd for server administration or " + "server integration purpose.", + module = ?MODULE, function = unlink_contacts, + args = [{jid1, string}, {jid2, string}], + result = {res, integer}}, + + %% TODO: test + %% This command is not supported by ejabberdctl + #ejabberd_commands{name = add_contacts, tags = [roster], + desc = "Call add_rosteritem with subscription \"both\" " + "for a given list of contacts", + module = ?MODULE, function = add_contacts, + args = [{user, string}, + {server, string}, + {contacts, {list, + {contact, {tuple, [ + {jid, string}, + {group, string}, + {nick, string} + ]}} + }} + ], + result = {res, integer}}, + %% xmlrpc:call({127, 0, 0, 1}, 4560, "/", {call, add_contacts, [{struct, + %% [{user, "badlop"}, + %% {server, "localhost"}, + %% {contacts, {array, [{struct, [ + %% {contact, {array, [{struct, [ + %% {group, "Friends"}, + %% {jid, "tom@localhost"}, + %% {nick, "Tom"} + %% ]}]}} + %% ]}]}} + %% ] + %% }]}). + + %% TODO: test + %% This command is not supported by ejabberdctl + #ejabberd_commands{name = remove_contacts, tags = [roster], + desc = "Call del_rosteritem for a list of contacts", + module = ?MODULE, function = remove_contacts, + args = [{user, string}, + {server, string}, + {contacts, {list, + {jid, string} + }} + ], + result = {res, integer}}, + %% xmlrpc:call({127, 0, 0, 1}, 4560, "/", {call, remove_contacts, [{struct, + %% [{user, "badlop"}, + %% {server, "localhost"}, + %% {contacts, {array, [{struct, [ + %% {jid, "tom@localhost"} + %% ]}]}} + %% ] + %% }]}). + + %% TODO: test + %% This command is not supported by ejabberdctl + #ejabberd_commands{name = check_users_registration, tags = [roster], + desc = "List registration status for a list of users", + module = ?MODULE, function = check_users_registration, + args = [{users, {list, + {auser, {tuple, [ + {user, string}, + {server, string} + ]}} + }} + ], + result = {users, {list, + {auser, {tuple, [ + {user, string}, + {server, string}, + {status, integer} + ]}} + }}}, + %% xmlrpc:call({127, 0, 0, 1}, 4560, "/", {call, check_users_registration, [{struct, + %% [{users, {array, [{struct, [ + %% {auser, {array, [{struct, [ + %% {user, "badlop"}, + %% {server, "localhost"} + %% ]}]}} + %% ]}]}}] + %% }]}). + + %% This command is also implemented in mod_admin_contrib + #ejabberd_commands{name = get_roster, tags = [roster], + desc = "Retrieve the roster for a given user", + longdesc = "Returns a list of the contacts in a user " + "roster.\n\n" + "Also returns the state of the contact subscription. " + "Subscription can be either " + " \"none\", \"from\", \"to\", \"both\". " + "Pending can be \"in\", \"out\" or \"none\".", + module = ?MODULE, function = get_roster, + args = [{user, string}, {server, string}], + result = {contacts, {list, {contact, {tuple, [{jid, string}, {group, string}, + {nick, string}, {subscription, string}, {pending, string}]}}}}}, + + #ejabberd_commands{name = get_roster_with_presence, tags = [roster], + desc = "Retrieve the roster for a given user including " + "presence information", + longdesc = "The 'show' value contains the user presence. " + "It can take limited values:\n" + " - available\n" + " - chat (Free for chat)\n" + " - away\n" + " - dnd (Do not disturb)\n" + " - xa (Not available, extended away)\n" + " - unavailable (Not connected)\n\n" + "'status' is a free text defined by the user client.\n\n" + "Also returns the state of the contact subscription. " + "Subscription can be either " + "\"none\", \"from\", \"to\", \"both\". " + "Pending can be \"in\", \"out\" or \"none\".\n\n" + "Note: If user is connected several times, only keep the" + " resource with the highest non-negative priority.", + module = ?MODULE, function = get_roster_with_presence, + args = [{user, string}, {server, string}], + result = {contacts, {list, {contact, {tuple, [{jid, string}, {resource, string}, {group, string}, {nick, string}, {subscription, string}, {pending, string}, {show, string}, {status, string}]}}}}}, + + #ejabberd_commands{name = get_presence, tags = [session], + desc = "Retrieve the resource with highest priority, " + "and its presence (show and status message) for a given " + "user.", + longdesc = "The 'jid' value contains the user jid with " + "resource.\n" + "The 'show' value contains the user presence flag. " + "It can take limited values:\n" + " - available\n" + " - chat (Free for chat)\n" + " - away\n" + " - dnd (Do not disturb)\n" + " - xa (Not available, extended away)\n" + " - unavailable (Not connected)\n\n" + "'status' is a free text defined by the user client.", + module = ?MODULE, function = get_presence, + args = [{user, string}, {server, string}], + result = {presence, {tuple, [{jid, string}, + {show, string}, + {status, string}]}}}, + + #ejabberd_commands{name = get_resources, tags = [session], + desc = "Get all available resources for a given user", + module = ?MODULE, function = get_resources, + args = [{user, string}, {server, string}], + result = {resources, {list, {resource, string}}}}, + + %% PubSub + #ejabberd_commands{name = update_status, tags = [pubsub], + desc = "Update the status on behalf of a user", + longdesc = + "jid: the JabberID of the user. Example: user@domain.\n\n" + "node: the reference of the node to publish on.\n" + "Example: http://process-one.net/protocol/availability\n\n" + "itemid: the reference of the item (in our case profile ID).\n\n" + "payload: the payload of the publish operation in XML.\n" + "The string has to be properly escaped to comply with XML formalism of XML RPC.", + module = ?MODULE, function = update_status, + args = [{jid, string}, {node, string}, {itemid, string}, {payload, string}], + result = {res, string}}, + + #ejabberd_commands{name = delete_status, tags = [pubsub], + desc = "Delete the status on behalf of a user", + longdesc = + "jid: the JabberID of the user. Example: user@domain.\n\n" + "node: the reference of the node to publish on.\n" + "Example: http://process-one.net/protocol/availability\n\n" + "itemid: the reference of the item (in our case profile ID).", + module = ?MODULE, function = delete_status, + args = [{jid, string}, {node, string}, {itemid, string}], + result = {res, string}}, + + #ejabberd_commands{name = transport_register, tags = [transports], + desc = "Register a user in a transport", + module = ?MODULE, function = transport_register, + args = [{host, string}, {transport, string}, + {jidstring, string}, {username, string}, {password, string}], + result = {res, string}}, + + %% Similar to mod_admin_contrib send_message which sends a headline + #ejabberd_commands{name = send_chat, tags = [stanza], + desc = "Send chat message to a given user", + module = ?MODULE, function = send_chat, + args = [{from, string}, {to, string}, {body, string}], + result = {res, integer}}, + + #ejabberd_commands{name = send_message, tags = [stanza], + desc = "Send normal message to a given user", + module = ?MODULE, function = send_message, + args = [{from, string}, {to, string}, + {subject, string}, {body, string}], + result = {res, integer}}, + + #ejabberd_commands{name = send_notification, tags = [stanza], + desc = "Send ON notification to XMPP client sessions", + module = ?MODULE, function = send_notification, + args = [{send_from, string}, {send_to, string}, {host, string}, + {unread_items, string}, {message, string}, + {type, string}], + result = {res, integer}}, + + #ejabberd_commands{name = send_stanza, tags = [stanza], + desc = "Send stanza to a given user", + longdesc = "If Stanza contains a \"from\" field, " + "then it overrides the passed from argument." + "If Stanza contains a \"to\" field, then it overrides " + "the passed to argument.", + module = ?MODULE, function = send_stanza, + args = [{user, string}, {server, string}, + {stanza, string}], + result = {res, integer}} + ]. + + +%%% +%%% Erlang +%%% + +restart_module(ModuleString, Host) -> + Module = list_to_atom(ModuleString), + List = gen_mod:loaded_modules_with_opts(Host), + Opts = case lists:keysearch(Module,1, List) of + {value, {_, O}} -> O; + _ -> [] + end, + gen_mod:stop_module(Host, Module), + code:delete(Module), + code:purge(Module), + gen_mod:start_module(Host, Module, Opts), + ok. + + +%%% +%%% Accounts +%%% + +create_account(U, S, P) -> + case ejabberd_auth:try_register(U, S, P) of + {atomic, ok} -> + 0; + {atomic, exists} -> + 409; + _ -> + 1 + end. + +delete_account(U, S) -> + Fun = fun() -> ejabberd_auth:remove_user(U, S) end, + user_action(U, S, Fun, ok). + +change_password(U, S, P) -> + Fun = fun() -> ejabberd_auth:set_password(U, S, P) end, + user_action(U, S, Fun, ok). + +rename_account(U, S, NU, NS) -> + case ejabberd_auth:is_user_exists(U, S) of + true -> + case ejabberd_auth:get_password(U, S) of + false -> + 1; + Password -> + case ejabberd_auth:try_register(NU, NS, Password) of + {atomic, ok} -> + OldJID = jlib:jid_to_string({U, S, ""}), + NewJID = jlib:jid_to_string({NU, NS, ""}), + Roster = get_roster2(U, S), + lists:foreach(fun(#roster{jid={RU, RS, RE}, name=Nick, groups=Groups}) -> + NewGroup = extract_group(Groups), + {NewNick, Group} = case lists:filter(fun(#roster{jid={PU, PS, _}}) -> + (PU == U) and (PS == S) + end, get_roster2(RU, RS)) of + [#roster{name=OldNick, groups=OldGroups}|_] -> {OldNick, extract_group(OldGroups)}; + [] -> {NU, []} + end, + JIDStr = jlib:jid_to_string({RU, RS, RE}), + link_contacts2(NewJID, NewNick, NewGroup, JIDStr, Nick, Group, true), + unlink_contacts2(OldJID, JIDStr, true) + end, Roster), + ejabberd_auth:remove_user(U, S), + 0; + {atomic, exists} -> + 409; + _ -> + 1 + end + end; + false -> + 404 + end. + + +%%% +%%% Sessions +%%% + +get_presence(U, S) -> + case ejabberd_auth:is_user_exists(U, S) of + true -> + {Resource, Show, Status} = get_presence2(U, S), + FullJID = case Resource of + [] -> + lists:flatten([U,"@",S]); + _ -> + lists:flatten([U,"@",S,"/",Resource]) + end, + {FullJID, Show, Status}; + false -> + 404 + end. + +get_resources(U, S) -> + case ejabberd_auth:is_user_exists(U, S) of + true -> + get_resources2(U, S); + false -> + 404 + end. + + +%%% +%%% Vcard +%%% + +set_nickname(U, S, N) -> + Fun = fun() -> case mod_vcard:process_sm_iq( + {jid, U, S, "", U, S, ""}, + {jid, U, S, "", U, S, ""}, + {iq, "", set, "", "en", + {xmlelement, "vCard", + [{"xmlns", "vcard-temp"}], [ + {xmlelement, "NICKNAME", [], [{xmlcdata, N}]} + ] + }}) of + {iq, [], result, [], _, []} -> ok; + _ -> error + end + end, + user_action(U, S, Fun, ok). + + +%%% +%%% Roster +%%% + +add_rosteritem(U, S, JID, G, N, Subs) -> + add_rosteritem(U, S, JID, G, N, Subs, true). + +add_rosteritem(U, S, JID, G, N, Subs, Push) -> + Fun = fun() -> add_rosteritem2(U, S, JID, N, G, Subs, Push) end, + user_action(U, S, Fun, {atomic, ok}). + +link_contacts(JID1, Nick1, JID2, Nick2) -> + link_contacts(JID1, Nick1, JID2, Nick2, true). + +link_contacts(JID1, Nick1, JID2, Nick2, Push) -> + {U1, S1, _} = jlib:jid_tolower(jlib:string_to_jid(JID1)), + {U2, S2, _} = jlib:jid_tolower(jlib:string_to_jid(JID2)), + case {ejabberd_auth:is_user_exists(U1, S1), ejabberd_auth:is_user_exists(U2, S2)} of + {true, true} -> + case link_contacts2(JID1, Nick1, JID2, Nick2, Push) of + {atomic, ok} -> + 0; + _ -> + 1 + end; + _ -> + 404 + end. + +delete_rosteritem(U, S, JID) -> + Fun = fun() -> del_rosteritem(U, S, JID) end, + user_action(U, S, Fun, {atomic, ok}). + +unlink_contacts(JID1, JID2) -> + unlink_contacts(JID1, JID2, true). + +unlink_contacts(JID1, JID2, Push) -> + {U1, S1, _} = jlib:jid_tolower(jlib:string_to_jid(JID1)), + {U2, S2, _} = jlib:jid_tolower(jlib:string_to_jid(JID2)), + case {ejabberd_auth:is_user_exists(U1, S1), ejabberd_auth:is_user_exists(U2, S2)} of + {true, true} -> + case unlink_contacts2(JID1, JID2, Push) of + {atomic, ok} -> + 0; + _ -> + 1 + end; + _ -> + 404 + end. + +get_roster(U, S) -> + case ejabberd_auth:is_user_exists(U, S) of + true -> + format_roster(get_roster2(U, S)); + false -> + 404 + end. + +get_roster_with_presence(U, S) -> + case ejabberd_auth:is_user_exists(U, S) of + true -> + format_roster_with_presence(get_roster2(U, S)); + false -> + 404 + end. + +add_contacts(U, S, Contacts) -> + case ejabberd_auth:is_user_exists(U, S) of + true -> + JID1 = jlib:jid_to_string({U, S, ""}), + lists:foldl(fun({JID2, Group, Nick}, Acc) -> + {PU, PS, _} = jlib:jid_tolower(jlib:string_to_jid(JID2)), + case ejabberd_auth:is_user_exists(PU, PS) of + true -> + case link_contacts2(JID1, "", Group, JID2, Nick, Group, true) of + {atomic, ok} -> Acc; + _ -> 1 + end; + false -> + Acc + end + end, 0, Contacts); + false -> + 404 + end. + +remove_contacts(U, S, Contacts) -> + case ejabberd_auth:is_user_exists(U, S) of + true -> + JID1 = jlib:jid_to_string({U, S, ""}), + lists:foldl(fun(JID2, Acc) -> + {PU, PS, _} = jlib:jid_tolower(jlib:string_to_jid(JID2)), + case ejabberd_auth:is_user_exists(PU, PS) of + true -> + case unlink_contacts2(JID1, JID2, true) of + {atomic, ok} -> Acc; + _ -> 1 + end; + false -> + Acc + end + end, 0, Contacts); + false -> + 404 + end. + +check_users_registration(Users) -> + lists:map(fun({U, S}) -> + Registered = case ejabberd_auth:is_user_exists(U, S) of + true -> 1; + false -> 0 + end, + {U, S, Registered} + end, Users). + + +%%% +%%% PubSub +%%% + +update_status(JidString, NodeString, Itemid, PayloadString) -> + Publisher = jlib:string_to_jid(JidString), + Host = jlib:jid_tolower(jlib:jid_remove_resource(Publisher)), + ServerHost = Publisher#jid.lserver, + Node = mod_pubsub_on:string_to_node(NodeString), + Payload = [xml_stream:parse_element(PayloadString)], + ?DEBUG("PayloadString: ~n~p~nPayload elements: ~n~p", [PayloadString, Payload]), + case mod_pubsub_on:publish_item_nothook(Host, ServerHost, Node, Publisher, Itemid, Payload) of + {result, _} -> + "OK"; + {error, {xmlelement, _, _, _} = XmlEl} -> + "ERROR: " ++ xml:element_to_string(XmlEl); + {error, ErrorAtom} when is_atom(ErrorAtom) -> + "ERROR: " ++ atom_to_list(ErrorAtom); + {error, ErrorString} when is_list(ErrorString) -> + "ERROR: " ++ ErrorString + end. + +delete_status(JidString, NodeString, Itemid) -> + Publisher = jlib:string_to_jid(JidString), + Host = jlib:jid_tolower(jlib:jid_remove_resource(Publisher)), + Node = mod_pubsub_on:string_to_node(NodeString), + case mod_pubsub_on:delete_item_nothook(Host, Node, Publisher, Itemid, true) of + {result, _} -> + "OK"; + {error, {xmlelement, _, _, _} = XmlEl} -> + "ERROR: " ++ xml:element_to_string(XmlEl); + {error, ErrorAtom} when is_atom(ErrorAtom) -> + "ERROR: " ++ atom_to_list(ErrorAtom); + {error, ErrorString} when is_list(ErrorString) -> + "ERROR: " ++ ErrorString + end. + +transport_register(Host, TransportString, JIDString, Username, Password) -> + TransportAtom = list_to_atom(TransportString), + case {lists:member(Host, ?MYHOSTS), jlib:string_to_jid(JIDString)} of + {true, JID} when is_record(JID, jid) -> + case catch gen_transport:register(Host, TransportAtom, JIDString, + Username, Password) of + ok -> + "OK"; + {error, Reason} -> + "ERROR: " ++ atom_to_list(Reason); + {'EXIT', {timeout,_}} -> + "ERROR: timed_out"; + {'EXIT', _} -> + "ERROR: unexpected_error" + end; + {false, _} -> + "ERROR: unknown_host"; + _ -> + "ERROR: bad_jid" + end. + +%%% +%%% Stanza +%%% + +send_chat(FromJID, ToJID, Msg) -> + From = jlib:string_to_jid(FromJID), + To = jlib:string_to_jid(ToJID), + Stanza = {xmlelement, "message", [{"type", "chat"}], + [{xmlelement, "body", [], [{xmlcdata, Msg}]}]}, + ejabberd_router:route(From, To, Stanza), + 0. + +send_message(FromJID, ToJID, Sub, Msg) -> + From = jlib:string_to_jid(FromJID), + To = jlib:string_to_jid(ToJID), + Stanza = {xmlelement, "message", [{"type", "normal"}], + [{xmlelement, "subject", [], [{xmlcdata, Sub}]}, + {xmlelement, "body", [], [{xmlcdata, Msg}]}]}, + ejabberd_router:route(From, To, Stanza), + 0. + +send_notification(SendFromUsername, SendToUsername, Host, UnreadItemsInteger, MessageBody, Type) -> + case get_resources(SendToUsername, Host) of + 404 -> + -1; + [] -> + -2; + [A|_] when is_list(A) -> + send_notification_really(SendFromUsername, SendToUsername, Host, UnreadItemsInteger, MessageBody, Type), + 0 + end. + +send_notification_really(SendFromUsername, SendToUsername, Host, UnreadItemsInteger, MessageBody, Type) -> + FromString = Host ++ "/voicemail-notifier", + ToString = SendToUsername ++ "@" ++ Host, + + XAttrs = [{"type", Type}, + {"send_from", SendFromUsername}, + {"unread_items", UnreadItemsInteger}], + XChildren = [{xmlelement, "text", [], [{xmlcdata, MessageBody}]}], + XEl = {xmlelement, "x", XAttrs, XChildren}, + + Attrs = [{"from", FromString}, {"to", ToString}, {"type", "chat"}], + Children = [XEl], + Stanza = {xmlelement, "message", Attrs, Children}, + + From = jlib:string_to_jid(FromString), + To = jlib:string_to_jid(ToString), + ejabberd_router:route(From, To, Stanza). + +send_stanza(FromJID, ToJID, StanzaStr) -> + case xml_stream:parse_element(StanzaStr) of + {error, _} -> + 1; + Stanza -> + {xmlelement, _, Attrs, _} = Stanza, + From = jlib:string_to_jid(proplists:get_value("from", Attrs, FromJID)), + To = jlib:string_to_jid(proplists:get_value("to", Attrs, ToJID)), + ejabberd_router:route(From, To, Stanza), + 0 + end. + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%%% Internal functions + +%% ----------------------------- +%% Internal roster handling +%% ----------------------------- + +get_roster2(User, Server) -> + LUser = jlib:nodeprep(User), + LServer = jlib:nameprep(Server), + case roster_backend(LServer) of + mnesia -> mod_roster:get_user_roster([], {LUser, LServer}); + odbc -> mod_roster_odbc:get_user_roster([], {LUser, LServer}) + end. + +add_rosteritem2(User, Server, JID, Nick, Group, Subscription, Push) -> + {RU, RS, _} = jlib:jid_tolower(jlib:string_to_jid(JID)), + LJID = {RU,RS,[]}, + Groups = case Group of + [] -> []; + _ -> [Group] + end, + Roster = #roster{ + usj = {User,Server,LJID}, + us = {User,Server}, + jid = LJID, + name = Nick, + ask = none, + subscription = list_to_atom(Subscription), + groups = Groups}, + Result = + case roster_backend(Server) of + mnesia -> + mnesia:transaction(fun() -> + case mnesia:read({roster,{User,Server,LJID}}) of + [#roster{subscription=both}] -> + already_added; + _ -> + mnesia:write(Roster) + end + end); + odbc -> + %% MREMOND: TODO: check if already_added + case ejabberd_odbc:sql_transaction(Server, + fun() -> + Username = ejabberd_odbc:escape(User), + SJID = ejabberd_odbc:escape(jlib:jid_to_string(LJID)), + case ejabberd_odbc:sql_query_t( + ["select username from rosterusers " + " where username='", Username, "' " + " and jid='", SJID, + "' and subscription = 'B';"]) of + {selected, ["username"],[]} -> + ItemVals = record_to_string(Roster), + ItemGroups = groups_to_string(Roster), + odbc_queries:update_roster(Server, Username, + SJID, ItemVals, + ItemGroups); + _ -> + already_added + end + end) of + {atomic, already_added} -> {atomic, already_added}; + {atomic, _} -> {atomic, ok}; + Error -> Error + end + end, + case {Result, Push} of + {{atomic, already_added}, _} -> ok; %% No need for roster push + {{atomic, ok}, true} -> roster_push(User, Server, JID, Nick, Subscription, Groups); + {{atomic, ok}, false} -> ok; + _ -> error + end, + Result. + +del_rosteritem(User, Server, JID) -> + del_rosteritem(User, Server, JID, true). + +del_rosteritem(User, Server, JID, Push) -> + {RU, RS, _} = jlib:jid_tolower(jlib:string_to_jid(JID)), + LJID = {RU,RS,[]}, + Result = case roster_backend(Server) of + mnesia -> + mnesia:transaction(fun() -> + mnesia:delete({roster, {User,Server,LJID}}) + end); + odbc -> + case ejabberd_odbc:sql_transaction(Server, fun() -> + Username = ejabberd_odbc:escape(User), + SJID = ejabberd_odbc:escape(jlib:jid_to_string(LJID)), + odbc_queries:del_roster(Server, Username, SJID) + end) of + {atomic, _} -> {atomic, ok}; + Error -> Error + end + end, + case {Result, Push} of + {{atomic, ok}, true} -> roster_push(User, Server, JID, "", "remove", []); + {{atomic, ok}, false} -> ok; + _ -> error + end, + Result. + +link_contacts2(JID1, Nick1, JID2, Nick2, Push) -> + link_contacts2(JID1, Nick1, [], JID2, Nick2, [], Push). + +link_contacts2(JID1, Nick1, Group1, JID2, Nick2, Group2, Push) -> + {U1, S1, _} = jlib:jid_tolower(jlib:string_to_jid(JID1)), + {U2, S2, _} = jlib:jid_tolower(jlib:string_to_jid(JID2)), + case add_rosteritem2(U1, S1, JID2, Nick2, Group1, "both", Push) of + {atomic, ok} -> add_rosteritem2(U2, S2, JID1, Nick1, Group2, "both", Push); + Error -> Error + end. + +unlink_contacts2(JID1, JID2, Push) -> + {U1, S1, _} = jlib:jid_tolower(jlib:string_to_jid(JID1)), + {U2, S2, _} = jlib:jid_tolower(jlib:string_to_jid(JID2)), + case del_rosteritem(U1, S1, JID2, Push) of + {atomic, ok} -> del_rosteritem(U2, S2, JID1, Push); + Error -> Error + end. + +roster_push(User, Server, JID, Nick, Subscription, Groups) -> + LJID = jlib:make_jid(User, Server, ""), + TJID = jlib:string_to_jid(JID), + {TU, TS, _} = jlib:jid_tolower(TJID), + + %% TODO: Problem: We assume that both user are local. More test + %% are needed to check if the JID is remote or not: + + %% TODO: We need to probe user2 especially, if it is not local. + %% As a quick fix, I do not go for the probe solution however, because all users + %% are local + case Subscription of + "to" -> %% Probe second user to route his presence to modified user + %% TODO: For now we assume both user are local so we do not, but we need to move to probe. + set_roster(User, Server, TJID, Nick, Subscription, Groups); + "from" -> + %% Send roster updates + set_roster(User, Server, TJID, Nick, Subscription, Groups); + "both" -> + %% Update both presence + set_roster(User, Server, TJID, Nick, Subscription, Groups), + UJID = jlib:make_jid(User, Server, ""), + set_roster(TU, TS, UJID, Nick, Subscription, Groups); + _ -> + %% Remove subscription + set_roster(User, Server, TJID, Nick, "none", Groups) + end. + + +set_roster(User, Server, TJID, Nick, Subscription, Groups) -> + GroupsXML = [{xmlelement, "group", [], [{xmlcdata, GroupString}]} || GroupString <- Groups], + Item = case Nick of + "" -> [{"jid", jlib:jid_to_string(TJID)}, {"subscription", Subscription}]; + _ -> [{"jid", jlib:jid_to_string(TJID)}, {"name", Nick}, {"subscription", Subscription}] + end, + Result = jlib:iq_to_xml(#iq{type = set, xmlns = ?NS_ROSTER, id = "push", + sub_el = [{xmlelement, "query", [{"xmlns", ?NS_ROSTER}], + [{xmlelement, "item", Item, GroupsXML}]}]}), + lists:foreach(fun(Session) -> + JID = jlib:make_jid(Session#session.usr), + ejabberd_router:route(JID, JID, Result), + PID = element(2, Session#session.sid), + ejabberd_c2s:add_rosteritem(PID, TJID, list_to_atom(Subscription)) %% TODO: Better error management + end, get_sessions(User, Server)). + + +roster_backend(Server) -> + case lists:member(mod_roster, gen_mod:loaded_modules(Server)) of + true -> mnesia; + _ -> odbc % we assume that + end. + +record_to_string(#roster{us = {User, _Server}, + jid = JID, + name = Name, + subscription = Subscription, + ask = Ask, + askmessage = AskMessage}) -> + Username = ejabberd_odbc:escape(User), + SJID = ejabberd_odbc:escape(jlib:jid_to_string(jlib:jid_tolower(JID))), + Nick = ejabberd_odbc:escape(Name), + SSubscription = case Subscription of + both -> "B"; + to -> "T"; + from -> "F"; + none -> "N" + end, + SAsk = case Ask of + subscribe -> "S"; + unsubscribe -> "U"; + both -> "B"; + out -> "O"; + in -> "I"; + none -> "N" + end, + SAskMessage = ejabberd_odbc:escape(AskMessage), + ["'", Username, "'," + "'", SJID, "'," + "'", Nick, "'," + "'", SSubscription, "'," + "'", SAsk, "'," + "'", SAskMessage, "'," + "'N', '', 'item'"]. + +groups_to_string(#roster{us = {User, _Server}, + jid = JID, + groups = Groups}) -> + Username = ejabberd_odbc:escape(User), + SJID = ejabberd_odbc:escape(jlib:jid_to_string(jlib:jid_tolower(JID))), + %% Empty groups do not need to be converted to string to be inserted in + %% the database + lists:foldl(fun([], Acc) -> Acc; + (Group, Acc) -> + String = ["'", Username, "'," + "'", SJID, "'," + "'", ejabberd_odbc:escape(Group), "'"], + [String|Acc] + end, [], Groups). + +%% Format roster items as a list of: +%% [{struct, [{jid, "test@localhost"},{group, "Friends"},{nick, "Nicktest"}]}] +format_roster([]) -> + []; +format_roster(Items) -> + format_roster(Items, []). +format_roster([], Structs) -> + Structs; +format_roster([#roster{jid=JID, name=Nick, groups=Group, + subscription=Subs, ask=Ask}|Items], Structs) -> + {User,Server,_Resource} = JID, + Struct = {lists:flatten([User,"@",Server]), + extract_group(Group), + Nick, + atom_to_list(Subs), + atom_to_list(Ask) + }, + format_roster(Items, [Struct|Structs]). + +%% Note: If user is connected several times, only keep the resource with the +%% highest non-negative priority +format_roster_with_presence([]) -> + []; +format_roster_with_presence(Items) -> + format_roster_with_presence(Items, []). +format_roster_with_presence([], Structs) -> + Structs; +format_roster_with_presence([#roster{jid=JID, name=Nick, groups=Group, + subscription=Subs, ask=Ask}|Items], Structs) -> + {User,Server,_R} = JID, + Presence = case Subs of + both -> get_presence2(User, Server); + from -> get_presence2(User, Server); + _Other -> {"", "unavailable", ""} + end, + {Resource, Show, Status} = + case Presence of + {_R, "invisible", _S} -> {"", "unavailable", ""}; + _Status -> Presence + end, + Struct = {lists:flatten([User,"@",Server]), + Resource, + extract_group(Group), + Nick, + atom_to_list(Subs), + atom_to_list(Ask), + Show, + Status + }, + format_roster_with_presence(Items, [Struct|Structs]). + +extract_group([]) -> []; +extract_group([Group|_Groups]) -> Group. + +%% ----------------------------- +%% Internal session handling +%% ----------------------------- + +%% This is inspired from ejabberd_sm.erl +get_presence2(User, Server) -> + case get_sessions(User, Server) of + [] -> + {"", "unavailable", ""}; + Ss -> + Session = hd(Ss), + if Session#session.priority >= 0 -> + Pid = element(2, Session#session.sid), + %{_User, _Resource, Show, Status} = rpc:call(node(Pid), ejabberd_c2s, get_presence, [Pid]), + {_User, Resource, Show, Status} = ejabberd_c2s:get_presence(Pid), + {Resource, Show, Status}; + true -> + {"", "unavailable", ""} + end + end. + +get_resources2(User, Server) -> + lists:map(fun(S) -> element(3, S#session.usr) + end, get_sessions(User, Server)). + +get_sessions(User, Server) -> + LUser = jlib:nodeprep(User), + LServer = jlib:nameprep(Server), + case catch mnesia:dirty_index_read(session, {LUser, LServer}, #session.us) of + {'EXIT', _Reason} -> []; + [] -> []; + Result -> lists:reverse(lists:keysort(#session.priority, clean_session_list(Result))) + end. + +clean_session_list(Ss) -> + clean_session_list(lists:keysort(#session.usr, Ss), []). + +clean_session_list([], Res) -> + Res; +clean_session_list([S], Res) -> + [S | Res]; +clean_session_list([S1, S2 | Rest], Res) -> + if + S1#session.usr == S2#session.usr -> + if + S1#session.sid > S2#session.sid -> + clean_session_list([S1 | Rest], Res); + true -> + clean_session_list([S2 | Rest], Res) + end; + true -> + clean_session_list([S2 | Rest], [S1 | Res]) + end. + + +%% ----------------------------- +%% Internal function pattern +%% ----------------------------- + +user_action(User, Server, Fun, OK) -> + case ejabberd_auth:is_user_exists(User, Server) of + true -> + case catch Fun() of + OK -> + 0; + _ -> + 1 + end; + false -> + 404 + end. diff --git a/src/mod_ip_blacklist.erl b/src/mod_ip_blacklist.erl index c9102f2c0..16b70deaa 100644 --- a/src/mod_ip_blacklist.erl +++ b/src/mod_ip_blacklist.erl @@ -85,7 +85,7 @@ loop(_State) -> %% TODO: Support comment lines starting by % update_bl_c2s() -> ?INFO_MSG("Updating C2S Blacklist", []), - case http:request(?BLC2S) of + case http_p1:request(?BLC2S) of {ok, {{_Version, 200, _Reason}, _Headers, Body}} -> IPs = string:tokens(Body,"\n"), ets:delete_all_objects(bl_c2s), diff --git a/src/mod_xmlrpc.erl b/src/mod_xmlrpc.erl new file mode 100644 index 000000000..8266d9727 --- /dev/null +++ b/src/mod_xmlrpc.erl @@ -0,0 +1,875 @@ +%%%---------------------------------------------------------------------- +%%% File : mod_xmlrpc.erl +%%% Author : Badlop / Mickael Remond / Christophe Romain +%%% Purpose : XML-RPC server +%%% Created : +%%% Id : +%%%---------------------------------------------------------------------- + +%%%/*************************************************************************** +%%% * * +%%% * 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. * +%%% * * +%%% ***************************************************************************/ +%%% +%%% +%%% MOD_XMLRPC - an XML-RPC server module for ejabberd +%%% +%%% v0.5 - 17 March 2008 +%%% +%%% http://ejabberd.jabber.ru/mod_xmlrpc +%%% +%%% (C) 2005, Badlop +%%% 2006, Process-one +%%% 2007, Process-one +%%% 2008, Process-one +%%% +%%% Changelog: +%%% +%%% 0.7 - 02 April 2009 - cromain +%%% - add user nick change +%%% +%%% 0.6 - 02 June 2008 - cromain +%%% - add user existance checking +%%% - improve parameter checking +%%% - allow orderless parameter +%%% +%%% 0.5 - 17 March 2008 - cromain +%%% - add user changing and higher level methods +%%% +%%% 0.4 - 18 February 2008 - cromain +%%% - add roster handling +%%% - add message sending +%%% - code and api clean-up +%%% +%%% 0.3 - 18 October 2007 - cromain +%%% - presence improvement +%%% - add new functionality +%%% +%%% 0.2 - 4 March 2006 - mremond +%%% - Code clean-up +%%% - Made it compatible with current ejabberd SVN version +%%% +%%% 0.1.2 - 28 December 2005 +%%% - Now compatible with ejabberd 1.0.0 +%%% - The XMLRPC server is started only once, not once for every virtual host +%%% - Added comments for handlers. Every available handler must be explained +%%% + +-module(mod_xmlrpc). +-author('Process-one'). +-vsn('0.6'). + +-behaviour(gen_mod). + +-export([start/2, + handler/2, + link_contacts/5, unlink_contacts/3, %% used by Nimbuzz + loop/1, + stop/1]). + +-export([add_rosteritem/6]). + +-include("ejabberd.hrl"). +-include("jlib.hrl"). +-include("mod_roster.hrl"). + +-ifdef(EJABBERD1). +-record(session, {sid, usr, us, priority}). %% ejabberd 1.1.x +-else. +-record(session, {sid, usr, us, priority, info}). %% ejabberd 2.0.x +-endif. + + +-define(PROCNAME, ejabberd_mod_xmlrpc). +-define(PORT, 4560). +-define(TIMEOUT, 5000). + +%% ----------------------------- +%% Module interface +%% ----------------------------- + +start(_Host, Opts) -> + case whereis(?PROCNAME) of + undefined -> + %% get options + Port = gen_mod:get_opt(port, Opts, ?PORT), + MaxSessions = 10, + Timeout = gen_mod:get_opt(timeout, Opts, ?TIMEOUT), + Handler = {mod_xmlrpc, handler}, + State = tryit, + + %% TODO: this option gives + %% error_info: {function_clause,[{gen_tcp,mod,[{ip,{127,0,0,1}}]}, + %%case gen_mod:get_opt(listen_all, Opts, false) of + %% true -> Ip = all; + %% false -> Ip = {127, 0, 0, 1} + %%end, + Ip = all, + + %% start the XML-RPC server + {ok, Pid} = xmlrpc:start_link(Ip, Port, MaxSessions, Timeout, Handler, State), + + %% start the loop process + register(?PROCNAME, spawn(?MODULE, loop, [Pid])), + ok; + _ -> + ok + end. + +loop(Pid) -> + receive + stop -> + xmlrpc:stop(Pid) + end. + +stop(_Host) -> + case whereis(?PROCNAME) of + undefined -> + ok; + _Pid -> + ?PROCNAME ! stop, + unregister(?PROCNAME) + end. + + +%% ----------------------------- +%% Handlers +%% ----------------------------- + +handler(tryit, Call) -> + try handler(notry, Call) of + Result -> Result + catch + A:B -> + ?ERROR_MSG("Problem '~p' in~nCall: ~p~nError: ~p", [A, Call, B]), + {false, {response, [-100]}} + end; + +% Call: Arguments: Returns: + +%% ............................. +%% Debug + +%% echothis String String +handler(_State, {call, echothis, [A]}) -> + {false, {response, [A]}}; + +%% multhis struct[{a, Integer}, {b, Integer}] Integer +handler(_State, {call, multhis, [{struct, Struct}]}) -> + [{a, A}, {b, B}] = lists:sort(Struct), + {false, {response, [A*B]}}; + +%% ............................. +%% User administration + +%% create_account struct[{user, String}, {server, Server}, {password, String}] Integer +handler(_State, {call, create_account, [{struct, Struct}]}) -> + [{password, P}, {server, S}, {user, U}] = lists:sort(Struct), + case ejabberd_auth:try_register(U, S, P) of + {atomic, ok} -> + {false, {response, [0]}}; + {atomic, exists} -> + {false, {response, [409]}}; + _ -> + {false, {response, [1]}} + end; + +%% delete_account struct[{user, String}, {server, Server}] Integer +handler(_State, {call, delete_account, [{struct, Struct}]}) -> + [{server, S}, {user, U}] = lists:sort(Struct), + Fun = fun() -> ejabberd_auth:remove_user(U, S) end, + user_action(U, S, Fun, ok); + +%% change_password struct[{user, String}, {server, String}, {newpass, String}] Integer +handler(_State, {call, change_password, [{struct, Struct}]}) -> + [{newpass, P}, {server, S}, {user, U}] = lists:sort(Struct), + Fun = fun() -> ejabberd_auth:set_password(U, S, P) end, + user_action(U, S, Fun, ok); + +%% set_nickname struct[{user, String}, {server, String}, {nick, String}] Integer +handler(_State, {call, set_nickname, [{struct, Struct}]}) -> + [{nick, N}, {server, S}, {user, U}] = lists:sort(Struct), + Fun = fun() -> case mod_vcard:process_sm_iq( + {jid, U, S, "", U, S, ""}, + {jid, U, S, "", U, S, ""}, + {iq, "", set, "", "en", + {xmlelement, "vCard", + [{"xmlns", "vcard-temp"}], [ + {xmlelement, "NICKNAME", [], [{xmlcdata, N}]} + ] + }}) of + {iq, [], result, [], _, []} -> ok; + _ -> error + end + end, + user_action(U, S, Fun, ok); + +%% set_rosternick struct[{user, String}, {server, String}, {nick, String}] Integer +handler(_State, {call, set_rosternick, [{struct, Struct}]}) -> + [{nick, N}, {server, S}, {user, U}] = lists:sort(Struct), + Fun = fun() -> change_rosternick(U, S, N) end, + user_action(U, S, Fun, ok); + +%% add_rosteritem struct[{user, String}, {server, String}, +%% {jid, String}, {group, String}, {nick, String}, {subs, String}] Integer +handler(_State, {call, add_rosteritem, [{struct, Struct}]}) -> + [{group, G},{jid, JID},{nick, N},{server, S},{subs, Subs},{user, U}] = lists:sort(Struct), + Fun = fun() -> add_rosteritem(U, S, JID, N, G, Subs) end, + user_action(U, S, Fun, {atomic, ok}); + +%% link_contacts struct[{jid1, String}, {nick1, String}, {jid2, String}, {nick2, String}] Integer +handler(_State, {call, link_contacts, [{struct, Struct}]}) -> + [{jid1, JID1}, {jid2, JID2}, {nick1, Nick1}, {nick2, Nick2}] = lists:sort(Struct), + {U1, S1, _} = jlib:jid_tolower(jlib:string_to_jid(JID1)), + {U2, S2, _} = jlib:jid_tolower(jlib:string_to_jid(JID2)), + case {ejabberd_auth:is_user_exists(U1, S1), ejabberd_auth:is_user_exists(U2, S2)} of + {true, true} -> + case link_contacts(JID1, Nick1, JID2, Nick2) of + {atomic, ok} -> + {false, {response, [0]}}; + _ -> + {false, {response, [1]}} + end; + _ -> + {false, {response, [404]}} + end; + +%% delete_rosteritem struct[{user, String}, {server, String}, {jid, String}] Integer +handler(_State, {call, delete_rosteritem, [{struct, Struct}]}) -> + [{jid, JID}, {server, S}, {user, U}] = lists:sort(Struct), + Fun = fun() -> del_rosteritem(U, S, JID) end, + user_action(U, S, Fun, {atomic, ok}); + +%% unlink_contacts struct[{jid1, String}, {jid2, String}] Integer +handler(_State, {call, unlink_contacts, [{struct, Struct}]}) -> + [{jid1, JID1}, {jid2, JID2}] = lists:sort(Struct), + {U1, S1, _} = jlib:jid_tolower(jlib:string_to_jid(JID1)), + {U2, S2, _} = jlib:jid_tolower(jlib:string_to_jid(JID2)), + case {ejabberd_auth:is_user_exists(U1, S1), ejabberd_auth:is_user_exists(U2, S2)} of + {true, true} -> + case unlink_contacts(JID1, JID2) of + {atomic, ok} -> + {false, {response, [0]}}; + _ -> + {false, {response, [1]}} + end; + _ -> + {false, {response, [404]}} + end; + +%% get_roster struct[{user, String}, {server, String}] +%% array[struct[{jid, String}, {group, String}, {nick, String}, +%% {subscription, String}, {pending, String}]] +handler(_State, {call, get_roster, [{struct, Struct}]}) -> + [{server, S}, {user, U}] = lists:sort(Struct), + case ejabberd_auth:is_user_exists(U, S) of + true -> + Roster = format_roster(get_roster(U, S)), + {false, {response, [{array, Roster}]}}; + false -> + {false, {response, [404]}} + end; + +%% get_roster_with_presence struct[{user, String}, {server, String}] +%% array[struct[{jid, String}, {resource, String}, {group, String}, {nick, String}, +%% {subscription, String}, {pending, String}, +%% {show, String}, {status, String}]] +handler(_State, {call, get_roster_with_presence, [{struct, Struct}]}) -> + [{server, S}, {user, U}] = lists:sort(Struct), + case ejabberd_auth:is_user_exists(U, S) of + true -> + Roster = format_roster_with_presence(get_roster(U, S)), + {false, {response, [{array, Roster}]}}; + false -> + {false, {response, [404]}} + end; + +%% get_presence struct[{user, String}, {server, String}] +%% array[struct[{jid, String}, {show, String}, {status, String}]] +handler(_State, {call, get_presence, [{struct, Struct}]}) -> + [{server, S}, {user, U}] = lists:sort(Struct), + case ejabberd_auth:is_user_exists(U, S) of + true -> + {Resource, Show, Status} = get_presence(U, S), + FullJID = case Resource of + [] -> + lists:flatten([U,"@",S]); + _ -> + lists:flatten([U,"@",S,"/",Resource]) + end, + R = {struct, [{jid, FullJID}, {show, Show}, {status, Status} ]}, + {false, {response, [R]}}; + false -> + {false, {response, [404]}} + end; + +%% get_resources struct[{user, String}, {server, String}] +%% array[String] +handler(_State, {call, get_resources, [{struct, Struct}]}) -> + [{server, S}, {user, U}] = lists:sort(Struct), + case ejabberd_auth:is_user_exists(U, S) of + true -> + Resources = get_resources(U, S), + {false, {response, [{array, Resources}]}}; + false -> + {false, {response, [404]}} + end; + +%% send_chat struct[{from, String}, {to, String}, {body, String}] +%% Integer +handler(_State, {call, send_chat, [{struct, Struct}]}) -> + [{body, Msg}, {from, FromJID}, {to, ToJID}] = lists:sort(Struct), + From = jlib:string_to_jid(FromJID), + To = jlib:string_to_jid(ToJID), + Stanza = {xmlelement, "message", [{"type", "chat"}], + [{xmlelement, "body", [], [{xmlcdata, Msg}]}]}, + ejabberd_router:route(From, To, Stanza), + {false, {response, [0]}}; + +%% send_message struct[{from, String}, {to, String}, {subject, String}, {body, String}] +%% Integer +handler(_State, {call, send_message, [{struct, Struct}]}) -> + [{body, Msg}, {from, FromJID}, {subject, Sub}, {to, ToJID}] = lists:sort(Struct), + From = jlib:string_to_jid(FromJID), + To = jlib:string_to_jid(ToJID), + Stanza = {xmlelement, "message", [{"type", "normal"}], + [{xmlelement, "subject", [], [{xmlcdata, Sub}]}, + {xmlelement, "body", [], [{xmlcdata, Msg}]}]}, + ejabberd_router:route(From, To, Stanza), + {false, {response, [0]}}; + +%% send_stanza struct[{from, String}, {to, String}, {stanza, String}] +%% Integer +handler(_State, {call, send_stanza, [{struct, Struct}]}) -> + [{from, FromJID}, {stanza, StanzaStr}, {to, ToJID}] = lists:sort(Struct), + case xml_stream:parse_element(StanzaStr) of + {error, _} -> + {false, {response, [1]}}; + Stanza -> + {xmlelement, _, Attrs, _} = Stanza, + From = jlib:string_to_jid(proplists:get_value("from", Attrs, FromJID)), + To = jlib:string_to_jid(proplists:get_value("to", Attrs, ToJID)), + ejabberd_router:route(From, To, Stanza), + {false, {response, [0]}} + end; + +%% rename_account struct[{user, String}, {server, String}, {newuser, String}, {newserver, String}] +%% Integer +handler(_State, {call, rename_account, [{struct, Struct}]}) -> + [{newserver, NS}, {newuser, NU}, {server, S}, {user, U}] = lists:sort(Struct), + case ejabberd_auth:is_user_exists(U, S) of + true -> + case ejabberd_auth:get_password(U, S) of + false -> + {false, {response, [1]}}; + Password -> + case ejabberd_auth:try_register(NU, NS, Password) of + {atomic, ok} -> + OldJID = jlib:jid_to_string({U, S, ""}), + NewJID = jlib:jid_to_string({NU, NS, ""}), + Roster = get_roster(U, S), + lists:foreach(fun(#roster{jid={RU, RS, RE}, name=Nick, groups=Groups}) -> + NewGroup = extract_group(Groups), + {NewNick, Group} = case lists:filter(fun(#roster{jid={PU, PS, _}}) -> + (PU == U) and (PS == S) + end, get_roster(RU, RS)) of + [#roster{name=OldNick, groups=OldGroups}|_] -> {OldNick, extract_group(OldGroups)}; + [] -> {NU, []} + end, + JIDStr = jlib:jid_to_string({RU, RS, RE}), + link_contacts(NewJID, NewNick, NewGroup, JIDStr, Nick, Group), + unlink_contacts(OldJID, JIDStr) + end, Roster), + ejabberd_auth:remove_user(U, S), + {false, {response, [0]}}; + {atomic, exists} -> + {false, {response, [409]}}; + _ -> + {false, {response, [1]}} + end + end; + false -> + {false, {response, [404]}} + end; + +%% add_contacts struct[{user, String}, {server, String}, +%% array[struct[{jid, String}, {group, String}, {nick, String}]]] +%% Integer +handler(_State, {call, add_contacts, [{struct, Struct}]}) -> + [{array, Contacts}, {server, S}, {user, U}] = lists:sort(Struct), + case ejabberd_auth:is_user_exists(U, S) of + true -> + JID1 = jlib:jid_to_string({U, S, ""}), + Response = lists:foldl(fun({struct, Struct2}, Acc) -> + [{group, Group}, {jid, JID2}, {nick, Nick}] = lists:sort(Struct2), + {PU, PS, _} = jlib:jid_tolower(jlib:string_to_jid(JID2)), + case ejabberd_auth:is_user_exists(PU, PS) of + true -> + case link_contacts(JID1, "", "", JID2, Nick, Group) of + {atomic, ok} -> Acc; + _ -> 1 + end; + false -> + Acc + end + end, 0, element(2, Contacts)), + {false, {response, [Response]}}; + false -> + {false, {response, [404]}} + end; + +%% remove_contacts struct[{user, String}, {server, String}, array[String]] +%% Integer +handler(_State, {call, remove_contacts, [{struct, Struct}]}) -> + [{array, Contacts}, {server, S}, {user, U}] = lists:sort(Struct), + case ejabberd_auth:is_user_exists(U, S) of + true -> + JID1 = jlib:jid_to_string({U, S, ""}), + Response = lists:foldl(fun(JID2, Acc) -> + {PU, PS, _} = jlib:jid_tolower(jlib:string_to_jid(JID2)), + case ejabberd_auth:is_user_exists(PU, PS) of + true -> + case unlink_contacts(JID1, JID2) of + {atomic, ok} -> Acc; + _ -> 1 + end; + false -> + Acc + end + end, 0, element(2, Contacts)), + {false, {response, [Response]}}; + false -> + {false, {response, [404]}} + end; + +%% check_users_registration array[struct[{user, String}, {server, String}]] +%% array[struct[{user, String}, {server, String}, {status, Integer}]] +handler(_State, {call, check_users_registration, [{array, Users}]}) -> + Response = lists:map(fun({struct, Struct}) -> + [{server, S}, {user, U}] = lists:sort(Struct), + Registered = case ejabberd_auth:is_user_exists(U, S) of + true -> 1; + false -> 0 + end, + {struct, [{user, U}, {server, S}, {status, Registered}]} + end, Users), + {false, {response, [{array, Response}]}}; + + +%% If no other guard matches +handler(_State, Payload) -> + FaultString = lists:flatten(io_lib:format("Unknown call: ~p", [Payload])), + {false, {response, {fault, -1, FaultString}}}. + + +%% ----------------------------- +%% Internal roster handling +%% ----------------------------- + +get_roster(User, Server) -> + LUser = jlib:nodeprep(User), + LServer = jlib:nameprep(Server), + ejabberd_hooks:run_fold(roster_get, LServer, [], [{LUser, LServer}]). + +change_rosternick(User, Server, Nick) -> + LUser = jlib:nodeprep(User), + LServer = jlib:nameprep(Server), + LJID = {LUser, LServer, []}, + JID = jlib:jid_to_string(LJID), + Push = fun(Subscription) -> + jlib:iq_to_xml(#iq{type = set, xmlns = ?NS_ROSTER, id = "push", + sub_el = [{xmlelement, "query", [{"xmlns", ?NS_ROSTER}], + [{xmlelement, "item", [{"jid", JID}, {"name", Nick}, {"subscription", atom_to_list(Subscription)}], + []}]}]}) + end, + Result = case roster_backend(Server) of + mnesia -> + %% XXX This way of doing can not work with s2s + mnesia:transaction( + fun() -> + lists:foreach(fun(Roster) -> + {U, S} = Roster#roster.us, + mnesia:write(Roster#roster{name = Nick}), + lists:foreach(fun(R) -> + UJID = jlib:make_jid(U, S, R), + ejabberd_router:route(UJID, UJID, Push(Roster#roster.subscription)) + end, get_resources(U, S)) + end, mnesia:match_object(#roster{jid = LJID, _ = '_'})) + end); + odbc -> + %%% XXX This way of doing does not work with several domains + ejabberd_odbc:sql_transaction(Server, + fun() -> + SNick = ejabberd_odbc:escape(Nick), + SJID = ejabberd_odbc:escape(JID), + ejabberd_odbc:sql_query_t( + ["update rosterusers" + " set nick='", SNick, "'" + " where jid='", SJID, "';"]), + case ejabberd_odbc:sql_query_t( + ["select username from rosterusers" + " where jid='", SJID, "'" + " and subscription = 'B';"]) of + {selected, ["username"], Users} -> + lists:foreach(fun({RU}) -> + lists:foreach(fun(R) -> + UJID = jlib:make_jid(RU, Server, R), + ejabberd_router:route(UJID, UJID, Push(both)) + end, get_resources(RU, Server)) + end, Users); + _ -> + ok + end + end); + none -> + {error, no_roster} + end, + case Result of + {atomic, ok} -> ok; + _ -> error + end. + +add_rosteritem(User, Server, JID, Nick, Group, Subscription) -> + add_rosteritem(User, Server, JID, Nick, Group, Subscription, true). +add_rosteritem(User, Server, JID, Nick, Group, Subscription, Push) -> + {RU, RS, _} = jlib:jid_tolower(jlib:string_to_jid(JID)), + LJID = {RU,RS,[]}, + Groups = case Group of + [] -> []; + _ -> [Group] + end, + Roster = #roster{ + usj = {User,Server,LJID}, + us = {User,Server}, + jid = LJID, + name = Nick, + ask = none, + subscription = list_to_atom(Subscription), + groups = Groups}, + Result = + case roster_backend(Server) of + mnesia -> + mnesia:transaction(fun() -> + case mnesia:read({roster,{User,Server,LJID}}) of + [#roster{subscription=both}] -> + already_added; + _ -> + mnesia:write(Roster) + end + end); + odbc -> + %% MREMOND: TODO: check if already_added + case ejabberd_odbc:sql_transaction(Server, + fun() -> + Username = ejabberd_odbc:escape(User), + SJID = ejabberd_odbc:escape(jlib:jid_to_string(LJID)), + case ejabberd_odbc:sql_query_t( + ["select username from rosterusers " + " where username='", Username, "' " + " and jid='", SJID, + "' and subscription = 'B';"]) of + {selected, ["username"],[]} -> + ItemVals = record_to_string(Roster), + ItemGroups = groups_to_string(Roster), + odbc_queries:update_roster(Server, Username, + SJID, ItemVals, + ItemGroups); + _ -> + already_added + end + end) of + {atomic, already_added} -> {atomic, already_added}; + {atomic, _} -> {atomic, ok}; + Error -> Error + end; + none -> + {error, no_roster} + end, + case {Result, Push} of + {{atomic, already_added}, _} -> ok; %% No need for roster push + {{atomic, ok}, true} -> roster_push(User, Server, JID, Nick, Subscription); + {{error, no_roster}, true} -> roster_push(User, Server, JID, Nick, Subscription); + {{atomic, ok}, false} -> ok; + _ -> error + end, + Result. + +del_rosteritem(User, Server, JID) -> + del_rosteritem(User, Server, JID, true). +del_rosteritem(User, Server, JID, Push) -> + {RU, RS, _} = jlib:jid_tolower(jlib:string_to_jid(JID)), + LJID = {RU,RS,[]}, + Result = case roster_backend(Server) of + mnesia -> + mnesia:transaction(fun() -> + mnesia:delete({roster, {User,Server,LJID}}) + end); + odbc -> + case ejabberd_odbc:sql_transaction(Server, fun() -> + Username = ejabberd_odbc:escape(User), + SJID = ejabberd_odbc:escape(jlib:jid_to_string(LJID)), + odbc_queries:del_roster(Server, Username, SJID) + end) of + {atomic, _} -> {atomic, ok}; + Error -> Error + end; + none -> + {error, no_roster} + end, + case {Result, Push} of + {{atomic, ok}, true} -> roster_push(User, Server, JID, "", "remove"); + {{error, no_roster}, true} -> roster_push(User, Server, JID, "", "remove"); + {{atomic, ok}, false} -> ok; + _ -> error + end, + Result. + +link_contacts(JID1, Nick1, JID2, Nick2) -> + link_contacts(JID1, Nick1, JID2, Nick2, true). +link_contacts(JID1, Nick1, JID2, Nick2, Push) -> + link_contacts(JID1, Nick1, [], JID2, Nick2, [], Push). + +link_contacts(JID1, Nick1, Group1, JID2, Nick2, Group2) -> + link_contacts(JID1, Nick1, Group1, JID2, Nick2, Group2, true). +link_contacts(JID1, Nick1, Group1, JID2, Nick2, Group2, Push) -> + {U1, S1, _} = jlib:jid_tolower(jlib:string_to_jid(JID1)), + {U2, S2, _} = jlib:jid_tolower(jlib:string_to_jid(JID2)), + case add_rosteritem(U1, S1, JID2, Nick2, Group1, "both", Push) of + {atomic, ok} -> add_rosteritem(U2, S2, JID1, Nick1, Group2, "both", Push); + Error -> Error + end. + +unlink_contacts(JID1, JID2) -> + unlink_contacts(JID1, JID2, true). +unlink_contacts(JID1, JID2, Push) -> + {U1, S1, _} = jlib:jid_tolower(jlib:string_to_jid(JID1)), + {U2, S2, _} = jlib:jid_tolower(jlib:string_to_jid(JID2)), + case del_rosteritem(U1, S1, JID2, Push) of + {atomic, ok} -> del_rosteritem(U2, S2, JID1, Push); + Error -> Error + end. + +roster_push(User, Server, JID, Nick, Subscription) -> + LJID = jlib:make_jid(User, Server, ""), + TJID = jlib:string_to_jid(JID), + {TU, TS, _} = jlib:jid_tolower(TJID), + Presence = {xmlelement, "presence", [{"type", + case Subscription of + "remove" -> "unsubscribed"; + "none" -> "unsubscribe"; + "both" -> "subscribed"; + _ -> "subscribe" + end}], []}, + Item = case Nick of + "" -> [{"jid", JID}, {"subscription", Subscription}]; + _ -> [{"jid", JID}, {"name", Nick}, {"subscription", Subscription}] + end, + Result = jlib:iq_to_xml(#iq{type = set, xmlns = ?NS_ROSTER, id = "push", + sub_el = [{xmlelement, "query", [{"xmlns", ?NS_ROSTER}], + [{xmlelement, "item", Item, []}]}]}), + ejabberd_router:route(TJID, LJID, Presence), + ejabberd_router:route(LJID, LJID, Result), + lists:foreach(fun(Resource) -> + UJID = jlib:make_jid(User, Server, Resource), + ejabberd_router:route(TJID, UJID, Presence), + ejabberd_router:route(UJID, UJID, Result), + case Subscription of + "remove" -> none; + _ -> + lists:foreach(fun(TR) -> + ejabberd_router:route(jlib:make_jid(TU, TS, TR), UJID, + {xmlelement, "presence", [], []}) + end, get_resources(TU, TS)) + end + end, [R || R <- get_resources(User, Server), Subscription =/= "remove"]). + +roster_backend(Server) -> + Modules = gen_mod:loaded_modules(Server), + Mnesia = lists:member(mod_roster, Modules), + Odbc = lists:member(mod_roster_odbc, Modules), + if Mnesia -> mnesia; + true -> + if Odbc -> odbc; + true -> none + end + end. + +record_to_string(#roster{us = {User, _Server}, + jid = JID, + name = Name, + subscription = Subscription, + ask = Ask, + askmessage = AskMessage}) -> + Username = ejabberd_odbc:escape(User), + SJID = ejabberd_odbc:escape(jlib:jid_to_string(jlib:jid_tolower(JID))), + Nick = ejabberd_odbc:escape(Name), + SSubscription = case Subscription of + both -> "B"; + to -> "T"; + from -> "F"; + none -> "N" + end, + SAsk = case Ask of + subscribe -> "S"; + unsubscribe -> "U"; + both -> "B"; + out -> "O"; + in -> "I"; + none -> "N" + end, + SAskMessage = ejabberd_odbc:escape(AskMessage), + ["'", Username, "'," + "'", SJID, "'," + "'", Nick, "'," + "'", SSubscription, "'," + "'", SAsk, "'," + "'", SAskMessage, "'," + "'N', '', 'item'"]. + +groups_to_string(#roster{us = {User, _Server}, + jid = JID, + groups = Groups}) -> + Username = ejabberd_odbc:escape(User), + SJID = ejabberd_odbc:escape(jlib:jid_to_string(jlib:jid_tolower(JID))), + %% Empty groups do not need to be converted to string to be inserted in + %% the database + lists:foldl(fun([], Acc) -> Acc; + (Group, Acc) -> + String = ["'", Username, "'," + "'", SJID, "'," + "'", ejabberd_odbc:escape(Group), "'"], + [String|Acc] + end, [], Groups). + +%% Format roster items as a list of: +%% [{struct, [{jid, "test@localhost"},{group, "Friends"},{nick, "Nicktest"}]}] +format_roster([]) -> + []; +format_roster(Items) -> + format_roster(Items, []). +format_roster([], Structs) -> + Structs; +format_roster([#roster{jid=JID, name=Nick, groups=Group, + subscription=Subs, ask=Ask}|Items], Structs) -> + {User,Server,_Resource} = JID, + Struct = {struct, [{jid,lists:flatten([User,"@",Server])}, + {group, extract_group(Group)}, + {nick, Nick}, + {subscription, atom_to_list(Subs)}, + {pending, atom_to_list(Ask)} + ]}, + format_roster(Items, [Struct|Structs]). + +%% Format roster items as a list of: +%% [{struct, [{jid, "test@localhost"}, {resource, "Messenger"}, {group, "Friends"}, +%% {nick, "Nicktest"},{show, "available"}, {status, "Currently at office"}]}] +%% Note: If user is connected several times, only keep the resource with the +%% highest non-negative priority +format_roster_with_presence([]) -> + []; +format_roster_with_presence(Items) -> + format_roster_with_presence(Items, []). +format_roster_with_presence([], Structs) -> + Structs; +format_roster_with_presence([#roster{jid=JID, name=Nick, groups=Group, + subscription=Subs, ask=Ask}|Items], Structs) -> + {User,Server,_R} = JID, + Presence = case Subs of + both -> get_presence(User, Server); + from -> get_presence(User, Server); + _Other -> {"", "unavailable", ""} + end, + {Resource, Show, Status} = + case Presence of + {_R, "invisible", _S} -> {"", "unavailable", ""}; + _Status -> Presence + end, + Struct = {struct, [{jid,lists:flatten([User,"@",Server])}, + {resource, Resource}, + {group, extract_group(Group)}, + {nick, Nick}, + {subscription, atom_to_list(Subs)}, + {pending, atom_to_list(Ask)}, + {show, Show}, + {status, Status} + ]}, + format_roster_with_presence(Items, [Struct|Structs]). + +extract_group([]) -> []; +extract_group([Group|_Groups]) -> Group. + +%% ----------------------------- +%% Internal session handling +%% ----------------------------- + +%% This is inspired from ejabberd_sm.erl +get_presence(User, Server) -> + case get_sessions(User, Server) of + [] -> + {"", "unavailable", ""}; + Ss -> + Session = hd(Ss), + if Session#session.priority >= 0 -> + Pid = element(2, Session#session.sid), + %{_User, _Resource, Show, Status} = rpc:call(node(Pid), ejabberd_c2s, get_presence, [Pid]), + {_User, Resource, Show, Status} = ejabberd_c2s:get_presence(Pid), + {Resource, Show, Status}; + true -> + {"", "unavailable", ""} + end + end. + +get_resources(User, Server) -> + lists:map(fun(S) -> element(3, S#session.usr) + end, get_sessions(User, Server)). + +get_sessions(User, Server) -> + LUser = jlib:nodeprep(User), + LServer = jlib:nameprep(Server), + case catch mnesia:dirty_index_read(session, {LUser, LServer}, #session.us) of + {'EXIT', _Reason} -> []; + [] -> []; + Result -> lists:reverse(lists:keysort(#session.priority, clean_session_list(Result))) + end. + +clean_session_list(Ss) -> + clean_session_list(lists:keysort(#session.usr, Ss), []). + +clean_session_list([], Res) -> + Res; +clean_session_list([S], Res) -> + [S | Res]; +clean_session_list([S1, S2 | Rest], Res) -> + if + S1#session.usr == S2#session.usr -> + if + S1#session.sid > S2#session.sid -> + clean_session_list([S1 | Rest], Res); + true -> + clean_session_list([S2 | Rest], Res) + end; + true -> + clean_session_list([S2 | Rest], [S1 | Res]) + end. + + +%% ----------------------------- +%% Internal function pattern +%% ----------------------------- + +user_action(User, Server, Fun, OK) -> + case ejabberd_auth:is_user_exists(User, Server) of + true -> + case catch Fun() of + OK -> + {false, {response, [0]}}; + _ -> + {false, {response, [1]}} + end; + false -> + {false, {response, [404]}} + end. From d87fff1a4c500d9abe3945cbfea792b4eddfa3f2 Mon Sep 17 00:00:00 2001 From: Badlop Date: Thu, 19 Aug 2010 17:37:21 +0200 Subject: [PATCH 15/85] Bugfix http-poll for correctly parsing binary (thanks to Peter Lemenkov) --- src/web/ejabberd_http_poll.erl | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/web/ejabberd_http_poll.erl b/src/web/ejabberd_http_poll.erl index 0bdbc6287..faa0f3c17 100644 --- a/src/web/ejabberd_http_poll.erl +++ b/src/web/ejabberd_http_poll.erl @@ -272,7 +272,13 @@ handle_event(_Event, StateName, StateData) -> %% {stop, Reason, Reply, NewStateData} %%---------------------------------------------------------------------- handle_sync_event({send, Packet}, _From, StateName, StateData) -> - Output = StateData#state.output ++ [lists:flatten(Packet)], + Packet2 = if + is_binary(Packet) -> + binary_to_list(Packet); + true -> + Packet + end, + Output = StateData#state.output ++ [lists:flatten(Packet2)], Reply = ok, {reply, Reply, StateName, StateData#state{output = Output}}; From 4b5ef8f2cefbddfaa468fe30a0a205da51b330d2 Mon Sep 17 00:00:00 2001 From: Badlop Date: Sat, 21 Aug 2010 18:56:01 +0200 Subject: [PATCH 16/85] Add mod_pubsub_odbc to list of ODBC modules (EJAB-1293) --- doc/guide.html | 5 +++-- doc/guide.tex | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/doc/guide.html b/doc/guide.html index 57873a873..50cdca74a 100644 --- a/doc/guide.html +++ b/doc/guide.html @@ -1944,8 +1944,8 @@ Mnesia as backend. (see 3.2) as backend.
  • ‘_ldap’, this means that the module needs an LDAP server as backend.
  • If you want to, -it is possible to use a relational database to store pieces of -information. You can do this by changing the module name to a name with an +it is possible to use a relational database to store the tables created by some ejabberd modules. +You can do this by changing the module name to a name with an _odbc suffix in ejabberd config file. You can use a relational database for the following data:

    • Last connection date and time: Use mod_last_odbc instead of @@ -1956,6 +1956,7 @@ Last connection date and time: Use mod_last_odbc instead of
    • Users’ VCARD: Use mod_vcard_odbc instead of mod_vcard.
    • Private XML storage: Use mod_private_odbc instead of mod_private.
    • User rules for blocking communications: Use mod_privacy_odbc instead of mod_privacy. +
    • Pub-Sub nodes, items and subscriptions: Use mod_pubsub_odbc instead of mod_pubsub.

    You can find more contributed modules on the ejabberd website. Please remember that these contributions might not work or diff --git a/doc/guide.tex b/doc/guide.tex index 044fab829..73f848f52 100644 --- a/doc/guide.tex +++ b/doc/guide.tex @@ -2560,8 +2560,8 @@ You can see which database backend each module needs by looking at the suffix: \end{itemize} If you want to, -it is possible to use a relational database to store pieces of -information. You can do this by changing the module name to a name with an +it is possible to use a relational database to store the tables created by some ejabberd modules. +You can do this by changing the module name to a name with an \term{\_odbc} suffix in \ejabberd{} config file. You can use a relational database for the following data: @@ -2574,6 +2574,7 @@ database for the following data: \item Users' VCARD: Use \term{mod\_vcard\_odbc} instead of \term{mod\_vcard}. \item Private XML storage: Use \term{mod\_private\_odbc} instead of \term{mod\_private}. \item User rules for blocking communications: Use \term{mod\_privacy\_odbc} instead of \term{mod\_privacy}. +\item Pub-Sub nodes, items and subscriptions: Use \term{mod\_pubsub\_odbc} instead of \term{mod\_pubsub}. \end{itemize} You can find more From 695232450925071d40fedd0c5e727d336e1d5af6 Mon Sep 17 00:00:00 2001 From: Evgeniy Khramtsov Date: Mon, 30 Aug 2010 14:02:47 +1000 Subject: [PATCH 17/85] implemented backend-independed key-value cacheing table; applied to mod_caps.erl first --- src/cache_tab.erl | 480 ++++++++++++++++++++++++++++++++++++++++++ src/cache_tab_sup.erl | 34 +++ src/ejabberd_sup.erl | 8 + src/mod_caps.erl | 61 ++++-- 4 files changed, 569 insertions(+), 14 deletions(-) create mode 100644 src/cache_tab.erl create mode 100644 src/cache_tab_sup.erl diff --git a/src/cache_tab.erl b/src/cache_tab.erl new file mode 100644 index 000000000..e2551ec78 --- /dev/null +++ b/src/cache_tab.erl @@ -0,0 +1,480 @@ +%%%------------------------------------------------------------------- +%%% File : cache_tab.erl +%%% Author : Evgeniy Khramtsov +%%% Description : Caching key-value table +%%% +%%% Created : 29 Aug 2010 by Evgeniy Khramtsov +%%%------------------------------------------------------------------- +-module(cache_tab). + +-define(GEN_SERVER, gen_server). + +-behaviour(?GEN_SERVER). + +%% API +-export([start_link/4, new/2, delete/1, delete/3, lookup/3, + insert/4, info/2, tab2list/1, setopts/2, all/0, test/0]). + +%% gen_server callbacks +-export([init/1, handle_call/3, handle_cast/2, handle_info/2, + terminate/2, code_change/3]). + +-include("ejabberd.hrl"). + +-record(state, {tab = treap:empty(), + name, + size = 0, + owner, + max_size, + life_time, + warn, + hits = 0, + miss = 0, + procs_num, + cache_missed, + shrink_size}). + +-define(PROCNAME, ?MODULE). +-define(CALL_TIMEOUT, 60000). + +%% Defaults +-define(MAX_SIZE, 1000). +-define(WARN, true). +-define(CACHE_MISSED, true). +-define(LIFETIME, 600). %% 10 minutes + +%%==================================================================== +%% API +%%==================================================================== +start_link(Proc, Tab, Opts, Owner) -> + ?GEN_SERVER:start_link( + {local, Proc}, ?MODULE, [Tab, Opts, get_proc_num(), Owner], []). + +new(Tab, Opts) -> + Res = lists:flatmap( + fun(Proc) -> + Spec = {{Tab, Proc}, + {?MODULE, start_link, + [Proc, Tab, Opts, self()]}, + permanent, + brutal_kill, + worker, + [?MODULE]}, + case supervisor:start_child(cache_tab_sup, Spec) of + {ok, _Pid} -> + [ok]; + R -> + [R] + end + end, get_all_procs(Tab)), + case lists:filter(fun(ok) -> false; (_) -> true end, Res) of + [] -> + ok; + Err -> + {error, Err} + end. + +delete(Tab) -> + lists:foreach( + fun(Proc) -> + supervisor:terminate_child(cache_tab_sup, {Tab, Proc}), + supervisor:delete_child(cache_tab_sup, {Tab, Proc}) + end, get_all_procs(Tab)). + +delete(Tab, Key, F) -> + ?GEN_SERVER:call( + get_proc_by_hash(Tab, Key), {delete, Key, F}, ?CALL_TIMEOUT). + +lookup(Tab, Key, F) -> + ?GEN_SERVER:call( + get_proc_by_hash(Tab, Key), {lookup, Key, F}, ?CALL_TIMEOUT). + +insert(Tab, Key, Val, F) -> + ?GEN_SERVER:call( + get_proc_by_hash(Tab, Key), {insert, Key, Val, F}, ?CALL_TIMEOUT). + +info(Tab, Info) -> + case lists:map( + fun(Proc) -> + ?GEN_SERVER:call(Proc, {info, Info}, ?CALL_TIMEOUT) + end, get_all_procs(Tab)) of + Res when Info == size -> + {ok, lists:sum(Res)}; + Res when Info == all -> + {ok, Res}; + Res when Info == ratio -> + {H, M} = lists:foldl( + fun({Hits, Miss}, {HitsAcc, MissAcc}) -> + {HitsAcc + Hits, MissAcc + Miss} + end, {0, 0}, Res), + {ok, [{hits, H}, {miss, M}]}; + _ -> + {error, badarg} + end. + +setopts(Tab, Opts) -> + lists:foreach( + fun(Proc) -> + ?GEN_SERVER:call(Proc, {setopts, Opts}, ?CALL_TIMEOUT) + end, get_all_procs(Tab)). + +tab2list(Tab) -> + lists:flatmap( + fun(Proc) -> + ?GEN_SERVER:call(Proc, tab2list, ?CALL_TIMEOUT) + end, get_all_procs(Tab)). + +all() -> + lists:usort( + [Tab || {{Tab, _}, _, _, _} <- supervisor:which_children(cache_tab_sup)]). + +%%==================================================================== +%% gen_server callbacks +%%==================================================================== +init([Tab, Opts, N, Pid]) -> + State = #state{procs_num = N, + owner = Pid, + name = Tab}, + {ok, do_setopts(State, Opts)}. + +handle_call({lookup, Key, F}, _From, #state{tab = T} = State) -> + case treap:lookup(Key, T) of + {ok, _Prio, Val} -> + Hits = State#state.hits, + NewState = treap_update(Key, Val, State#state{hits = Hits + 1}), + case Val of + '$cached_mismatch' -> + {reply, error, NewState}; + _ -> + {reply, {ok, Val}, NewState} + end; + _ -> + case catch F() of + {ok, Val} -> + Miss = State#state.miss, + NewState = treap_insert(Key, Val, State), + {reply, {ok, Val}, NewState#state{miss = Miss + 1}}; + {'EXIT', Reason} -> + print_error(lookup, [Key], Reason, State), + {reply, error, State}; + _ -> + Miss = State#state.miss, + NewState = State#state{miss = Miss + 1}, + if State#state.cache_missed -> + {reply, error, + treap_insert(Key, '$cached_mismatch', NewState)}; + true -> + {reply, error, NewState} + end + end + end; +handle_call({insert, Key, Val, F}, _From, #state{tab = T} = State) -> + case treap:lookup(Key, T) of + {ok, _Prio, Val} -> + {reply, ok, State}; + Res -> + case catch F() of + {'EXIT', Reason} -> + print_error(insert, [Key, Val], Reason, State), + {reply, ok, State}; + _ -> + NewState = case Res of + {ok, _, _} -> + treap_update(Key, Val, State); + _ -> + treap_insert(Key, Val, State) + end, + {reply, ok, NewState} + end + end; +handle_call({delete, Key, F}, _From, State) -> + NewState = treap_delete(Key, State), + case catch F() of + {'EXIT', Reason} -> + print_error(delete, [Key], Reason, State); + _ -> + ok + end, + {reply, ok, NewState}; +handle_call({info, Info}, _From, State) -> + Res = case Info of + size -> + State#state.size; + ratio -> + {State#state.hits, State#state.miss}; + all -> + [{max_size, State#state.max_size}, + {life_time, State#state.life_time}, + {shrink_size, State#state.shrink_size}, + {size, State#state.size}, + {owner, State#state.owner}, + {hits, State#state.hits}, + {miss, State#state.miss}, + {cache_missed, State#state.cache_missed}, + {warn, State#state.warn}]; + _ -> + badarg + end, + {reply, Res, State}; +handle_call(tab2list, _From, #state{tab = T} = State) -> + Res = treap:fold( + fun({Key, _, Val}, Acc) -> + [{Key, Val}|Acc] + end, [], T), + {reply, Res, State}; +handle_call({setopts, Opts}, _From, State) -> + {reply, ok, do_setopts(State, Opts)}; +handle_call(_Request, _From, State) -> + Reply = ok, + {reply, Reply, State}. + +handle_cast(_Msg, State) -> + {noreply, State}. + +handle_info(_Info, State) -> + {noreply, State}. + +terminate(_Reason, _State) -> + ok. + +code_change(_OldVsn, State, _Extra) -> + {ok, State}. + +%%-------------------------------------------------------------------- +%%% Internal functions +%%-------------------------------------------------------------------- +do_setopts(#state{procs_num = N} = State, Opts) -> + MaxSize = case {proplists:get_value(max_size, Opts), + State#state.max_size} of + {MS, _} when is_integer(MS), MS > 0 -> + round(MS/N); + {unlimited, _} -> + unlimited; + {_, undefined} -> + round(?MAX_SIZE/N); + {_, MS} -> + MS + end, + LifeTime = case {proplists:get_value(life_time, Opts), + State#state.life_time} of + {LT, _} when is_integer(LT), LT > 0 -> + LT*1000; + {unlimited, _} -> + unlimited; + {_, undefined} -> + ?LIFETIME*1000; + {_, LT} -> + LT + end, + ShrinkSize = case {proplists:get_value(shrink_size, Opts), + State#state.shrink_size} of + {SS, _} when is_integer(SS), SS > 0 -> + round(SS/N); + _ when is_integer(MaxSize) -> + round(MaxSize/2); + _ -> + unlimited + end, + Warn = case {proplists:get_value(warn, Opts), + State#state.warn} of + {true, _} -> + true; + {false, _} -> + false; + {_, undefined} -> + ?WARN; + {_, W} -> + W + end, + CacheMissed = case proplists:get_value( + cache_missed, Opts, State#state.cache_missed) of + false -> + false; + true -> + true; + _ -> + ?CACHE_MISSED + end, + State#state{max_size = MaxSize, + warn = Warn, + life_time = LifeTime, + cache_missed = CacheMissed, + shrink_size = ShrinkSize}. + +get_proc_num() -> + erlang:system_info(logical_processors). + +get_proc_by_hash(Tab, Term) -> + N = erlang:phash2(Term, get_proc_num()) + 1, + get_proc(Tab, N). + +get_proc(Tab, N) -> + list_to_atom(atom_to_list(?PROCNAME) ++ "_" ++ + atom_to_list(Tab) ++ "_" ++ integer_to_list(N)). + +get_all_procs(Tab) -> + [get_proc(Tab, N) || N <- lists:seq(1, get_proc_num())]. + +now_priority() -> + {MSec, Sec, USec} = now(), + -((MSec*1000000 + Sec)*1000000 + USec). + +treap_update(Key, Val, #state{tab = T} = State) -> + Priority = now_priority(), + NewT = treap:insert(Key, Priority, Val, T), + State#state{tab = NewT}. + +treap_insert(Key, Val, State) -> + State1 = clean_treap(State), + #state{size = Size} = State2 = shrink_treap(State1), + treap_update(Key, Val, State2#state{size = Size+1}). + +treap_delete(Key, #state{tab = T, size = Size} = State) -> + case treap:lookup(Key, T) of + {ok, _, _} -> + NewT = treap:delete(Key, T), + clean_treap(State#state{tab = NewT, size = Size-1}); + _ -> + State + end. + +clean_treap(#state{tab = T, size = Size, life_time = LifeTime} = State) -> + if is_integer(LifeTime) -> + Priority = now_priority(), + {Cleaned, NewT} = clean_treap(T, Priority + LifeTime, 0), + State#state{size = Size - Cleaned, tab = NewT}; + true -> + State + end. + +clean_treap(Treap, CleanPriority, N) -> + case treap:is_empty(Treap) of + true -> + {N, Treap}; + false -> + {_Key, Priority, _Value} = treap:get_root(Treap), + if Priority > CleanPriority -> + clean_treap(treap:delete_root(Treap), CleanPriority, N+1); + true -> + {N, Treap} + end + end. + +shrink_treap(#state{tab = T, + max_size = MaxSize, + shrink_size = ShrinkSize, + warn = Warn, + size = Size} = State) when Size >= MaxSize -> + if Warn -> + ?WARNING_MSG("shrinking table:~n" + "** Table: ~p~n" + "** Processes Number: ~p~n" + "** Max Size: ~p items~n" + "** Shrink Size: ~p items~n" + "** Life Time: ~p microseconds~n" + "** Hits/Miss: ~p/~p~n" + "** Owner: ~p~n" + "** Cache Missed: ~p~n" + "** Instruction: you have to tune cacheing options" + " if this message repeats too frequently", + [State#state.name, State#state.procs_num, + MaxSize, ShrinkSize, State#state.life_time, + State#state.hits, State#state.miss, + State#state.owner, State#state.cache_missed]); + true -> + ok + end, + {Shrinked, NewT} = shrink_treap(T, ShrinkSize, 0), + State#state{tab = NewT, size = Size - Shrinked}; +shrink_treap(State) -> + State. + +shrink_treap(T, ShrinkSize, ShrinkSize) -> + {ShrinkSize, T}; +shrink_treap(T, ShrinkSize, N) -> + case treap:is_empty(T) of + true -> + {N, T}; + false -> + shrink_treap(treap:delete_root(T), ShrinkSize, N+1) + end. + +print_error(Operation, Args, Reason, State) -> + ?ERROR_MSG("callback failed:~n" + "** Tab: ~p~n" + "** Owner: ~p~n" + "** Operation: ~p~n" + "** Args: ~p~n" + "** Reason: ~p", + [State#state.name, State#state.owner, + Operation, Args, Reason]). + +%%-------------------------------------------------------------------- +%%% Tests +%%-------------------------------------------------------------------- +test() -> + LifeTime = 2, + ok = new(test_tbl, [{life_time, LifeTime}, {max_size, unlimited}]), + check([]), + ok = insert(test_tbl, "key", "value", fun() -> ok end), + check([{"key", "value"}]), + {ok, "value"} = lookup(test_tbl, "key", fun() -> error end), + check([{"key", "value"}]), + io:format("** waiting for ~p seconds to check if cleaner works fine...~n", + [LifeTime+1]), + timer:sleep(timer:seconds(LifeTime+1)), + ok = insert(test_tbl, "key1", "value1", fun() -> ok end), + check([{"key1", "value1"}]), + ok = delete(test_tbl, "key1", fun() -> ok end), + {ok, "value"} = lookup(test_tbl, "key", fun() -> {ok, "value"} end), + check([{"key", "value"}]), + ok = delete(test_tbl, "key", fun() -> ok end), + check([]), + %% io:format("** testing buggy callbacks...~n"), + %% delete(test_tbl, "key", fun() -> erlang:error(badarg) end), + %% insert(test_tbl, "key", "val", fun() -> erlang:error(badarg) end), + %% lookup(test_tbl, "key", fun() -> erlang:error(badarg) end), + check([]), + delete(test_tbl), + test1(). + +test1() -> + MaxSize = 10, + ok = new(test_tbl, [{max_size, MaxSize}, {shrink_size, 1}, {warn, false}]), + lists:foreach( + fun(N) -> + ok = insert(test_tbl, N, N, fun() -> ok end) + end, lists:seq(1, MaxSize*get_proc_num())), + {ok, MaxSize} = info(test_tbl, size), + delete(test_tbl), + success. +%% io:format("** testing speed, this may take a while...~n"), +%% test2(1000), +%% test2(10000), +%% test2(100000), +%% test2(1000000). + +%% test2(Iter) -> +%% ok = new(test_tbl, [{max_size, unlimited}, {life_time, unlimited}]), +%% L = lists:seq(1, Iter), +%% T1 = now(), +%% lists:foreach( +%% fun(N) -> +%% ok = insert(test_tbl, N, N, fun() -> ok end) +%% end, L), +%% io:format("** average insert (size = ~p): ~p usec~n", +%% [Iter, round(timer:now_diff(now(), T1)/Iter)]), +%% T2 = now(), +%% lists:foreach( +%% fun(N) -> +%% {ok, N} = lookup(test_tbl, N, fun() -> ok end) +%% end, L), +%% io:format("** average lookup (size = ~p): ~p usec~n", +%% [Iter, round(timer:now_diff(now(), T2)/Iter)]), +%% {ok, Iter} = info(test_tbl, size), +%% delete(test_tbl). + +check(List) -> + Size = length(List), + {ok, Size} = info(test_tbl, size), + List = tab2list(test_tbl). diff --git a/src/cache_tab_sup.erl b/src/cache_tab_sup.erl new file mode 100644 index 000000000..d417c5488 --- /dev/null +++ b/src/cache_tab_sup.erl @@ -0,0 +1,34 @@ +%%%------------------------------------------------------------------- +%%% File : cache_tab_sup.erl +%%% Author : Evgeniy Khramtsov +%%% Description : +%%% +%%% Created : 30 Aug 2010 by Evgeniy Khramtsov +%%%------------------------------------------------------------------- +-module(cache_tab_sup). + +-behaviour(supervisor). + +%% API +-export([start_link/0]). + +%% Supervisor callbacks +-export([init/1]). + +-define(SERVER, ?MODULE). + +%%==================================================================== +%% API functions +%%==================================================================== +start_link() -> + supervisor:start_link({local, ?SERVER}, ?MODULE, []). + +%%==================================================================== +%% Supervisor callbacks +%%==================================================================== +init([]) -> + {ok, {{one_for_one,10,1}, []}}. + +%%==================================================================== +%% Internal functions +%%==================================================================== diff --git a/src/ejabberd_sup.erl b/src/ejabberd_sup.erl index f0119326a..7dc3068ed 100644 --- a/src/ejabberd_sup.erl +++ b/src/ejabberd_sup.erl @@ -177,6 +177,13 @@ init([]) -> infinity, supervisor, [ejabberd_tmp_sup]}, + CacheTabSupervisor = + {cache_tab_sup, + {cache_tab_sup, start_link, []}, + permanent, + infinity, + supervisor, + [cache_tab_sup]}, {ok, {{one_for_one, 10, 1}, [Hooks, NodeGroups, @@ -196,6 +203,7 @@ init([]) -> IQSupervisor, STUNSupervisor, FrontendSocketSupervisor, + CacheTabSupervisor, Listener]}}. diff --git a/src/mod_caps.erl b/src/mod_caps.erl index d9f4f30c8..01056fbe5 100644 --- a/src/mod_caps.erl +++ b/src/mod_caps.erl @@ -98,11 +98,12 @@ get_features(#caps{node = Node, version = Version, exts = Exts}) -> SubNodes = [Version | Exts], lists:foldl( fun(SubNode, Acc) -> - case mnesia:dirty_read({caps_features, - node_to_binary(Node, SubNode)}) of - [] -> + BinaryNode = node_to_binary(Node, SubNode), + case cache_tab:lookup(caps_features, BinaryNode, + caps_read_fun(BinaryNode)) of + error -> Acc; - [#caps_features{features = Features}] -> + {ok, Features} -> binary_to_features(Features) ++ Acc end end, [], SubNodes). @@ -196,12 +197,23 @@ disco_info(Acc, _Host, _Module, _Node, _Lang) -> %%==================================================================== %% gen_server callbacks %%==================================================================== -init([Host, _Opts]) -> +init([Host, Opts]) -> + case catch mnesia:table_info(caps_features, storage_type) of + {'EXIT', _} -> + ok; + disc_only_copies -> + ok; + _ -> + mnesia:delete_table(caps_features) + end, mnesia:create_table(caps_features, - [{disc_copies, [node()]}, + [{disc_only_copies, [node()]}, {local_content, true}, {attributes, record_info(fields, caps_features)}]), - mnesia:add_table_copy(caps_features, node(), disc_copies), + mnesia:add_table_copy(caps_features, node(), disc_only_copies), + MaxSize = gen_mod:get_opt(cache_size, Opts, 1000), + LifeTime = gen_mod:get_opt(cache_life_time, Opts, timer:hours(24)), + cache_tab:new(caps_features, [{max_size, MaxSize}, {life_time, LifeTime}]), ejabberd_hooks:add(user_send_packet, Host, ?MODULE, user_send_packet, 75), ejabberd_hooks:add(c2s_stream_features, Host, @@ -252,8 +264,9 @@ code_change(_OldVsn, State, _Extra) -> feature_request(Host, From, Caps, [SubNode | Tail] = SubNodes) -> Node = Caps#caps.node, BinaryNode = node_to_binary(Node, SubNode), - case mnesia:dirty_read({caps_features, BinaryNode}) of - [] -> + case cache_tab:lookup(caps_features, BinaryNode, + caps_read_fun(BinaryNode)) of + error -> IQ = #iq{type = get, xmlns = ?NS_DISCO_INFO, sub_el = [{xmlelement, "query", @@ -284,11 +297,13 @@ feature_response(#iq{type = result, (_) -> [] end, Els), - mnesia:dirty_write( - #caps_features{node_pair = BinaryNode, - features = features_to_binary(Features)}); + BinaryFeatures = features_to_binary(Features), + cache_tab:insert( + caps_features, BinaryNode, BinaryFeatures, + caps_write_fun(BinaryNode, BinaryFeatures)); false -> - mnesia:dirty_write(#caps_features{node_pair = BinaryNode}) + cache_tab:insert(caps_features, BinaryNode, [], + caps_write_fun(BinaryNode, [])) end, feature_request(Host, From, Caps, SubNodes); feature_response(timeout, _Host, _From, _Caps, _SubNodes) -> @@ -297,7 +312,8 @@ feature_response(_IQResult, Host, From, Caps, [SubNode | SubNodes]) -> %% We got type=error or invalid type=result stanza, so %% we cache empty feature not to probe the client permanently BinaryNode = node_to_binary(Caps#caps.node, SubNode), - mnesia:dirty_write(#caps_features{node_pair = BinaryNode}), + cache_tab:insert(caps_features, BinaryNode, [], + caps_write_fun(BinaryNode, [])), feature_request(Host, From, Caps, SubNodes). node_to_binary(Node, SubNode) -> @@ -306,6 +322,23 @@ node_to_binary(Node, SubNode) -> features_to_binary(L) -> [list_to_binary(I) || I <- L]. binary_to_features(L) -> [binary_to_list(I) || I <- L]. +caps_read_fun(Node) -> + fun() -> + case mnesia:dirty_read({caps_features, Node}) of + [#caps_features{features = Features}] -> + {ok, Features}; + _ -> + error + end + end. + +caps_write_fun(Node, Features) -> + fun() -> + mnesia:dirty_write( + #caps_features{node_pair = Node, + features = Features}) + end. + make_my_disco_hash(Host) -> JID = jlib:make_jid("", Host, ""), case {ejabberd_hooks:run_fold(disco_local_features, From c03140d4be9e0e8a691881f74548bc7ff4fccb5a Mon Sep 17 00:00:00 2001 From: Christophe Romain Date: Mon, 30 Aug 2010 11:14:57 +0200 Subject: [PATCH 18/85] fix merge issue --- src/odbc/ejabberd_odbc.erl | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/odbc/ejabberd_odbc.erl b/src/odbc/ejabberd_odbc.erl index 84619eccd..dc23dd928 100644 --- a/src/odbc/ejabberd_odbc.erl +++ b/src/odbc/ejabberd_odbc.erl @@ -39,13 +39,9 @@ sql_bloc/2, escape/1, escape_like/1, -<<<<<<< HEAD + to_bool/1, keep_alive/1, sql_query_on_all_connections/2]). -======= - to_bool/1, - keep_alive/1]). ->>>>>>> mainline/2.1.x %% gen_fsm callbacks -export([init/1, From c754c91ad1e68bb10afc541321dc13c4711fc665 Mon Sep 17 00:00:00 2001 From: Badlop Date: Mon, 30 Aug 2010 23:23:28 +0200 Subject: [PATCH 19/85] Add IPv6 support to mod_irc (thanks to Matthias Schiffer)(EJAB-1298) --- src/mod_irc/mod_irc_connection.erl | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/mod_irc/mod_irc_connection.erl b/src/mod_irc/mod_irc_connection.erl index 107e6602e..39a06a294 100644 --- a/src/mod_irc/mod_irc_connection.erl +++ b/src/mod_irc/mod_irc_connection.erl @@ -105,8 +105,16 @@ init([From, Host, Server, Username, Encoding, Port, Password]) -> open_socket(init, StateData) -> Addr = StateData#state.server, Port = StateData#state.port, - ?DEBUG("connecting to ~s:~p~n", [Addr, Port]), - case gen_tcp:connect(Addr, Port, [binary, {packet, 0}]) of + ?DEBUG("Connecting with IPv6 to ~s:~p", [Addr, Port]), + Connect6 = gen_tcp:connect(Addr, Port, [inet6, binary, {packet, 0}]), + Connect = case Connect6 of + {error, _} -> + ?DEBUG("Connection with IPv6 to ~s:~p failed. Now using IPv4.", [Addr, Port]), + gen_tcp:connect(Addr, Port, [inet, binary, {packet, 0}]); + _ -> + Connect6 + end, + case Connect of {ok, Socket} -> NewStateData = StateData#state{socket = Socket}, if From c75b7b2b125f9b6dd199a2e6a4a309c4add893f3 Mon Sep 17 00:00:00 2001 From: Evgeniy Khramtsov Date: Tue, 31 Aug 2010 18:06:02 +1000 Subject: [PATCH 20/85] Implemented dirty (non-atomic) functions; added copyright notice --- src/cache_tab.erl | 155 ++++++++++++++++++++++++++++++++---------- src/cache_tab_sup.erl | 21 +++++- 2 files changed, 139 insertions(+), 37 deletions(-) diff --git a/src/cache_tab.erl b/src/cache_tab.erl index e2551ec78..75ef6159a 100644 --- a/src/cache_tab.erl +++ b/src/cache_tab.erl @@ -4,6 +4,25 @@ %%% Description : Caching key-value table %%% %%% Created : 29 Aug 2010 by Evgeniy Khramtsov +%%% +%%% +%%% ejabberd, Copyright (C) 2002-2010 ProcessOne +%%% +%%% This program is free software; you can redistribute it and/or +%%% modify it under the terms of the GNU General Public License as +%%% published by the Free Software Foundation; either version 2 of the +%%% License, or (at your option) any later version. +%%% +%%% This program is distributed in the hope that it will be useful, +%%% but WITHOUT ANY WARRANTY; without even the implied warranty of +%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +%%% General Public License for more details. +%%% +%%% You should have received a copy of the GNU General Public License +%%% along with this program; if not, write to the Free Software +%%% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +%%% 02111-1307 USA +%%% %%%------------------------------------------------------------------- -module(cache_tab). @@ -13,7 +32,9 @@ %% API -export([start_link/4, new/2, delete/1, delete/3, lookup/3, - insert/4, info/2, tab2list/1, setopts/2, all/0, test/0]). + insert/4, info/2, tab2list/1, setopts/2, + dirty_lookup/3, dirty_insert/4, dirty_delete/3, + all/0, test/0]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, @@ -83,15 +104,43 @@ delete(Tab) -> delete(Tab, Key, F) -> ?GEN_SERVER:call( - get_proc_by_hash(Tab, Key), {delete, Key, F}, ?CALL_TIMEOUT). + get_proc_by_hash(Tab, Key), {delete, Key, F}, ?CALL_TIMEOUT). + +dirty_delete(Tab, Key, F) -> + F(), + ?GEN_SERVER:call( + get_proc_by_hash(Tab, Key), {dirty_delete, Key}, ?CALL_TIMEOUT). lookup(Tab, Key, F) -> ?GEN_SERVER:call( - get_proc_by_hash(Tab, Key), {lookup, Key, F}, ?CALL_TIMEOUT). + get_proc_by_hash(Tab, Key), {lookup, Key, F}, ?CALL_TIMEOUT). + +dirty_lookup(Tab, Key, F) -> + Proc = get_proc_by_hash(Tab, Key), + case ?GEN_SERVER:call(Proc, {dirty_lookup, Key}, ?CALL_TIMEOUT) of + {ok, '$cached_mismatch'} -> + error; + {ok, Val} -> + {ok, Val}; + _ -> + case F() of + {ok, Val} -> + ?GEN_SERVER:call( + Proc, {dirty_insert, Key, Val}, ?CALL_TIMEOUT), + {ok, Val}; + _ -> + error + end + end. insert(Tab, Key, Val, F) -> ?GEN_SERVER:call( - get_proc_by_hash(Tab, Key), {insert, Key, Val, F}, ?CALL_TIMEOUT). + get_proc_by_hash(Tab, Key), {insert, Key, Val, F}, ?CALL_TIMEOUT). + +dirty_insert(Tab, Key, Val, F) -> + F(), + ?GEN_SERVER:call( + get_proc_by_hash(Tab, Key), {dirty_insert, Key, Val}, ?CALL_TIMEOUT). info(Tab, Info) -> case lists:map( @@ -168,6 +217,22 @@ handle_call({lookup, Key, F}, _From, #state{tab = T} = State) -> end end end; +handle_call({dirty_lookup, Key}, _From, #state{tab = T} = State) -> + case treap:lookup(Key, T) of + {ok, _Prio, Val} -> + Hits = State#state.hits, + NewState = treap_update(Key, Val, State#state{hits = Hits + 1}), + {reply, {ok, Val}, NewState}; + _ -> + Miss = State#state.miss, + NewState = State#state{miss = Miss + 1}, + if State#state.cache_missed -> + {reply, error, + treap_insert(Key, '$cached_mismatch', NewState)}; + true -> + {reply, error, NewState} + end + end; handle_call({insert, Key, Val, F}, _From, #state{tab = T} = State) -> case treap:lookup(Key, T) of {ok, _Prio, Val} -> @@ -187,6 +252,15 @@ handle_call({insert, Key, Val, F}, _From, #state{tab = T} = State) -> {reply, ok, NewState} end end; +handle_call({dirty_insert, Key, Val}, _From, #state{tab = T} = State) -> + case treap:lookup(Key, T) of + {ok, _Prio, Val} -> + {reply, ok, State}; + {ok, _, _} -> + {reply, ok, treap_update(Key, Val, State)}; + _ -> + {reply, ok, treap_insert(Key, Val, State)} + end; handle_call({delete, Key, F}, _From, State) -> NewState = treap_delete(Key, State), case catch F() of @@ -196,6 +270,9 @@ handle_call({delete, Key, F}, _From, State) -> ok end, {reply, ok, NewState}; +handle_call({dirty_delete, Key}, _From, State) -> + NewState = treap_delete(Key, State), + {reply, ok, NewState}; handle_call({info, Info}, _From, State) -> Res = case Info of size -> @@ -412,23 +489,30 @@ print_error(Operation, Args, Reason, State) -> %%-------------------------------------------------------------------- %%% Tests %%-------------------------------------------------------------------- +-define(lookup, dirty_lookup). +-define(delete, dirty_delete). +-define(insert, dirty_insert). +%% -define(lookup, lookup). +%% -define(delete, delete). +%% -define(insert, insert). + test() -> LifeTime = 2, ok = new(test_tbl, [{life_time, LifeTime}, {max_size, unlimited}]), check([]), - ok = insert(test_tbl, "key", "value", fun() -> ok end), + ok = ?insert(test_tbl, "key", "value", fun() -> ok end), check([{"key", "value"}]), - {ok, "value"} = lookup(test_tbl, "key", fun() -> error end), + {ok, "value"} = ?lookup(test_tbl, "key", fun() -> error end), check([{"key", "value"}]), io:format("** waiting for ~p seconds to check if cleaner works fine...~n", [LifeTime+1]), timer:sleep(timer:seconds(LifeTime+1)), - ok = insert(test_tbl, "key1", "value1", fun() -> ok end), + ok = ?insert(test_tbl, "key1", "value1", fun() -> ok end), check([{"key1", "value1"}]), - ok = delete(test_tbl, "key1", fun() -> ok end), - {ok, "value"} = lookup(test_tbl, "key", fun() -> {ok, "value"} end), + ok = ?delete(test_tbl, "key1", fun() -> ok end), + {ok, "value"} = ?lookup(test_tbl, "key", fun() -> {ok, "value"} end), check([{"key", "value"}]), - ok = delete(test_tbl, "key", fun() -> ok end), + ok = ?delete(test_tbl, "key", fun() -> ok end), check([]), %% io:format("** testing buggy callbacks...~n"), %% delete(test_tbl, "key", fun() -> erlang:error(badarg) end), @@ -443,36 +527,35 @@ test1() -> ok = new(test_tbl, [{max_size, MaxSize}, {shrink_size, 1}, {warn, false}]), lists:foreach( fun(N) -> - ok = insert(test_tbl, N, N, fun() -> ok end) + ok = ?insert(test_tbl, N, N, fun() -> ok end) end, lists:seq(1, MaxSize*get_proc_num())), {ok, MaxSize} = info(test_tbl, size), delete(test_tbl), - success. -%% io:format("** testing speed, this may take a while...~n"), -%% test2(1000), -%% test2(10000), -%% test2(100000), -%% test2(1000000). + io:format("** testing speed, this may take a while...~n"), + test2(1000), + test2(10000), + test2(100000), + test2(1000000). -%% test2(Iter) -> -%% ok = new(test_tbl, [{max_size, unlimited}, {life_time, unlimited}]), -%% L = lists:seq(1, Iter), -%% T1 = now(), -%% lists:foreach( -%% fun(N) -> -%% ok = insert(test_tbl, N, N, fun() -> ok end) -%% end, L), -%% io:format("** average insert (size = ~p): ~p usec~n", -%% [Iter, round(timer:now_diff(now(), T1)/Iter)]), -%% T2 = now(), -%% lists:foreach( -%% fun(N) -> -%% {ok, N} = lookup(test_tbl, N, fun() -> ok end) -%% end, L), -%% io:format("** average lookup (size = ~p): ~p usec~n", -%% [Iter, round(timer:now_diff(now(), T2)/Iter)]), -%% {ok, Iter} = info(test_tbl, size), -%% delete(test_tbl). +test2(Iter) -> + ok = new(test_tbl, [{max_size, unlimited}, {life_time, unlimited}]), + L = lists:seq(1, Iter), + T1 = now(), + lists:foreach( + fun(N) -> + ok = ?insert(test_tbl, N, N, fun() -> ok end) + end, L), + io:format("** average insert (size = ~p): ~p usec~n", + [Iter, round(timer:now_diff(now(), T1)/Iter)]), + T2 = now(), + lists:foreach( + fun(N) -> + {ok, N} = ?lookup(test_tbl, N, fun() -> ok end) + end, L), + io:format("** average lookup (size = ~p): ~p usec~n", + [Iter, round(timer:now_diff(now(), T2)/Iter)]), + {ok, Iter} = info(test_tbl, size), + delete(test_tbl). check(List) -> Size = length(List), diff --git a/src/cache_tab_sup.erl b/src/cache_tab_sup.erl index d417c5488..a49593f5e 100644 --- a/src/cache_tab_sup.erl +++ b/src/cache_tab_sup.erl @@ -1,9 +1,28 @@ %%%------------------------------------------------------------------- %%% File : cache_tab_sup.erl %%% Author : Evgeniy Khramtsov -%%% Description : +%%% Description : Cache tables supervisor %%% %%% Created : 30 Aug 2010 by Evgeniy Khramtsov +%%% +%%% +%%% ejabberd, Copyright (C) 2002-2010 ProcessOne +%%% +%%% This program is free software; you can redistribute it and/or +%%% modify it under the terms of the GNU General Public License as +%%% published by the Free Software Foundation; either version 2 of the +%%% License, or (at your option) any later version. +%%% +%%% This program is distributed in the hope that it will be useful, +%%% but WITHOUT ANY WARRANTY; without even the implied warranty of +%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +%%% General Public License for more details. +%%% +%%% You should have received a copy of the GNU General Public License +%%% along with this program; if not, write to the Free Software +%%% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +%%% 02111-1307 USA +%%% %%%------------------------------------------------------------------- -module(cache_tab_sup). From 353d16b8ef2bdf95eae822ff0cb02c150bcd2228 Mon Sep 17 00:00:00 2001 From: Eric Cestari Date: Thu, 2 Sep 2010 16:57:21 +0200 Subject: [PATCH 21/85] Post to pubsub using http POST : {5280, ejabberd_http, [ http_poll, web_admin, {request_handlers, [{["pshb"], pshb_http}]} % this should be added ]} To post to a node the content of the file "sam.atom" on the "foo", on the localhost virtual host, using cstar@localhost curl -u cstar@localhost:encore -i -X POST http://localhost:5280/pshb/localhost/foo -d @sam.atom --- src/web/pshb_http.erl | 253 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 253 insertions(+) create mode 100644 src/web/pshb_http.erl diff --git a/src/web/pshb_http.erl b/src/web/pshb_http.erl new file mode 100644 index 000000000..fa1f9a431 --- /dev/null +++ b/src/web/pshb_http.erl @@ -0,0 +1,253 @@ +%%%---------------------------------------------------------------------- +%%% File : pshb_http.erl +%%% Author : Eric Cestari +%%% Purpose : +%%% Created :01-09-2010 +%%% +%%% +%%% ejabberd, Copyright (C) 2002-2010 ProcessOne +%%% +%%% This program is free software; you can redistribute it and/or +%%% modify it under the terms of the GNU General Public License as +%%% published by the Free Software Foundation; either version 2 of the +%%% License, or (at your option) any later version. +%%% +%%% This program is distributed in the hope that it will be useful, +%%% but WITHOUT ANY WARRANTY; without even the implied warranty of +%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +%%% General Public License for more details. +%%% +%%% You should have received a copy of the GNU General Public License +%%% along with this program; if not, write to the Free Software +%%% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +%%% 02111-1307 USA +%%% +%%%---------------------------------------------------------------------- +%%% +%%% {5280, ejabberd_http, [ +%%% http_poll, +%%% web_admin, +%%% {request_handlers, [{["pshb"], pshb_http}]} % this should be added +%%% ]} +%%% +%%% To post to a node the content of the file "sam.atom" on the "foo", on the localhost virtual host, using cstar@localhost +%%% curl -u cstar@localhost:encore -i -X POST http://localhost:5280/pshb/localhost/foo -d @sam.atom +%%% + + +-module (pshb_http). +-author('ecestari@process-one.net'). + +-include("ejabberd.hrl"). +-include("jlib.hrl"). +-include("ejabberd_http.hrl"). + +-include("mod_pubsub/pubsub.hrl"). + +-export([process/2]). + +process([Domain, _Node|_Rest]=LocalPath, #request{auth = Auth} = Request)-> + case get_auth(Auth) of + %%make sure user belongs to pubsub domain + {User, Domain} -> + out(Request, Request#request.method, LocalPath,{User, Domain}); + _ -> + out(Request, Request#request.method, LocalPath,undefined) + end; + +process(_LocalPath, _Request)-> + error(404). + +get_auth(Auth) -> + case Auth of + {SJID, P} -> + case jlib:string_to_jid(SJID) of + error -> + unauthorized; + #jid{user = U, server = S} -> + case ejabberd_auth:check_password(U, S, P) of + true -> + {U, S}; + false -> + unauthorized + end + end; + _ -> + unauthorized + end. + +out(Args, 'POST', [Domain, Node]=Uri, {User, _Domain}) -> + Slug = uniqid(false), + Payload = xml_stream:parse_element(Args#request.data), + [FilteredPayload]=xml:remove_cdata([Payload]), + + %FilteredPayload2 = case xml:get_subtag(FilteredPayload, "app:edited") -> + % {xmlelement, Name, Attrs, [{cdata, }]} + case mod_pubsub:publish_item(get_host(Uri), + Domain, + get_collection(Uri), + jlib:make_jid(User,Domain, ""), + Slug, + [FilteredPayload]) of + {result, [_]} -> + ?DEBUG("Publishing to ~p~n",[entry_uri(Args, Domain, Node,Slug)]), + {201, [{"location", entry_uri(Args, Domain,Node,Slug)}], Payload}; + {error, Error} -> + error(400, Error) + end; + +out(Args, 'GET', [Domain, Node, _Item]=URI, _) -> + Failure = fun(Error)-> + ?DEBUG("Error getting URI ~p : ~p",[URI, Error]), + error(404) + end, + Success = fun(Item)-> + Etag =generate_etag(Item), + IfNoneMatch=proplists:get_value('If-None-Match', Args#request.headers), + if IfNoneMatch==Etag + -> + success(304); + true -> + {200, [{"Content-Type", "application/atom+xml"},{"Etag", Etag}], "" + ++ xml:element_to_string(item_to_entry(Args, Domain,Node, Item))} + end + end, + get_item(URI, Failure, Success); + +out(_,Method,Uri,undefined) -> + ?DEBUG("Error, ~p not authorized for ~p : ~p",[ Method,Uri]), + error(403). + +get_item(Uri, Failure, Success)-> + case mod_pubsub:get_item(get_host(Uri), get_collection(Uri), tl(get_member(Uri))) of + {error, Reason} -> + Failure(Reason); + {result, Item} -> + Success(Item) + end. + +generate_etag(#pubsub_item{modification={_JID, {_, D2, D3}}})->integer_to_list(D3+D2). +get_host([Domain|_Rest])-> "pubsub."++Domain. +get_collection([_Domain, Node|_Rest])->list_to_binary(Node). +get_member([Domain, _Node, Member]=Uri)-> + [get_host(Uri), get_collection(Uri), Member]. + +collection_uri(R, Domain, Node) -> + base_uri(R, Domain)++ "/" ++Node. + +entry_uri(R,Domain, Node, Id)-> + collection_uri(R,Domain, Node)++"/"++Id. + +base_uri(#request{host=Host, port=Port}, Domain)-> + "http://"++Host++":"++i2l(Port)++"/pshb/" ++ Domain. + +item_to_entry(Args,Domain, Node,#pubsub_item{itemid={Id,_}, payload=Entry}=Item)-> + [R]=xml:remove_cdata(Entry), + item_to_entry(Args, Domain, Node, Id, R, Item). + +item_to_entry(Args,Domain, Node, Id,{xmlelement, "entry", Attrs, SubEl}, + #pubsub_item{modification={JID, Secs} }) -> + Date = calendar:now_to_local_time(Secs), + {_User, Domain, _}=jlib:jid_tolower(JID), + SubEl2=[{xmlelement, "app:edited", [], [{xmlcdata, w3cdtf(Date)}]}, + {xmlelement, "link",[{"rel", "edit"}, + {"href", entry_uri(Args,Domain,Node, Id)}],[] }, + {xmlelement, "id", [],[{xmlcdata, Id}]} + | SubEl], + {xmlelement, "entry", [{"xmlns:app","http://www.w3.org/2007/app"}|Attrs], SubEl2}; + +% Don't do anything except adding xmlns +item_to_entry(_Args,_Domain, Node, _Id, {xmlelement, Name, Attrs, Subels}=Element, _Item)-> + case proplists:is_defined("xmlns",Attrs) of + true -> Element; + false -> {xmlelement, Name, [{"xmlns", Node}|Attrs], Subels} + end. + + +%% simple output functions +error(404)-> + {404, [], "Not Found"}; +error(403)-> + {403, [], "Forbidden"}; +error(500)-> + {500, [], "Internal server error"}; +error(401)-> + {401, [{"WWW-Authenticate", "basic realm=\"ejabberd\""}],"Unauthorized"}; +error(Code)-> + {Code, [], ""}. +error(Code, Error) when is_list(Error) -> {Code, [], Error}; +error(Code, {xmlelement, "error",_,_}=Error) -> {Code, [], xml:element_to_string(Error)}; +error(Code, _Error) -> {Code, [], "Bad request"}. +success(200)-> + {200, [], ""}; +success(Code)-> + {Code, [], ""}. + + +% Code below is taken (with some modifications) from the yaws webserver, which +% is distributed under the folowing license: +% +% This software (the yaws webserver) is free software. +% Parts of this software is Copyright (c) Claes Wikstrom +% Any use or misuse of the source code is hereby freely allowed. +% +% 1. Redistributions of source code must retain the above copyright +% notice as well as this list of conditions. +% +% 2. Redistributions in binary form must reproduce the above copyright +% notice as well as this list of conditions. +%%% Create W3CDTF (http://www.w3.org/TR/NOTE-datetime) formatted date +%%% w3cdtf(GregSecs) -> "YYYY-MM-DDThh:mm:ssTZD" +%%% +uniqid(false)-> + {T1, T2, T3} = now(), + lists:flatten(io_lib:fwrite("~.16B~.16B~.16B", [T1, T2, T3])); +uniqid(Slug) -> + Slut = string:to_lower(Slug), + S = string:substr(Slut, 1, 9), + {_T1, T2, T3} = now(), + lists:flatten(io_lib:fwrite("~s-~.16B~.16B", [S, T2, T3])). + +w3cdtf(Date) -> %1 Date = calendar:gregorian_seconds_to_datetime(GregSecs), + {{Y, Mo, D},{H, Mi, S}} = Date, + [UDate|_] = calendar:local_time_to_universal_time_dst(Date), + {DiffD,{DiffH,DiffMi,_}}=calendar:time_difference(UDate,Date), + w3cdtf_diff(Y, Mo, D, H, Mi, S, DiffD, DiffH, DiffMi). + +%%% w3cdtf's helper function +w3cdtf_diff(Y, Mo, D, H, Mi, S, _DiffD, DiffH, DiffMi) when DiffH < 12, DiffH /= 0 -> + i2l(Y) ++ "-" ++ add_zero(Mo) ++ "-" ++ add_zero(D) ++ "T" ++ + add_zero(H) ++ ":" ++ add_zero(Mi) ++ ":" ++ + add_zero(S) ++ "+" ++ add_zero(DiffH) ++ ":" ++ add_zero(DiffMi); + +w3cdtf_diff(Y, Mo, D, H, Mi, S, DiffD, DiffH, DiffMi) when DiffH > 12, DiffD == 0 -> + i2l(Y) ++ "-" ++ add_zero(Mo) ++ "-" ++ add_zero(D) ++ "T" ++ + add_zero(H) ++ ":" ++ add_zero(Mi) ++ ":" ++ + add_zero(S) ++ "+" ++ add_zero(DiffH) ++ ":" ++ + add_zero(DiffMi); + +w3cdtf_diff(Y, Mo, D, H, Mi, S, DiffD, DiffH, DiffMi) when DiffH > 12, DiffD /= 0, DiffMi /= 0 -> + i2l(Y) ++ "-" ++ add_zero(Mo) ++ "-" ++ add_zero(D) ++ "T" ++ + add_zero(H) ++ ":" ++ add_zero(Mi) ++ ":" ++ + add_zero(S) ++ "-" ++ add_zero(23-DiffH) ++ + ":" ++ add_zero(60-DiffMi); + +w3cdtf_diff(Y, Mo, D, H, Mi, S, DiffD, DiffH, DiffMi) when DiffH > 12, DiffD /= 0, DiffMi == 0 -> + i2l(Y) ++ "-" ++ add_zero(Mo) ++ "-" ++ add_zero(D) ++ "T" ++ + add_zero(H) ++ ":" ++ add_zero(Mi) ++ ":" ++ + add_zero(S) ++ "-" ++ add_zero(24-DiffH) ++ + ":" ++ add_zero(DiffMi); + +w3cdtf_diff(Y, Mo, D, H, Mi, S, _DiffD, DiffH, _DiffMi) when DiffH == 0 -> + i2l(Y) ++ "-" ++ add_zero(Mo) ++ "-" ++ add_zero(D) ++ "T" ++ + add_zero(H) ++ ":" ++ add_zero(Mi) ++ ":" ++ + add_zero(S) ++ "Z". + +add_zero(I) when is_integer(I) -> add_zero(i2l(I)); +add_zero([A]) -> [$0,A]; +add_zero(L) when is_list(L) -> L. + + + +i2l(I) when is_integer(I) -> integer_to_list(I); +i2l(L) when is_list(L) -> L. \ No newline at end of file From a22ebd3c493ffc9bc5b8bbef57ea98075c098c59 Mon Sep 17 00:00:00 2001 From: Eric Cestari Date: Fri, 3 Sep 2010 15:54:51 +0200 Subject: [PATCH 22/85] Added support for GET a single item and GET an atom feed of a node --- src/web/pshb_http.erl | 61 +++++++++++++++++++++++++++++++++++++------ 1 file changed, 53 insertions(+), 8 deletions(-) diff --git a/src/web/pshb_http.erl b/src/web/pshb_http.erl index fa1f9a431..f76504183 100644 --- a/src/web/pshb_http.erl +++ b/src/web/pshb_http.erl @@ -46,7 +46,7 @@ -export([process/2]). -process([Domain, _Node|_Rest]=LocalPath, #request{auth = Auth} = Request)-> +process([_Domain, _Node|_Rest]=LocalPath, #request{auth = Auth} = Request)-> case get_auth(Auth) of %%make sure user belongs to pubsub domain {User, Domain} -> @@ -76,6 +76,41 @@ get_auth(Auth) -> unauthorized end. +out(Args, 'GET', [Domain,Node]=Uri, _User) -> + case mod_pubsub:tree_action(get_host(Uri), get_node, [get_host(Uri),get_collection(Uri)]) of + {error, _} -> error(404); + _ -> + Items = lists:sort(fun(X,Y)-> + {DateX, _} = X#pubsub_item.modification, + {DateY, _} = Y#pubsub_item.modification, + DateX > DateY + end, mod_pubsub:get_items( + get_host(Uri), + get_collection(Uri))), + case Items of + [] -> ?DEBUG("Items : ~p ~n", [collection(get_collection(Uri), + collection_uri(Args,Domain,Node), calendar:now_to_universal_time(erlang:now()), "", [])]), + {200, [{"Content-Type", "application/atom+xml"}], + collection(get_collection(Uri), + collection_uri(Args,Domain,Node), calendar:now_to_universal_time(erlang:now()), "", [])}; + _ -> + #pubsub_item{modification = {LastDate, _JID}} = LastItem = hd(Items), + Etag =generate_etag(LastItem), + IfNoneMatch=proplists:get_value('If-None-Match', Args#request.headers), + if IfNoneMatch==Etag + -> + success(304); + true -> + XMLEntries= [item_to_entry(Args,Domain, Node,Entry)||Entry <- Items], + {200, [{"Content-Type", "application/atom+xml"},{"Etag", Etag}], + "" + ++ xml:element_to_string( + collection(get_collection(Uri), collection_uri(Args,Domain,Node), + calendar:now_to_universal_time(LastDate), "", XMLEntries))} + end + end + end; + out(Args, 'POST', [Domain, Node]=Uri, {User, _Domain}) -> Slug = uniqid(false), Payload = xml_stream:parse_element(Args#request.data), @@ -119,18 +154,19 @@ out(_,Method,Uri,undefined) -> error(403). get_item(Uri, Failure, Success)-> - case mod_pubsub:get_item(get_host(Uri), get_collection(Uri), tl(get_member(Uri))) of + ?DEBUG(" mod_pubsub:get_item(~p, ~p,~p)", [get_host(Uri), get_collection(Uri), get_member(Uri)]), + case mod_pubsub:get_item(get_host(Uri), get_collection(Uri), get_member(Uri)) of {error, Reason} -> Failure(Reason); - {result, Item} -> + #pubsub_item{}=Item -> Success(Item) end. -generate_etag(#pubsub_item{modification={_JID, {_, D2, D3}}})->integer_to_list(D3+D2). +generate_etag(#pubsub_item{modification={{_, D2, D3}, _JID}})->integer_to_list(D3+D2). get_host([Domain|_Rest])-> "pubsub."++Domain. get_collection([_Domain, Node|_Rest])->list_to_binary(Node). -get_member([Domain, _Node, Member]=Uri)-> - [get_host(Uri), get_collection(Uri), Member]. +get_member([_Domain, _Node, Member])-> + Member. collection_uri(R, Domain, Node) -> base_uri(R, Domain)++ "/" ++Node. @@ -146,7 +182,7 @@ item_to_entry(Args,Domain, Node,#pubsub_item{itemid={Id,_}, payload=Entry}=Item) item_to_entry(Args, Domain, Node, Id, R, Item). item_to_entry(Args,Domain, Node, Id,{xmlelement, "entry", Attrs, SubEl}, - #pubsub_item{modification={JID, Secs} }) -> + #pubsub_item{modification={ Secs, JID} }) -> Date = calendar:now_to_local_time(Secs), {_User, Domain, _}=jlib:jid_tolower(JID), SubEl2=[{xmlelement, "app:edited", [], [{xmlcdata, w3cdtf(Date)}]}, @@ -163,7 +199,16 @@ item_to_entry(_Args,_Domain, Node, _Id, {xmlelement, Name, Attrs, Subels}=Eleme false -> {xmlelement, Name, [{"xmlns", Node}|Attrs], Subels} end. - +collection(Title, Link, Updated, _Id, Entries)-> + {xmlelement, "feed", [{"xmlns", "http://www.w3.org/2005/Atom"}, + {"xmlns:app", "http://www.w3.org/2007/app"}], [ + {xmlelement, "title", [],[{xmlcdata, Title}]}, + {xmlelement, "updated", [],[{xmlcdata, w3cdtf(Updated)}]}, + {xmlelement, "link", [{"href", Link}], []}, + {xmlelement, "title", [],[{xmlcdata, Title}]} | + Entries + ]}. + %% simple output functions error(404)-> {404, [], "Not Found"}; From cd923838c3f1d0d96cc199c537b27d4d4c11dd85 Mon Sep 17 00:00:00 2001 From: Eric Cestari Date: Tue, 7 Sep 2010 11:32:14 +0200 Subject: [PATCH 23/85] Making progress on the Atom interface. - GET items - POST items - GET nodes HTTP error codes now are the ones XMPP returns. --- doc/http_post.md | 45 +++++++++++++++++++++++++++ src/web/pshb_http.erl | 72 +++++++++++++++++++++++++++++++++++-------- 2 files changed, 104 insertions(+), 13 deletions(-) create mode 100644 doc/http_post.md diff --git a/doc/http_post.md b/doc/http_post.md new file mode 100644 index 000000000..90242e9b9 --- /dev/null +++ b/doc/http_post.md @@ -0,0 +1,45 @@ +# Managing pubsub nodes through HTTP Atompub # + + +## Configuration ## + +These options will be used by the service to know how to build URLs. Using the previous configuration items the service should be accessed through `http://notify.push.bbc.co.uk:5280/pshb///`. + +Also, in the ejabberd_http handler configuration, add the identified line. + + {5280, ejabberd_http, [ + http_poll, + web_admin, + {request_handlers, [{["pshb"], pshb_http}]} % this should be added + ]} + +## Usage example with cURL ## + +### Getting the service document ### + +No authentication necessary. All nodes are listed. + + curl -i http://:/pshb// + +### Getting items from a node ### + +No authentication done, and all nodes are accessible. + + curl -i http://:/pshb/// + + +### Posting a new item ### + + curl -u : -i -X POST -d @entry.atom http://:/pshb// + +User ability to post is based on node configuration. + + +### Creating a new node ### + +An instant node can be created : + + curl -X POST -u cstar@localhost:encore -d "" http://localhost:5280/pshb/localhost + + + diff --git a/src/web/pshb_http.erl b/src/web/pshb_http.erl index f76504183..f9f9e886e 100644 --- a/src/web/pshb_http.erl +++ b/src/web/pshb_http.erl @@ -44,19 +44,17 @@ -include("mod_pubsub/pubsub.hrl"). --export([process/2]). +-export([process/2]). -process([_Domain, _Node|_Rest]=LocalPath, #request{auth = Auth} = Request)-> +process(LocalPath, #request{auth = Auth} = Request)-> + ?DEBUG("LocalPath = ~p", [LocalPath]), case get_auth(Auth) of %%make sure user belongs to pubsub domain {User, Domain} -> out(Request, Request#request.method, LocalPath,{User, Domain}); _ -> - out(Request, Request#request.method, LocalPath,undefined) - end; - -process(_LocalPath, _Request)-> - error(404). + out(Request, Request#request.method, LocalPath, undefined) + end. get_auth(Auth) -> case Auth of @@ -128,13 +126,42 @@ out(Args, 'POST', [Domain, Node]=Uri, {User, _Domain}) -> ?DEBUG("Publishing to ~p~n",[entry_uri(Args, Domain, Node,Slug)]), {201, [{"location", entry_uri(Args, Domain,Node,Slug)}], Payload}; {error, Error} -> - error(400, Error) + error(Error) end; +out(Args, 'GET', [Domain]=Uri, From)-> + Host = get_host(Uri), + ?DEBUG("Host = ~p", [Host]), + case mod_pubsub:tree_action(Host, get_subnodes, [Host, <<>>, From ]) of + [] -> + ?DEBUG("Error getting URI ~p : ~p",[Uri, From]), + error(404); + Collections -> + {200, [{"Content-Type", "application/atomsvc+xml"}], "" + ++ xml:element_to_string(service(Args,Domain, Collections))} + end; + +out(Args, 'POST', [Domain]=Uri, {User, UDomain})-> + Host = get_host(Uri), + case mod_pubsub:create_node(Host, Domain, <<>>, {User, UDomain}, "default") of + {error, Error} -> + ?ERROR_MSG("Error create node via HTTP : ~p",[Error]), + + error(Error); % will probably detail more + {result, [Node]} -> + {200, [{"Content-Type", "application/xml"}], "" + ++ xml:element_to_string(Node)} + end; + +out(Args, 'POST', [Domain]=Uri, undefined) -> + error(403); + + + out(Args, 'GET', [Domain, Node, _Item]=URI, _) -> Failure = fun(Error)-> ?DEBUG("Error getting URI ~p : ~p",[URI, Error]), - error(404) + error(Error) end, Success = fun(Item)-> Etag =generate_etag(Item), @@ -169,10 +196,10 @@ get_member([_Domain, _Node, Member])-> Member. collection_uri(R, Domain, Node) -> - base_uri(R, Domain)++ "/" ++Node. + base_uri(R, Domain)++ "/" ++ b2l(Node). entry_uri(R,Domain, Node, Id)-> - collection_uri(R,Domain, Node)++"/"++Id. + collection_uri(R,Domain, Node)++"/"++b2l(Id). base_uri(#request{host=Host, port=Port}, Domain)-> "http://"++Host++":"++i2l(Port)++"/pshb/" ++ Domain. @@ -208,8 +235,25 @@ collection(Title, Link, Updated, _Id, Entries)-> {xmlelement, "title", [],[{xmlcdata, Title}]} | Entries ]}. + +service(Args, Domain,Collections)-> + {xmlelement, "service", [{"xmlns", "http://www.w3.org/2007/app"}, + {"xmlns:atom", "http://www.w3.org/2005/Atom"}, + {"xmlns:app", "http://www.w3.org/2007/app"}],[ + {xmlelement, "workspace", [],[ + {xmlelement, "atom:title", [],[{xmlcdata,"Pubsub node Feed for " ++Domain}]} | + lists:map(fun(#pubsub_node{nodeid={_Server, Id}, type=_Type})-> + {xmlelement, "collection", [{"href", collection_uri(Args,Domain, Id)}], [ + {xmlelement, "atom:title", [], [{xmlcdata, Id}]} + ]} + end, Collections) + ]} + ]}. %% simple output functions +error({xmlelement, "error", Attrs, _}=Error) -> + Value = list_to_integer(xml:get_attr_s("code", Attrs)), + {Value, [{"Content-type", "application/xml"}], xml:element_to_string(Error)}; error(404)-> {404, [], "Not Found"}; error(403)-> @@ -221,7 +265,6 @@ error(401)-> error(Code)-> {Code, [], ""}. error(Code, Error) when is_list(Error) -> {Code, [], Error}; -error(Code, {xmlelement, "error",_,_}=Error) -> {Code, [], xml:element_to_string(Error)}; error(Code, _Error) -> {Code, [], "Bad request"}. success(200)-> {200, [], ""}; @@ -295,4 +338,7 @@ add_zero(L) when is_list(L) -> L. i2l(I) when is_integer(I) -> integer_to_list(I); -i2l(L) when is_list(L) -> L. \ No newline at end of file +i2l(L) when is_list(L) -> L. + +b2l(B) when is_binary(B) -> binary_to_list(B); +b2l(L) when is_list(L) -> L. \ No newline at end of file From bf98fa0c016387165726ac79963f0ceb0556a219 Mon Sep 17 00:00:00 2001 From: Eric Cestari Date: Tue, 7 Sep 2010 14:35:40 +0200 Subject: [PATCH 24/85] Added node creation with configure form Added deletion Better behavior in case of a crash (returns 500) --- doc/http_post.md | 42 +++++++++++++++++++--- src/mod_pubsub/mod_pubsub.erl | 1 + src/web/pshb_http.erl | 68 ++++++++++++++++++++++++----------- 3 files changed, 86 insertions(+), 25 deletions(-) diff --git a/doc/http_post.md b/doc/http_post.md index 90242e9b9..cbddb4d5c 100644 --- a/doc/http_post.md +++ b/doc/http_post.md @@ -13,33 +13,67 @@ Also, in the ejabberd_http handler configuration, add the identified line. {request_handlers, [{["pshb"], pshb_http}]} % this should be added ]} +## Important notice ## + +In the current version of the code, some security checks are not done : + + * read operations can all be done without authentication + + * node creation uses the default `all` access_createnode acl, not checking for the actual configuration. + ## Usage example with cURL ## ### Getting the service document ### No authentication necessary. All nodes are listed. - curl -i http://:/pshb// + curl -i http://host:port/pshb/domain/ ### Getting items from a node ### No authentication done, and all nodes are accessible. - curl -i http://:/pshb/// + curl -i http://host:port/pshb/domain/node/ ### Posting a new item ### - curl -u : -i -X POST -d @entry.atom http://:/pshb// + curl -u jid:password -i -X POST -d @entry.atom http://post:port/pshb/domain/node User ability to post is based on node configuration. ### Creating a new node ### -An instant node can be created : +An instant node can be created if server configuration allows: curl -X POST -u cstar@localhost:encore -d "" http://localhost:5280/pshb/localhost + +or + + curl -X POST -u cstar@localhost:encore -d "" http://localhost:5280/pshb/localhost + +configure element (as per XEP-60) can be passed in the pubsub body. + + $ cat createnode.xml + + + + http://jabber.org/protocol/pubsub#node_config + + Princely Musings (Atom) + 1028 + Atom + + + + $ curl -X POST -u cstar@localhost:encore -d @createnode.xml http://localhost:5280/pshb/localhost + +### Deleting a node ### + +A node is deleted by: + + curl -X DELETE -u cstar@localhost:encore http://localhost:5280/pshb/localhost/princely_musings diff --git a/src/mod_pubsub/mod_pubsub.erl b/src/mod_pubsub/mod_pubsub.erl index a9293212d..2d95b1fac 100644 --- a/src/mod_pubsub/mod_pubsub.erl +++ b/src/mod_pubsub/mod_pubsub.erl @@ -78,6 +78,7 @@ %% exports for console debug manual use -export([create_node/5, + create_node/7, delete_node/3, subscribe_node/5, unsubscribe_node/5, diff --git a/src/web/pshb_http.erl b/src/web/pshb_http.erl index f9f9e886e..89eea479e 100644 --- a/src/web/pshb_http.erl +++ b/src/web/pshb_http.erl @@ -48,35 +48,36 @@ process(LocalPath, #request{auth = Auth} = Request)-> ?DEBUG("LocalPath = ~p", [LocalPath]), - case get_auth(Auth) of - %%make sure user belongs to pubsub domain - {User, Domain} -> - out(Request, Request#request.method, LocalPath,{User, Domain}); - _ -> - out(Request, Request#request.method, LocalPath, undefined) - end. + UD = get_auth(Auth), + case catch out(Request, Request#request.method, LocalPath,UD) of + {'EXIT', Error} -> + ?ERROR_MSG("Error while processing ~p : ~n~p", [LocalPath, Error]), + error(500); + Result -> + Result + end. get_auth(Auth) -> case Auth of {SJID, P} -> case jlib:string_to_jid(SJID) of error -> - unauthorized; + undefined; #jid{user = U, server = S} -> case ejabberd_auth:check_password(U, S, P) of true -> {U, S}; false -> - unauthorized + undefined end end; _ -> - unauthorized + undefined end. out(Args, 'GET', [Domain,Node]=Uri, _User) -> case mod_pubsub:tree_action(get_host(Uri), get_node, [get_host(Uri),get_collection(Uri)]) of - {error, _} -> error(404); + {error, Error} -> error(Error); _ -> Items = lists:sort(fun(X,Y)-> {DateX, _} = X#pubsub_item.modification, @@ -135,7 +136,7 @@ out(Args, 'GET', [Domain]=Uri, From)-> case mod_pubsub:tree_action(Host, get_subnodes, [Host, <<>>, From ]) of [] -> ?DEBUG("Error getting URI ~p : ~p",[Uri, From]), - error(404); + error(?ERR_ITEM_NOT_FOUND); Collections -> {200, [{"Content-Type", "application/atomsvc+xml"}], "" ++ xml:element_to_string(service(Args,Domain, Collections))} @@ -143,18 +144,37 @@ out(Args, 'GET', [Domain]=Uri, From)-> out(Args, 'POST', [Domain]=Uri, {User, UDomain})-> Host = get_host(Uri), - case mod_pubsub:create_node(Host, Domain, <<>>, {User, UDomain}, "default") of + Payload = xml_stream:parse_element(Args#request.data), + {Node, Type} = case xml:get_subtag(Payload, "create") of + false -> {<<>>,"flat"}; + E -> + {list_to_binary(get_tag_attr_or_default("node", E,"")), + get_tag_attr_or_default("type", E,"flat")} + + end, + ConfigureElement = case xml:get_subtag(Payload, "configure") of + false ->[]; + {xmlelement, _, _, SubEls}->SubEls + end, + Jid = jlib:make_jid({User, UDomain, ""}), + case mod_pubsub:create_node(Host, Domain, Node, Jid, Type, all, ConfigureElement) of {error, Error} -> ?ERROR_MSG("Error create node via HTTP : ~p",[Error]), - error(Error); % will probably detail more - {result, [Node]} -> + {result, [Result]} -> {200, [{"Content-Type", "application/xml"}], "" - ++ xml:element_to_string(Node)} + ++ xml:element_to_string(Result)} + end; + +out(Args, 'DELETE', [Domain, Node] = Uri, {User, UDomain})-> + Host = get_host(Uri), + Jid = jlib:make_jid({User, UDomain, ""}), + BinNode = list_to_binary(Node), + case mod_pubsub:delete_node(Host, BinNode, Jid) of + {error, Error} -> error(Error); + {result, []} -> + {200, [],[]} end; - -out(Args, 'POST', [Domain]=Uri, undefined) -> - error(403); @@ -178,7 +198,7 @@ out(Args, 'GET', [Domain, Node, _Item]=URI, _) -> out(_,Method,Uri,undefined) -> ?DEBUG("Error, ~p not authorized for ~p : ~p",[ Method,Uri]), - error(403). + error(?ERR_FORBIDDEN). get_item(Uri, Failure, Success)-> ?DEBUG(" mod_pubsub:get_item(~p, ~p,~p)", [get_host(Uri), get_collection(Uri), get_member(Uri)]), @@ -341,4 +361,10 @@ i2l(I) when is_integer(I) -> integer_to_list(I); i2l(L) when is_list(L) -> L. b2l(B) when is_binary(B) -> binary_to_list(B); -b2l(L) when is_list(L) -> L. \ No newline at end of file +b2l(L) when is_list(L) -> L. + +get_tag_attr_or_default(AttrName, Element, Default)-> + case xml:get_tag_attr_s(AttrName, Element) of + "" -> Default; + Val -> Val + end. \ No newline at end of file From 363711a37055459388ef15bef32ff11dcada4910 Mon Sep 17 00:00:00 2001 From: Eric Cestari Date: Tue, 7 Sep 2010 16:22:57 +0200 Subject: [PATCH 25/85] New features : - edit an item - edit node configuration --- doc/http_post.md | 72 ++++++++++++++++++++++++++++++++++++++----- src/web/pshb_http.erl | 65 +++++++++++++++++++++++--------------- 2 files changed, 106 insertions(+), 31 deletions(-) diff --git a/doc/http_post.md b/doc/http_post.md index cbddb4d5c..97cec2a07 100644 --- a/doc/http_post.md +++ b/doc/http_post.md @@ -23,22 +23,50 @@ In the current version of the code, some security checks are not done : ## Usage example with cURL ## +### Errors ### + +HTTP status codes are used as intended. Additionally, the XMPP error stanza can also be set in the body : + + $ curl -i -X POST -u cstar@localhost:encore -d @createnode.xml http://localhost:5280/pshb/localhost + HTTP/1.1 409 Conflict + Content-Type: text/html; charset=utf-8 + Content-Length: 95 + Content-type: application/xml + + + +or + + $ curl -i -X DELETE -u cstar@localhost:encore http://localhost:5280/pshb/localhost/princely_musings + HTTP/1.1 404 Not Found + Content-Type: text/html; charset=utf-8 + Content-Length: 101 + Content-type: application/xml + + + ### Getting the service document ### No authentication necessary. All nodes are listed. - curl -i http://host:port/pshb/domain/ + $ curl -i http://host:port/pshb/domain/ ### Getting items from a node ### No authentication done, and all nodes are accessible. - curl -i http://host:port/pshb/domain/node/ + $ curl -i http://host:port/pshb/domain/node/ ### Posting a new item ### - curl -u jid:password -i -X POST -d @entry.atom http://post:port/pshb/domain/node + $ curl -u jid:password -i -X POST -d @entry.atom http://post:port/pshb/domain/node + +User ability to post is based on node configuration. + +### Editing a new item ### + + $ curl -u jid:password -i -X POST -d @entry.atom http://post:port/pshb/domain/node/itemid User ability to post is based on node configuration. @@ -47,11 +75,11 @@ User ability to post is based on node configuration. An instant node can be created if server configuration allows: - curl -X POST -u cstar@localhost:encore -d "" http://localhost:5280/pshb/localhost + $ curl -X POST -u cstar@localhost:encore -d "" http://localhost:5280/pshb/localhost or - curl -X POST -u cstar@localhost:encore -d "" http://localhost:5280/pshb/localhost + $ curl -X POST -u cstar@localhost:encore -d "" http://localhost:5280/pshb/localhost configure element (as per XEP-60) can be passed in the pubsub body. @@ -67,13 +95,43 @@ configure element (as per XEP-60) can be passed in the pubsub body. - $ curl -X POST -u cstar@localhost:encore -d @createnode.xml http://localhost:5280/pshb/localhost + $ curl -i -X POST -u cstar@localhost:encore -d @createnode.xml http://localhost:5280/pshb/localhost + HTTP/1.1 200 OK + Content-Length: 130 + Content-Type: application/xml + + + +### Editing a node configuration ### + + $ cat editnode.xml + + + + + http://jabber.org/protocol/pubsub#node_config + + Princely Musings (Atom) + 1 + 1 + 1 + 10 + 604800 + roster + + + + + + $ curl -i -X PUT -u cstar@localhost:encore -d @createnode.xml http://localhost:5280/pshb/localhost/princely_musings + + ### Deleting a node ### A node is deleted by: - curl -X DELETE -u cstar@localhost:encore http://localhost:5280/pshb/localhost/princely_musings + $ curl -X DELETE -u cstar@localhost:encore http://localhost:5280/pshb/localhost/princely_musings diff --git a/src/web/pshb_http.erl b/src/web/pshb_http.erl index 89eea479e..0b48b378d 100644 --- a/src/web/pshb_http.erl +++ b/src/web/pshb_http.erl @@ -49,7 +49,7 @@ process(LocalPath, #request{auth = Auth} = Request)-> ?DEBUG("LocalPath = ~p", [LocalPath]), UD = get_auth(Auth), - case catch out(Request, Request#request.method, LocalPath,UD) of + case out(Request, Request#request.method, LocalPath,UD) of {'EXIT', Error} -> ?ERROR_MSG("Error while processing ~p : ~n~p", [LocalPath, Error]), error(500); @@ -110,26 +110,26 @@ out(Args, 'GET', [Domain,Node]=Uri, _User) -> end end; -out(Args, 'POST', [Domain, Node]=Uri, {User, _Domain}) -> - Slug = uniqid(false), - Payload = xml_stream:parse_element(Args#request.data), - [FilteredPayload]=xml:remove_cdata([Payload]), +out(Args, 'POST', [_D, _Node]=Uri, {_User, _Domain} = UD) -> + publish_item(Args, Uri, uniqid(false), UD); - %FilteredPayload2 = case xml:get_subtag(FilteredPayload, "app:edited") -> - % {xmlelement, Name, Attrs, [{cdata, }]} - case mod_pubsub:publish_item(get_host(Uri), - Domain, - get_collection(Uri), - jlib:make_jid(User,Domain, ""), - Slug, - [FilteredPayload]) of - {result, [_]} -> - ?DEBUG("Publishing to ~p~n",[entry_uri(Args, Domain, Node,Slug)]), - {201, [{"location", entry_uri(Args, Domain,Node,Slug)}], Payload}; - {error, Error} -> - error(Error) - end; - +out(Args, 'PUT', [_D, _Node, Slug]=Uri, {_User, _Domain} = UD) -> + publish_item(Args, Uri, Slug, UD); + + +out(Args, 'PUT', [_Domain, Node]= Uri, {User, UDomain}) -> + Host = get_host(Uri), + Jid = jlib:make_jid({User, UDomain, ""}), + Payload = xml_stream:parse_element(Args#request.data), + ConfigureElement = case xml:get_subtag(Payload, "configure") of + false ->[]; + {xmlelement, _, _, SubEls}->SubEls + end, + case mod_pubsub:set_configure(Host, list_to_binary(Node), Jid, ConfigureElement, Args#request.lang) of + {result, []} -> success(200); + {error, Error} -> error(Error) + end; + out(Args, 'GET', [Domain]=Uri, From)-> Host = get_host(Uri), ?DEBUG("Host = ~p", [Host]), @@ -150,7 +150,6 @@ out(Args, 'POST', [Domain]=Uri, {User, UDomain})-> E -> {list_to_binary(get_tag_attr_or_default("node", E,"")), get_tag_attr_or_default("type", E,"flat")} - end, ConfigureElement = case xml:get_subtag(Payload, "configure") of false ->[]; @@ -166,7 +165,7 @@ out(Args, 'POST', [Domain]=Uri, {User, UDomain})-> ++ xml:element_to_string(Result)} end; -out(Args, 'DELETE', [Domain, Node] = Uri, {User, UDomain})-> +out(_Args, 'DELETE', [_Domain, Node] = Uri, {User, UDomain})-> Host = get_host(Uri), Jid = jlib:make_jid({User, UDomain, ""}), BinNode = list_to_binary(Node), @@ -208,6 +207,26 @@ get_item(Uri, Failure, Success)-> #pubsub_item{}=Item -> Success(Item) end. + +publish_item(Args, [Domain, Node | _R] = Uri, Slug, {User, Domain})-> + + Payload = xml_stream:parse_element(Args#request.data), + [FilteredPayload]=xml:remove_cdata([Payload]), + + %FilteredPayload2 = case xml:get_subtag(FilteredPayload, "app:edited") -> + % {xmlelement, Name, Attrs, [{cdata, }]} + case mod_pubsub:publish_item(get_host(Uri), + Domain, + get_collection(Uri), + jlib:make_jid(User,Domain, ""), + Slug, + [FilteredPayload]) of + {result, [_]} -> + ?DEBUG("Publishing to ~p~n",[entry_uri(Args, Domain, Node,Slug)]), + {201, [{"location", entry_uri(Args, Domain,Node,Slug)}], Payload}; + {error, Error} -> + error(Error) + end. generate_etag(#pubsub_item{modification={{_, D2, D3}, _JID}})->integer_to_list(D3+D2). get_host([Domain|_Rest])-> "pubsub."++Domain. @@ -284,8 +303,6 @@ error(401)-> {401, [{"WWW-Authenticate", "basic realm=\"ejabberd\""}],"Unauthorized"}; error(Code)-> {Code, [], ""}. -error(Code, Error) when is_list(Error) -> {Code, [], Error}; -error(Code, _Error) -> {Code, [], "Bad request"}. success(200)-> {200, [], ""}; success(Code)-> From 31da259a75fd047d4365b9b7cc75cc9993928e13 Mon Sep 17 00:00:00 2001 From: Eric Cestari Date: Tue, 7 Sep 2010 16:42:12 +0200 Subject: [PATCH 26/85] HTTP Delete item --- doc/http_post.md | 6 ++++++ src/web/pshb_http.erl | 8 ++++++++ 2 files changed, 14 insertions(+) diff --git a/doc/http_post.md b/doc/http_post.md index 97cec2a07..d77aa9329 100644 --- a/doc/http_post.md +++ b/doc/http_post.md @@ -70,6 +70,12 @@ User ability to post is based on node configuration. User ability to post is based on node configuration. +### Deleting an item ### + + $ curl -u jid:password -i -X DELETE http://post:port/pshb/domain/node/itemid + +User ability to post is based on node configuration. + ### Creating a new node ### diff --git a/src/web/pshb_http.erl b/src/web/pshb_http.erl index 0b48b378d..f7967b285 100644 --- a/src/web/pshb_http.erl +++ b/src/web/pshb_http.erl @@ -116,6 +116,14 @@ out(Args, 'POST', [_D, _Node]=Uri, {_User, _Domain} = UD) -> out(Args, 'PUT', [_D, _Node, Slug]=Uri, {_User, _Domain} = UD) -> publish_item(Args, Uri, Slug, UD); +out(Args, 'DELETE', [_D, Node, Id]= Uri, {User, UDomain}) -> + Host = get_host(Uri), + Jid = jlib:make_jid({User, UDomain, ""}), + case mod_pubsub:delete_item(get_host(Uri), list_to_binary(Node), Jid, Id) of + {error, Error} -> error(Error); + {result, Res} -> success(200) + end; + out(Args, 'PUT', [_Domain, Node]= Uri, {User, UDomain}) -> Host = get_host(Uri), From 86a59fb469964b175cccca5434636d002ee120c9 Mon Sep 17 00:00:00 2001 From: Eric Cestari Date: Tue, 7 Sep 2010 17:23:13 +0200 Subject: [PATCH 27/85] Implemented rough access_model access control. --- doc/http_post.md | 7 ++- src/web/pshb_http.erl | 136 +++++++++++++++++++++++------------------- 2 files changed, 81 insertions(+), 62 deletions(-) diff --git a/doc/http_post.md b/doc/http_post.md index d77aa9329..359fb2adf 100644 --- a/doc/http_post.md +++ b/doc/http_post.md @@ -13,14 +13,17 @@ Also, in the ejabberd_http handler configuration, add the identified line. {request_handlers, [{["pshb"], pshb_http}]} % this should be added ]} +It will automatically detect the version of mod_pubsub (odbc or mnesia) and call the appropriate module. + ## Important notice ## In the current version of the code, some security checks are not done : - * read operations can all be done without authentication - * node creation uses the default `all` access_createnode acl, not checking for the actual configuration. + * most read operations are successfully executed without authentication. HOWEVER listing items can only be done when the node access_model is "open". In all other cases, the service returns 403. A finer grained authentication will be implemented. + + ## Usage example with cURL ## ### Errors ### diff --git a/src/web/pshb_http.erl b/src/web/pshb_http.erl index f7967b285..dd42965f7 100644 --- a/src/web/pshb_http.erl +++ b/src/web/pshb_http.erl @@ -46,10 +46,10 @@ -export([process/2]). -process(LocalPath, #request{auth = Auth} = Request)-> - ?DEBUG("LocalPath = ~p", [LocalPath]), +process([Domain | _Rest] = LocalPath, #request{auth = Auth} = Request)-> UD = get_auth(Auth), - case out(Request, Request#request.method, LocalPath,UD) of + Module = backend(Domain), + case out(Module, Request, Request#request.method, LocalPath,UD) of {'EXIT', Error} -> ?ERROR_MSG("Error while processing ~p : ~n~p", [LocalPath, Error]), error(500); @@ -75,57 +75,66 @@ get_auth(Auth) -> undefined end. -out(Args, 'GET', [Domain,Node]=Uri, _User) -> - case mod_pubsub:tree_action(get_host(Uri), get_node, [get_host(Uri),get_collection(Uri)]) of - {error, Error} -> error(Error); - _ -> - Items = lists:sort(fun(X,Y)-> - {DateX, _} = X#pubsub_item.modification, - {DateY, _} = Y#pubsub_item.modification, - DateX > DateY - end, mod_pubsub:get_items( - get_host(Uri), - get_collection(Uri))), - case Items of - [] -> ?DEBUG("Items : ~p ~n", [collection(get_collection(Uri), - collection_uri(Args,Domain,Node), calendar:now_to_universal_time(erlang:now()), "", [])]), - {200, [{"Content-Type", "application/atom+xml"}], - collection(get_collection(Uri), - collection_uri(Args,Domain,Node), calendar:now_to_universal_time(erlang:now()), "", [])}; - _ -> - #pubsub_item{modification = {LastDate, _JID}} = LastItem = hd(Items), - Etag =generate_etag(LastItem), - IfNoneMatch=proplists:get_value('If-None-Match', Args#request.headers), - if IfNoneMatch==Etag - -> - success(304); - true -> - XMLEntries= [item_to_entry(Args,Domain, Node,Entry)||Entry <- Items], - {200, [{"Content-Type", "application/atom+xml"},{"Etag", Etag}], - "" - ++ xml:element_to_string( - collection(get_collection(Uri), collection_uri(Args,Domain,Node), - calendar:now_to_universal_time(LastDate), "", XMLEntries))} - end - end +out(Module, Args, 'GET', [Domain,Node]=Uri, _User) -> + case Module:tree_action(get_host(Uri), get_node, [get_host(Uri),get_collection(Uri)]) of + {error, Error} -> + error(Error); + #pubsub_node{options = Options}-> + AccessModel = lists:keyfind(access_model, 1, Options), + ?INFO_MSG("Uri ~p requested. access_model is ~p. HTTP access denied unless access_model =:= open",[Uri, AccessModel]), + case AccessModel of + {access_model, open} -> + Items = lists:sort(fun(X,Y)-> + {DateX, _} = X#pubsub_item.modification, + {DateY, _} = Y#pubsub_item.modification, + DateX > DateY + end, Module:get_items( + get_host(Uri), + get_collection(Uri))), + case Items of + [] -> ?DEBUG("Items : ~p ~n", [collection(get_collection(Uri), + collection_uri(Args,Domain,Node), calendar:now_to_universal_time(erlang:now()), "", [])]), + {200, [{"Content-Type", "application/atom+xml"}], + collection(get_collection(Uri), + collection_uri(Args,Domain,Node), calendar:now_to_universal_time(erlang:now()), "", [])}; + _ -> + #pubsub_item{modification = {LastDate, _JID}} = LastItem = hd(Items), + Etag =generate_etag(LastItem), + IfNoneMatch=proplists:get_value('If-None-Match', Args#request.headers), + if IfNoneMatch==Etag + -> + success(304); + true -> + XMLEntries= [item_to_entry(Args,Domain, Node,Entry)||Entry <- Items], + {200, [{"Content-Type", "application/atom+xml"},{"Etag", Etag}], + "" + ++ xml:element_to_string( + collection(get_collection(Uri), collection_uri(Args,Domain,Node), + calendar:now_to_universal_time(LastDate), "", XMLEntries))} + end + end; + {access_model, Access} -> + ?INFO_MSG("Uri ~p requested. access_model is ~p. HTTP access denied unless access_model =:= open", + [Uri, Access]), + error(?ERR_FORBIDDEN) + end end; -out(Args, 'POST', [_D, _Node]=Uri, {_User, _Domain} = UD) -> - publish_item(Args, Uri, uniqid(false), UD); +out(Module, Args, 'POST', [_D, _Node]=Uri, {_User, _Domain} = UD) -> + publish_item(Module, Args, Uri, uniqid(false), UD); -out(Args, 'PUT', [_D, _Node, Slug]=Uri, {_User, _Domain} = UD) -> - publish_item(Args, Uri, Slug, UD); +out(Module, Args, 'PUT', [_D, _Node, Slug]=Uri, {_User, _Domain} = UD) -> + publish_item(Module, Args, Uri, Slug, UD); -out(Args, 'DELETE', [_D, Node, Id]= Uri, {User, UDomain}) -> - Host = get_host(Uri), +out(Module, _Args, 'DELETE', [_D, Node, Id]= Uri, {User, UDomain}) -> Jid = jlib:make_jid({User, UDomain, ""}), - case mod_pubsub:delete_item(get_host(Uri), list_to_binary(Node), Jid, Id) of + case Module:delete_item(get_host(Uri), list_to_binary(Node), Jid, Id) of {error, Error} -> error(Error); - {result, Res} -> success(200) + {result, _Res} -> success(200) end; -out(Args, 'PUT', [_Domain, Node]= Uri, {User, UDomain}) -> +out(Module, Args, 'PUT', [_Domain, Node]= Uri, {User, UDomain}) -> Host = get_host(Uri), Jid = jlib:make_jid({User, UDomain, ""}), Payload = xml_stream:parse_element(Args#request.data), @@ -133,15 +142,15 @@ out(Args, 'PUT', [_Domain, Node]= Uri, {User, UDomain}) -> false ->[]; {xmlelement, _, _, SubEls}->SubEls end, - case mod_pubsub:set_configure(Host, list_to_binary(Node), Jid, ConfigureElement, Args#request.lang) of + case Module:set_configure(Host, list_to_binary(Node), Jid, ConfigureElement, Args#request.lang) of {result, []} -> success(200); {error, Error} -> error(Error) end; -out(Args, 'GET', [Domain]=Uri, From)-> +out(Module, Args, 'GET', [Domain]=Uri, From)-> Host = get_host(Uri), ?DEBUG("Host = ~p", [Host]), - case mod_pubsub:tree_action(Host, get_subnodes, [Host, <<>>, From ]) of + case Module:tree_action(Host, get_subnodes, [Host, <<>>, From ]) of [] -> ?DEBUG("Error getting URI ~p : ~p",[Uri, From]), error(?ERR_ITEM_NOT_FOUND); @@ -150,7 +159,7 @@ out(Args, 'GET', [Domain]=Uri, From)-> ++ xml:element_to_string(service(Args,Domain, Collections))} end; -out(Args, 'POST', [Domain]=Uri, {User, UDomain})-> +out(Module, Args, 'POST', [Domain]=Uri, {User, UDomain})-> Host = get_host(Uri), Payload = xml_stream:parse_element(Args#request.data), {Node, Type} = case xml:get_subtag(Payload, "create") of @@ -164,7 +173,7 @@ out(Args, 'POST', [Domain]=Uri, {User, UDomain})-> {xmlelement, _, _, SubEls}->SubEls end, Jid = jlib:make_jid({User, UDomain, ""}), - case mod_pubsub:create_node(Host, Domain, Node, Jid, Type, all, ConfigureElement) of + case Module:create_node(Host, Domain, Node, Jid, Type, all, ConfigureElement) of {error, Error} -> ?ERROR_MSG("Error create node via HTTP : ~p",[Error]), error(Error); % will probably detail more @@ -173,11 +182,11 @@ out(Args, 'POST', [Domain]=Uri, {User, UDomain})-> ++ xml:element_to_string(Result)} end; -out(_Args, 'DELETE', [_Domain, Node] = Uri, {User, UDomain})-> +out(Module,_Args, 'DELETE', [_Domain, Node] = Uri, {User, UDomain})-> Host = get_host(Uri), Jid = jlib:make_jid({User, UDomain, ""}), BinNode = list_to_binary(Node), - case mod_pubsub:delete_node(Host, BinNode, Jid) of + case Module:delete_node(Host, BinNode, Jid) of {error, Error} -> error(Error); {result, []} -> {200, [],[]} @@ -185,7 +194,7 @@ out(_Args, 'DELETE', [_Domain, Node] = Uri, {User, UDomain})-> -out(Args, 'GET', [Domain, Node, _Item]=URI, _) -> +out(Module, Args, 'GET', [Domain, Node, _Item]=URI, _) -> Failure = fun(Error)-> ?DEBUG("Error getting URI ~p : ~p",[URI, Error]), error(Error) @@ -201,29 +210,29 @@ out(Args, 'GET', [Domain, Node, _Item]=URI, _) -> ++ xml:element_to_string(item_to_entry(Args, Domain,Node, Item))} end end, - get_item(URI, Failure, Success); + get_item(Module, URI, Failure, Success); -out(_,Method,Uri,undefined) -> +out(_Module,_,Method,Uri,undefined) -> ?DEBUG("Error, ~p not authorized for ~p : ~p",[ Method,Uri]), error(?ERR_FORBIDDEN). -get_item(Uri, Failure, Success)-> - ?DEBUG(" mod_pubsub:get_item(~p, ~p,~p)", [get_host(Uri), get_collection(Uri), get_member(Uri)]), - case mod_pubsub:get_item(get_host(Uri), get_collection(Uri), get_member(Uri)) of +get_item(Module, Uri, Failure, Success)-> + ?DEBUG(" Module:get_item(~p, ~p,~p)", [get_host(Uri), get_collection(Uri), get_member(Uri)]), + case Module:get_item(get_host(Uri), get_collection(Uri), get_member(Uri)) of {error, Reason} -> Failure(Reason); #pubsub_item{}=Item -> Success(Item) end. -publish_item(Args, [Domain, Node | _R] = Uri, Slug, {User, Domain})-> +publish_item(Module, Args, [Domain, Node | _R] = Uri, Slug, {User, Domain})-> Payload = xml_stream:parse_element(Args#request.data), [FilteredPayload]=xml:remove_cdata([Payload]), %FilteredPayload2 = case xml:get_subtag(FilteredPayload, "app:edited") -> % {xmlelement, Name, Attrs, [{cdata, }]} - case mod_pubsub:publish_item(get_host(Uri), + case Module:publish_item(get_host(Uri), Domain, get_collection(Uri), jlib:make_jid(User,Domain, ""), @@ -316,6 +325,13 @@ success(200)-> success(Code)-> {Code, [], ""}. +backend(Domain)-> + Modules = gen_mod:loaded_modules(Domain), + case lists:member(mod_pubsub_odbc, Modules) of + true -> mod_pubsub_odbc; + _ -> mod_pubsub + end. + % Code below is taken (with some modifications) from the yaws webserver, which % is distributed under the folowing license: From c29b2fda991a4d090b0a729a41b6fb0e0022e050 Mon Sep 17 00:00:00 2001 From: Evgeniy Khramtsov Date: Wed, 8 Sep 2010 02:33:49 +1000 Subject: [PATCH 28/85] cache lifetime should be converted in microseconds --- src/cache_tab.erl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cache_tab.erl b/src/cache_tab.erl index 75ef6159a..b05e78b0e 100644 --- a/src/cache_tab.erl +++ b/src/cache_tab.erl @@ -335,11 +335,11 @@ do_setopts(#state{procs_num = N} = State, Opts) -> LifeTime = case {proplists:get_value(life_time, Opts), State#state.life_time} of {LT, _} when is_integer(LT), LT > 0 -> - LT*1000; + LT*1000*1000; {unlimited, _} -> unlimited; {_, undefined} -> - ?LIFETIME*1000; + ?LIFETIME*1000*1000; {_, LT} -> LT end, From f284fc32841aa24848474b29cc3ec6d73c34ee83 Mon Sep 17 00:00:00 2001 From: Eric Cestari Date: Wed, 8 Sep 2010 15:30:28 +0200 Subject: [PATCH 29/85] [TECH-1068] Atom feed is good enough. --- src/web/pshb_http.erl | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/web/pshb_http.erl b/src/web/pshb_http.erl index dd42965f7..20f472812 100644 --- a/src/web/pshb_http.erl +++ b/src/web/pshb_http.erl @@ -81,7 +81,6 @@ out(Module, Args, 'GET', [Domain,Node]=Uri, _User) -> error(Error); #pubsub_node{options = Options}-> AccessModel = lists:keyfind(access_model, 1, Options), - ?INFO_MSG("Uri ~p requested. access_model is ~p. HTTP access denied unless access_model =:= open",[Uri, AccessModel]), case AccessModel of {access_model, open} -> Items = lists:sort(fun(X,Y)-> @@ -107,7 +106,7 @@ out(Module, Args, 'GET', [Domain,Node]=Uri, _User) -> true -> XMLEntries= [item_to_entry(Args,Domain, Node,Entry)||Entry <- Items], {200, [{"Content-Type", "application/atom+xml"},{"Etag", Etag}], - "" + "\n" ++ xml:element_to_string( collection(get_collection(Uri), collection_uri(Args,Domain,Node), calendar:now_to_universal_time(LastDate), "", XMLEntries))} @@ -269,9 +268,11 @@ item_to_entry(Args,Domain, Node, Id,{xmlelement, "entry", Attrs, SubEl}, Date = calendar:now_to_local_time(Secs), {_User, Domain, _}=jlib:jid_tolower(JID), SubEl2=[{xmlelement, "app:edited", [], [{xmlcdata, w3cdtf(Date)}]}, + {xmlelement, "updated", [],[{xmlcdata, w3cdtf(Date)}]}, + {xmlelement, "author", [],[{xmlelement, "name", [], [{xmlcdata, list_to_binary(jlib:jid_to_string(JID))}]}]}, {xmlelement, "link",[{"rel", "edit"}, - {"href", entry_uri(Args,Domain,Node, Id)}],[] }, - {xmlelement, "id", [],[{xmlcdata, Id}]} + {"href", entry_uri(Args,Domain,Node, Id)}],[] }, + {xmlelement, "id", [],[{xmlcdata, entry_uri(Args, Domain, Node, Id)}]} | SubEl], {xmlelement, "entry", [{"xmlns:app","http://www.w3.org/2007/app"}|Attrs], SubEl2}; @@ -286,8 +287,10 @@ collection(Title, Link, Updated, _Id, Entries)-> {xmlelement, "feed", [{"xmlns", "http://www.w3.org/2005/Atom"}, {"xmlns:app", "http://www.w3.org/2007/app"}], [ {xmlelement, "title", [],[{xmlcdata, Title}]}, + {xmlelement, "generator", [],[{xmlcdata, <<"ejabberd">>}]}, {xmlelement, "updated", [],[{xmlcdata, w3cdtf(Updated)}]}, - {xmlelement, "link", [{"href", Link}], []}, + {xmlelement, "link", [{"href", Link}, {"rel", "self"}], []}, + {xmlelement, "id", [], [{xmlcdata, list_to_binary(Link)}]}, {xmlelement, "title", [],[{xmlcdata, Title}]} | Entries ]}. From 6c7316cbdd3b21ee85e9a158bf45a2c0e043c7da Mon Sep 17 00:00:00 2001 From: Christophe Romain Date: Tue, 25 May 2010 16:22:27 +0200 Subject: [PATCH 30/85] apply flash hack patch --- doc/guide.tex | 25 ++- src/Makefile.in | 7 +- src/configure | 359 ++++++++++++++++++++++++------------------- src/configure.ac | 9 ++ src/ejabberd.hrl | 7 + src/ejabberd_c2s.erl | 120 +++++++++++++-- src/expat_erl.c | 29 ++++ src/jlib.hrl | 1 + 8 files changed, 376 insertions(+), 181 deletions(-) diff --git a/doc/guide.tex b/doc/guide.tex index 73f848f52..8bcd9b25f 100644 --- a/doc/guide.tex +++ b/doc/guide.tex @@ -386,6 +386,9 @@ Some options that you may be interested in modifying: \titem{--enable-nif} Replaces some critical Erlang functions with equivalents written in C to improve performance. This feature requires Erlang/OTP R13B04 or higher. + + \titem{--enable-flash-hack} + Enable support for non-standard XML socket clients of Adobe Flash 8 and lower. \end{description} \makesubsection{install}{Install} @@ -2000,9 +2003,19 @@ enabled. This can be done, by using next commands: \makesubsubsection{configuremssql}{Database Connection} \ind{Microsoft SQL Server!Database Connection} -The configuration of Database Connection for a Microsoft SQL Server -is the same as the configuration for -ODBC compatible servers (see section~\ref{configureodbc}). +By default \ejabberd{} opens 10 connections to the database for each virtual host. +Use this option to modify the value: +\begin{verbatim} +{odbc_pool_size, 10}. +\end{verbatim} + +You can configure an interval to make a dummy SQL request +to keep alive the connections to the database. +The default value is 'undefined', so no keepalive requests are made. +Specify in seconds: for example 28800 means 8 hours. +\begin{verbatim} +{odbc_keepalive_interval, undefined}. +\end{verbatim} \makesubsubsection{mssqlauth}{Authentication} @@ -2010,8 +2023,7 @@ ODBC compatible servers (see section~\ref{configureodbc}). %TODO: not sure if this section is right!!!!!! -The configuration of Authentication for a Microsoft SQL Server -is the same as the configuration for +The configuration of Microsoft SQL Server is the same as the configuration of ODBC compatible servers (see section~\ref{odbcauth}). \makesubsubsection{mssqlstorage}{Storage} @@ -2218,9 +2230,6 @@ and LDAP server supports \makesubsubsection{ldapconnection}{Connection} -Two connections are established to the LDAP server per vhost, -one for authentication and other for regular calls. - Parameters: \begin{description} \titem{\{ldap\_servers, [Servers, ...]\}} \ind{options!ldap\_server}List of IP addresses or DNS names of your diff --git a/src/Makefile.in b/src/Makefile.in index 4e561813d..312983395 100644 --- a/src/Makefile.in +++ b/src/Makefile.in @@ -74,6 +74,11 @@ ifeq (@pam@, pam) INSTALL_EPAM=install -m 750 $(O_USER) epam $(PBINDIR) endif +ifeq (@flash_hack@, true) + ERLC_FLAGS+=-DENABLE_FLASH_HACK + CPPFLAGS+=-DENABLE_FLASH_HACK +endif + prefix = @prefix@ exec_prefix = @exec_prefix@ @@ -168,7 +173,7 @@ mostlyclean-recursive maintainer-clean-recursive: @ERLC@ -W $(EFLAGS) $*.erl $(ERLSHLIBS): %.so: %.c - $(CC) $(CFLAGS) $(LDFLAGS) $(LIBS) \ + $(CC) $(CFLAGS) $(CPPFLAGS) $(LDFLAGS) $(LIBS) \ $(subst ../,,$(subst .so,.c,$@)) \ $(EXPAT_LIBS) \ $(EXPAT_CFLAGS) \ diff --git a/src/configure b/src/configure index d515abc22..ff51ca020 100755 --- a/src/configure +++ b/src/configure @@ -1,13 +1,13 @@ #! /bin/sh # Guess values for system-dependent variables and create Makefiles. -# Generated by GNU Autoconf 2.65 for ejabberd 2.1.x. +# Generated by GNU Autoconf 2.67 for ejabberd 2.1.x. # # Report bugs to . # # # Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, -# 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation, -# Inc. +# 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software +# Foundation, Inc. # # # This configure script is free software; the Free Software Foundation @@ -319,7 +319,7 @@ $as_echo X"$as_dir" | test -d "$as_dir" && break done test -z "$as_dirs" || eval "mkdir $as_dirs" - } || test -d "$as_dir" || as_fn_error "cannot create directory $as_dir" + } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" } # as_fn_mkdir_p @@ -359,19 +359,19 @@ else fi # as_fn_arith -# as_fn_error ERROR [LINENO LOG_FD] -# --------------------------------- +# as_fn_error STATUS ERROR [LINENO LOG_FD] +# ---------------------------------------- # Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are # provided, also output the error to LOG_FD, referencing LINENO. Then exit the -# script with status $?, using 1 if that was 0. +# script with STATUS, using 1 if that was 0. as_fn_error () { - as_status=$?; test $as_status -eq 0 && as_status=1 - if test "$3"; then - as_lineno=${as_lineno-"$2"} as_lineno_stack=as_lineno_stack=$as_lineno_stack - $as_echo "$as_me:${as_lineno-$LINENO}: error: $1" >&$3 + as_status=$1; test $as_status -eq 0 && as_status=1 + if test "$4"; then + as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 fi - $as_echo "$as_me: error: $1" >&2 + $as_echo "$as_me: error: $2" >&2 as_fn_exit $as_status } # as_fn_error @@ -533,7 +533,7 @@ test -n "$DJDIR" || exec 7<&0 &1 # Name of the host. -# hostname on some systems (SVR3.2, Linux) returns a bogus exit status, +# hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status, # so uname gets run too. ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q` @@ -616,6 +616,7 @@ nif full_xml transient_supervisors db_type +flash_hack roster_gateway_workaround hipe PAM_LIBS @@ -720,6 +721,7 @@ enable_pam with_pam enable_hipe enable_roster_gateway_workaround +enable_flash_hack enable_mssql enable_transient_supervisors enable_full_xml @@ -800,8 +802,9 @@ do fi case $ac_option in - *=*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;; - *) ac_optarg=yes ;; + *=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;; + *=) ac_optarg= ;; + *) ac_optarg=yes ;; esac # Accept the important Cygnus configure options, so we can diagnose typos. @@ -846,7 +849,7 @@ do ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && - as_fn_error "invalid feature name: $ac_useropt" + as_fn_error $? "invalid feature name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in @@ -872,7 +875,7 @@ do ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && - as_fn_error "invalid feature name: $ac_useropt" + as_fn_error $? "invalid feature name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in @@ -1076,7 +1079,7 @@ do ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && - as_fn_error "invalid package name: $ac_useropt" + as_fn_error $? "invalid package name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in @@ -1092,7 +1095,7 @@ do ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && - as_fn_error "invalid package name: $ac_useropt" + as_fn_error $? "invalid package name: $ac_useropt" ac_useropt_orig=$ac_useropt ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in @@ -1122,8 +1125,8 @@ do | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) x_libraries=$ac_optarg ;; - -*) as_fn_error "unrecognized option: \`$ac_option' -Try \`$0 --help' for more information." + -*) as_fn_error $? "unrecognized option: \`$ac_option' +Try \`$0 --help' for more information" ;; *=*) @@ -1131,7 +1134,7 @@ Try \`$0 --help' for more information." # Reject names that are not valid shell variable names. case $ac_envvar in #( '' | [0-9]* | *[!_$as_cr_alnum]* ) - as_fn_error "invalid variable name: \`$ac_envvar'" ;; + as_fn_error $? "invalid variable name: \`$ac_envvar'" ;; esac eval $ac_envvar=\$ac_optarg export $ac_envvar ;; @@ -1149,13 +1152,13 @@ done if test -n "$ac_prev"; then ac_option=--`echo $ac_prev | sed 's/_/-/g'` - as_fn_error "missing argument to $ac_option" + as_fn_error $? "missing argument to $ac_option" fi if test -n "$ac_unrecognized_opts"; then case $enable_option_checking in no) ;; - fatal) as_fn_error "unrecognized options: $ac_unrecognized_opts" ;; + fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;; *) $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;; esac fi @@ -1178,7 +1181,7 @@ do [\\/$]* | ?:[\\/]* ) continue;; NONE | '' ) case $ac_var in *prefix ) continue;; esac;; esac - as_fn_error "expected an absolute directory name for --$ac_var: $ac_val" + as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val" done # There might be people who depend on the old broken behavior: `$host' @@ -1192,8 +1195,8 @@ target=$target_alias if test "x$host_alias" != x; then if test "x$build_alias" = x; then cross_compiling=maybe - $as_echo "$as_me: WARNING: If you wanted to set the --build type, don't use --host. - If a cross compiler is detected then cross compile mode will be used." >&2 + $as_echo "$as_me: WARNING: if you wanted to set the --build type, don't use --host. + If a cross compiler is detected then cross compile mode will be used" >&2 elif test "x$build_alias" != "x$host_alias"; then cross_compiling=yes fi @@ -1208,9 +1211,9 @@ test "$silent" = yes && exec 6>/dev/null ac_pwd=`pwd` && test -n "$ac_pwd" && ac_ls_di=`ls -di .` && ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || - as_fn_error "working directory cannot be determined" + as_fn_error $? "working directory cannot be determined" test "X$ac_ls_di" = "X$ac_pwd_ls_di" || - as_fn_error "pwd does not report name of working directory" + as_fn_error $? "pwd does not report name of working directory" # Find the source files, if location was not specified. @@ -1249,11 +1252,11 @@ else fi if test ! -r "$srcdir/$ac_unique_file"; then test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." - as_fn_error "cannot find sources ($ac_unique_file) in $srcdir" + as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir" fi ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" ac_abs_confdir=`( - cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error "$ac_msg" + cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg" pwd)` # When building in place, set srcdir=. if test "$ac_abs_confdir" = "$ac_pwd"; then @@ -1293,7 +1296,7 @@ Configuration: --help=short display options specific to this package --help=recursive display the short help of all the included packages -V, --version display version information and exit - -q, --quiet, --silent do not print \`checking...' messages + -q, --quiet, --silent do not print \`checking ...' messages --cache-file=FILE cache test results in FILE [disabled] -C, --config-cache alias for \`--cache-file=config.cache' -n, --no-create do not create output files @@ -1368,6 +1371,7 @@ Optional Features: --enable-roster-gateway-workaround turn on workaround for processing gateway subscriptions (default: no) + --enable-flash-hack support Adobe Flash client XML (default: no) --enable-mssql use Microsoft SQL Server database (default: no, requires --enable-odbc) --enable-transient_supervisors @@ -1471,9 +1475,9 @@ test -n "$ac_init_help" && exit $ac_status if $ac_init_version; then cat <<\_ACEOF ejabberd configure 2.1.x -generated by GNU Autoconf 2.65 +generated by GNU Autoconf 2.67 -Copyright (C) 2009 Free Software Foundation, Inc. +Copyright (C) 2010 Free Software Foundation, Inc. This configure script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it. _ACEOF @@ -1589,7 +1593,7 @@ $as_echo "$ac_try_echo"; } >&5 mv -f conftest.er1 conftest.err fi $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; } >/dev/null && { + test $ac_status = 0; } > conftest.i && { test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || test ! -s conftest.err }; then : @@ -1613,10 +1617,10 @@ fi ac_fn_c_check_header_mongrel () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack - if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : + if eval "test \"\${$3+set}\"" = set; then : { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } -if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : +if eval "test \"\${$3+set}\"" = set; then : $as_echo_n "(cached) " >&6 fi eval ac_res=\$$3 @@ -1652,7 +1656,7 @@ if ac_fn_c_try_cpp "$LINENO"; then : else ac_header_preproc=no fi -rm -f conftest.err conftest.$ac_ext +rm -f conftest.err conftest.i conftest.$ac_ext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5 $as_echo "$ac_header_preproc" >&6; } @@ -1675,17 +1679,15 @@ $as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;} $as_echo "$as_me: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 $as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} -( cat <<\_ASBOX -## --------------------------------------- ## +( $as_echo "## --------------------------------------- ## ## Report this to ejabberd@process-one.net ## -## --------------------------------------- ## -_ASBOX +## --------------------------------------- ##" ) | sed "s/^/$as_me: WARNING: /" >&2 ;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } -if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : +if eval "test \"\${$3+set}\"" = set; then : $as_echo_n "(cached) " >&6 else eval "$3=\$ac_header_compiler" @@ -1749,7 +1751,7 @@ ac_fn_c_check_header_compile () as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } -if { as_var=$3; eval "test \"\${$as_var+set}\" = set"; }; then : +if eval "test \"\${$3+set}\"" = set; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext @@ -1817,7 +1819,7 @@ This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. It was created by ejabberd $as_me 2.1.x, which was -generated by GNU Autoconf 2.65. Invocation command line was +generated by GNU Autoconf 2.67. Invocation command line was $ $0 $@ @@ -1927,11 +1929,9 @@ trap 'exit_status=$? { echo - cat <<\_ASBOX -## ---------------- ## + $as_echo "## ---------------- ## ## Cache variables. ## -## ---------------- ## -_ASBOX +## ---------------- ##" echo # The following way of writing the cache mishandles newlines in values, ( @@ -1965,11 +1965,9 @@ $as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; ) echo - cat <<\_ASBOX -## ----------------- ## + $as_echo "## ----------------- ## ## Output variables. ## -## ----------------- ## -_ASBOX +## ----------------- ##" echo for ac_var in $ac_subst_vars do @@ -1982,11 +1980,9 @@ _ASBOX echo if test -n "$ac_subst_files"; then - cat <<\_ASBOX -## ------------------- ## + $as_echo "## ------------------- ## ## File substitutions. ## -## ------------------- ## -_ASBOX +## ------------------- ##" echo for ac_var in $ac_subst_files do @@ -2000,11 +1996,9 @@ _ASBOX fi if test -s confdefs.h; then - cat <<\_ASBOX -## ----------- ## + $as_echo "## ----------- ## ## confdefs.h. ## -## ----------- ## -_ASBOX +## ----------- ##" echo cat confdefs.h echo @@ -2059,7 +2053,12 @@ _ACEOF ac_site_file1=NONE ac_site_file2=NONE if test -n "$CONFIG_SITE"; then - ac_site_file1=$CONFIG_SITE + # We do not want a PATH search for config.site. + case $CONFIG_SITE in #(( + -*) ac_site_file1=./$CONFIG_SITE;; + */*) ac_site_file1=$CONFIG_SITE;; + *) ac_site_file1=./$CONFIG_SITE;; + esac elif test "x$prefix" != xNONE; then ac_site_file1=$prefix/share/config.site ac_site_file2=$prefix/etc/config.site @@ -2074,7 +2073,11 @@ do { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5 $as_echo "$as_me: loading site script $ac_site_file" >&6;} sed 's/^/| /' "$ac_site_file" >&5 - . "$ac_site_file" + . "$ac_site_file" \ + || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "failed to load site script $ac_site_file +See \`config.log' for more details" "$LINENO" 5 ; } fi done @@ -2150,7 +2153,7 @@ if $ac_cache_corrupted; then $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5 $as_echo "$as_me: error: changes in the environment can compromise the build" >&2;} - as_fn_error "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5 + as_fn_error $? "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5 fi ## -------------------- ## ## Main body of script. ## @@ -2465,8 +2468,8 @@ fi test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -as_fn_error "no acceptable C compiler found in \$PATH -See \`config.log' for more details." "$LINENO" 5; } +as_fn_error $? "no acceptable C compiler found in \$PATH +See \`config.log' for more details" "$LINENO" 5 ; } # Provide some information about the compiler. $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5 @@ -2580,9 +2583,8 @@ sed 's/^/| /' conftest.$ac_ext >&5 { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -{ as_fn_set_status 77 -as_fn_error "C compiler cannot create executables -See \`config.log' for more details." "$LINENO" 5; }; } +as_fn_error 77 "C compiler cannot create executables +See \`config.log' for more details" "$LINENO" 5 ; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } @@ -2624,8 +2626,8 @@ done else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -as_fn_error "cannot compute suffix of executables: cannot compile and link -See \`config.log' for more details." "$LINENO" 5; } +as_fn_error $? "cannot compute suffix of executables: cannot compile and link +See \`config.log' for more details" "$LINENO" 5 ; } fi rm -f conftest conftest$ac_cv_exeext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5 @@ -2682,9 +2684,9 @@ $as_echo "$ac_try_echo"; } >&5 else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -as_fn_error "cannot run C compiled programs. +as_fn_error $? "cannot run C compiled programs. If you meant to cross compile, use \`--host'. -See \`config.log' for more details." "$LINENO" 5; } +See \`config.log' for more details" "$LINENO" 5 ; } fi fi fi @@ -2735,8 +2737,8 @@ sed 's/^/| /' conftest.$ac_ext >&5 { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -as_fn_error "cannot compute suffix of object files: cannot compile -See \`config.log' for more details." "$LINENO" 5; } +as_fn_error $? "cannot compute suffix of object files: cannot compile +See \`config.log' for more details" "$LINENO" 5 ; } fi rm -f conftest.$ac_cv_objext conftest.$ac_ext fi @@ -2960,7 +2962,7 @@ ac_compiler_gnu=$ac_cv_c_compiler_gnu $as_echo_n "checking whether ${MAKE-make} sets \$(MAKE)... " >&6; } set x ${MAKE-make} ac_make=`$as_echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'` -if { as_var=ac_cv_prog_make_${ac_make}_set; eval "test \"\${$as_var+set}\" = set"; }; then : +if eval "test \"\${ac_cv_prog_make_${ac_make}_set+set}\"" = set; then : $as_echo_n "(cached) " >&6 else cat >conftest.make <<\_ACEOF @@ -2968,7 +2970,7 @@ SHELL = /bin/sh all: @echo '@@@%%%=$(MAKE)=@@@%%%' _ACEOF -# GNU make sometimes prints "make[1]: Entering...", which would confuse us. +# GNU make sometimes prints "make[1]: Entering ...", which would confuse us. case `${MAKE-make} -f conftest.make 2>/dev/null` in *@@@%%%=?*=@@@%%%*) eval ac_cv_prog_make_${ac_make}_set=yes;; @@ -3202,7 +3204,7 @@ fi if test "z$ERLC" = "z" || test "z$ERL" = "z"; then - as_fn_error "erlang not found" "$LINENO" 5 + as_fn_error $? "erlang not found" "$LINENO" 5 fi @@ -3260,15 +3262,15 @@ libpath(App) -> _EOF if ! $ERLC conftest.erl; then - as_fn_error "could not compile sample program" "$LINENO" 5 + as_fn_error $? "could not compile sample program" "$LINENO" 5 fi if ! $ERL -s conftest -noshell; then - as_fn_error "could not run sample program" "$LINENO" 5 + as_fn_error $? "could not run sample program" "$LINENO" 5 fi if ! test -f conftest.out; then - as_fn_error "erlang program was not properly executed, (conftest.out was not produced)" "$LINENO" 5 + as_fn_error $? "erlang program was not properly executed, (conftest.out was not produced)" "$LINENO" 5 fi # First line @@ -3497,7 +3499,7 @@ else # Broken: fails on valid input. continue fi -rm -f conftest.err conftest.$ac_ext +rm -f conftest.err conftest.i conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. @@ -3513,11 +3515,11 @@ else ac_preproc_ok=: break fi -rm -f conftest.err conftest.$ac_ext +rm -f conftest.err conftest.i conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. -rm -f conftest.err conftest.$ac_ext +rm -f conftest.i conftest.err conftest.$ac_ext if $ac_preproc_ok; then : break fi @@ -3556,7 +3558,7 @@ else # Broken: fails on valid input. continue fi -rm -f conftest.err conftest.$ac_ext +rm -f conftest.err conftest.i conftest.$ac_ext # OK, works on sane cases. Now check whether nonexistent headers # can be detected and how. @@ -3572,18 +3574,18 @@ else ac_preproc_ok=: break fi -rm -f conftest.err conftest.$ac_ext +rm -f conftest.err conftest.i conftest.$ac_ext done # Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. -rm -f conftest.err conftest.$ac_ext +rm -f conftest.i conftest.err conftest.$ac_ext if $ac_preproc_ok; then : else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -as_fn_error "C preprocessor \"$CPP\" fails sanity check -See \`config.log' for more details." "$LINENO" 5; } +as_fn_error $? "C preprocessor \"$CPP\" fails sanity check +See \`config.log' for more details" "$LINENO" 5 ; } fi ac_ext=c @@ -3644,7 +3646,7 @@ esac done IFS=$as_save_IFS if test -z "$ac_cv_path_GREP"; then - as_fn_error "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 + as_fn_error $? "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 fi else ac_cv_path_GREP=$GREP @@ -3710,7 +3712,7 @@ esac done IFS=$as_save_IFS if test -z "$ac_cv_path_EGREP"; then - as_fn_error "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 + as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 fi else ac_cv_path_EGREP=$EGREP @@ -3842,8 +3844,7 @@ do : as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default " -eval as_val=\$$as_ac_Header - if test "x$as_val" = x""yes; then : +if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : cat >>confdefs.h <<_ACEOF #define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 _ACEOF @@ -3911,7 +3912,7 @@ else fi if test $expat_found = no; then - as_fn_error "Could not find development files of Expat library" "$LINENO" 5 + as_fn_error $? "Could not find development files of Expat library" "$LINENO" 5 fi expat_save_CFLAGS="$CFLAGS" CFLAGS="$CFLAGS $EXPAT_CFLAGS" @@ -3932,7 +3933,7 @@ fi done if test $expat_found = no; then - as_fn_error "Could not find expat.h" "$LINENO" 5 + as_fn_error $? "Could not find expat.h" "$LINENO" 5 fi CFLAGS="$expat_save_CFLAGS" CPPFLAGS="$expat_save_CPPFLAGS" @@ -4469,7 +4470,7 @@ else fi if test $zlib_found = no; then - as_fn_error "Could not find development files of zlib library. Install them or disable \`ejabberd_zlib' with: --disable-ejabberd_zlib" "$LINENO" 5 + as_fn_error $? "Could not find development files of zlib library. Install them or disable \`ejabberd_zlib' with: --disable-ejabberd_zlib" "$LINENO" 5 fi zlib_save_CFLAGS="$CFLAGS" CFLAGS="$CFLAGS $ZLIB_CFLAGS" @@ -4490,7 +4491,7 @@ fi done if test $zlib_found = no; then - as_fn_error "Could not find zlib.h. Install it or disable \`ejabberd_zlib' with: --disable-ejabberd_zlib" "$LINENO" 5 + as_fn_error $? "Could not find zlib.h. Install it or disable \`ejabberd_zlib' with: --disable-ejabberd_zlib" "$LINENO" 5 fi CFLAGS="$zlib_save_CFLAGS" CPPFLAGS="$zlib_save_CPPFLAGS" @@ -4581,7 +4582,7 @@ else fi if test $pam_found = no; then - as_fn_error "Could not find development files of PAM library. Install them or disable \`pam' with: --disable-pam" "$LINENO" 5 + as_fn_error $? "Could not find development files of PAM library. Install them or disable \`pam' with: --disable-pam" "$LINENO" 5 fi pam_save_CFLAGS="$CFLAGS" CFLAGS="$CFLAGS $PAM_CFLAGS" @@ -4602,7 +4603,7 @@ fi done if test $pam_found = no; then - as_fn_error "Could not find security/pam_appl.h. Install it or disable \`pam' with: --disable-pam" "$LINENO" 5 + as_fn_error $? "Could not find security/pam_appl.h. Install it or disable \`pam' with: --disable-pam" "$LINENO" 5 fi CFLAGS="$pam_save_CFLAGS" CPPFLAGS="$pam_save_CPPFLAGS" @@ -4617,7 +4618,7 @@ if test "${enable_hipe+set}" = set; then : enableval=$enable_hipe; case "${enableval}" in yes) hipe=true ;; no) hipe=false ;; - *) as_fn_error "bad value ${enableval} for --enable-hipe" "$LINENO" 5 ;; + *) as_fn_error $? "bad value ${enableval} for --enable-hipe" "$LINENO" 5 ;; esac else hipe=false @@ -4630,7 +4631,7 @@ if test "${enable_roster_gateway_workaround+set}" = set; then : enableval=$enable_roster_gateway_workaround; case "${enableval}" in yes) roster_gateway_workaround=true ;; no) roster_gateway_workaround=false ;; - *) as_fn_error "bad value ${enableval} for --enable-roster-gateway-workaround" "$LINENO" 5 ;; + *) as_fn_error $? "bad value ${enableval} for --enable-roster-gateway-workaround" "$LINENO" 5 ;; esac else roster_gateway_workaround=false @@ -4638,12 +4639,25 @@ fi +# Check whether --enable-flash_hack was given. +if test "${enable_flash_hack+set}" = set; then : + enableval=$enable_flash_hack; case "${enableval}" in + yes) flash_hack=true ;; + no) flash_hack=false ;; + *) as_fn_error $? "bad value ${enableval} for --enable-flash-hack" "$LINENO" 5 ;; +esac +else + flash_hack=false +fi + + + # Check whether --enable-mssql was given. if test "${enable_mssql+set}" = set; then : enableval=$enable_mssql; case "${enableval}" in yes) db_type=mssql ;; no) db_type=generic ;; - *) as_fn_error "bad value ${enableval} for --enable-mssql" "$LINENO" 5 ;; + *) as_fn_error $? "bad value ${enableval} for --enable-mssql" "$LINENO" 5 ;; esac else db_type=generic @@ -4656,7 +4670,7 @@ if test "${enable_transient_supervisors+set}" = set; then : enableval=$enable_transient_supervisors; case "${enableval}" in yes) transient_supervisors=true ;; no) transient_supervisors=false ;; - *) as_fn_error "bad value ${enableval} for --enable-transient_supervisors" "$LINENO" 5 ;; + *) as_fn_error $? "bad value ${enableval} for --enable-transient_supervisors" "$LINENO" 5 ;; esac else transient_supervisors=true @@ -4669,7 +4683,7 @@ if test "${enable_full_xml+set}" = set; then : enableval=$enable_full_xml; case "${enableval}" in yes) full_xml=true ;; no) full_xml=false ;; - *) as_fn_error "bad value ${enableval} for --enable-full-xml" "$LINENO" 5 ;; + *) as_fn_error $? "bad value ${enableval} for --enable-full-xml" "$LINENO" 5 ;; esac else full_xml=false @@ -4682,7 +4696,7 @@ if test "${enable_nif+set}" = set; then : enableval=$enable_nif; case "${enableval}" in yes) nif=true ;; no) nif=false ;; - *) as_fn_error "bad value ${enableval} for --enable-nif" "$LINENO" 5 ;; + *) as_fn_error $? "bad value ${enableval} for --enable-nif" "$LINENO" 5 ;; esac else nif=false @@ -4780,7 +4794,7 @@ done fi done if test x${have_openssl} != xyes; then - as_fn_error "Could not find development files of OpenSSL library. Install them or disable \`tls' with: --disable-tls" "$LINENO" 5 + as_fn_error $? "Could not find development files of OpenSSL library. Install them or disable \`tls' with: --disable-tls" "$LINENO" 5 fi @@ -4835,16 +4849,22 @@ fi ac_aux_dir= for ac_dir in "$srcdir" "$srcdir/.." "$srcdir/../.."; do - for ac_t in install-sh install.sh shtool; do - if test -f "$ac_dir/$ac_t"; then - ac_aux_dir=$ac_dir - ac_install_sh="$ac_aux_dir/$ac_t -c" - break 2 - fi - done + if test -f "$ac_dir/install-sh"; then + ac_aux_dir=$ac_dir + ac_install_sh="$ac_aux_dir/install-sh -c" + break + elif test -f "$ac_dir/install.sh"; then + ac_aux_dir=$ac_dir + ac_install_sh="$ac_aux_dir/install.sh -c" + break + elif test -f "$ac_dir/shtool"; then + ac_aux_dir=$ac_dir + ac_install_sh="$ac_aux_dir/shtool install -c" + break + fi done if test -z "$ac_aux_dir"; then - as_fn_error "cannot find install-sh, install.sh, or shtool in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" "$LINENO" 5 + as_fn_error $? "cannot find install-sh, install.sh, or shtool in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" "$LINENO" 5 fi # These three variables are undocumented and unsupported, @@ -4858,7 +4878,7 @@ ac_configure="$SHELL $ac_aux_dir/configure" # Please don't use this var. # Make sure we can run config.sub. $SHELL "$ac_aux_dir/config.sub" sun4 >/dev/null 2>&1 || - as_fn_error "cannot run $SHELL $ac_aux_dir/config.sub" "$LINENO" 5 + as_fn_error $? "cannot run $SHELL $ac_aux_dir/config.sub" "$LINENO" 5 { $as_echo "$as_me:${as_lineno-$LINENO}: checking build system type" >&5 $as_echo_n "checking build system type... " >&6; } @@ -4869,16 +4889,16 @@ else test "x$ac_build_alias" = x && ac_build_alias=`$SHELL "$ac_aux_dir/config.guess"` test "x$ac_build_alias" = x && - as_fn_error "cannot guess build type; you must specify one" "$LINENO" 5 + as_fn_error $? "cannot guess build type; you must specify one" "$LINENO" 5 ac_cv_build=`$SHELL "$ac_aux_dir/config.sub" $ac_build_alias` || - as_fn_error "$SHELL $ac_aux_dir/config.sub $ac_build_alias failed" "$LINENO" 5 + as_fn_error $? "$SHELL $ac_aux_dir/config.sub $ac_build_alias failed" "$LINENO" 5 fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_build" >&5 $as_echo "$ac_cv_build" >&6; } case $ac_cv_build in *-*-*) ;; -*) as_fn_error "invalid value of canonical build" "$LINENO" 5;; +*) as_fn_error $? "invalid value of canonical build" "$LINENO" 5 ;; esac build=$ac_cv_build ac_save_IFS=$IFS; IFS='-' @@ -4903,7 +4923,7 @@ else ac_cv_host=$ac_cv_build else ac_cv_host=`$SHELL "$ac_aux_dir/config.sub" $host_alias` || - as_fn_error "$SHELL $ac_aux_dir/config.sub $host_alias failed" "$LINENO" 5 + as_fn_error $? "$SHELL $ac_aux_dir/config.sub $host_alias failed" "$LINENO" 5 fi fi @@ -4911,7 +4931,7 @@ fi $as_echo "$ac_cv_host" >&6; } case $ac_cv_host in *-*-*) ;; -*) as_fn_error "invalid value of canonical host" "$LINENO" 5;; +*) as_fn_error $? "invalid value of canonical host" "$LINENO" 5 ;; esac host=$ac_cv_host ac_save_IFS=$IFS; IFS='-' @@ -4936,7 +4956,7 @@ else ac_cv_target=$ac_cv_host else ac_cv_target=`$SHELL "$ac_aux_dir/config.sub" $target_alias` || - as_fn_error "$SHELL $ac_aux_dir/config.sub $target_alias failed" "$LINENO" 5 + as_fn_error $? "$SHELL $ac_aux_dir/config.sub $target_alias failed" "$LINENO" 5 fi fi @@ -4944,7 +4964,7 @@ fi $as_echo "$ac_cv_target" >&6; } case $ac_cv_target in *-*-*) ;; -*) as_fn_error "invalid value of canonical target" "$LINENO" 5;; +*) as_fn_error $? "invalid value of canonical target" "$LINENO" 5 ;; esac target=$ac_cv_target ac_save_IFS=$IFS; IFS='-' @@ -5088,8 +5108,8 @@ fi if test "$cross_compiling" = yes; then : { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -as_fn_error "cannot run test program while cross compiling -See \`config.log' for more details." "$LINENO" 5; } +as_fn_error $? "cannot run test program while cross compiling +See \`config.log' for more details" "$LINENO" 5 ; } else cat > conftest.$ac_ext <<_ACEOF -module(conftest). @@ -5243,6 +5263,7 @@ DEFS=`sed -n "$ac_script" confdefs.h` ac_libobjs= ac_ltlibobjs= +U= for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue # 1. Remove the extension, and $U if already installed. ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' @@ -5404,19 +5425,19 @@ export LANGUAGE (unset CDPATH) >/dev/null 2>&1 && unset CDPATH -# as_fn_error ERROR [LINENO LOG_FD] -# --------------------------------- +# as_fn_error STATUS ERROR [LINENO LOG_FD] +# ---------------------------------------- # Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are # provided, also output the error to LOG_FD, referencing LINENO. Then exit the -# script with status $?, using 1 if that was 0. +# script with STATUS, using 1 if that was 0. as_fn_error () { - as_status=$?; test $as_status -eq 0 && as_status=1 - if test "$3"; then - as_lineno=${as_lineno-"$2"} as_lineno_stack=as_lineno_stack=$as_lineno_stack - $as_echo "$as_me:${as_lineno-$LINENO}: error: $1" >&$3 + as_status=$1; test $as_status -eq 0 && as_status=1 + if test "$4"; then + as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 fi - $as_echo "$as_me: error: $1" >&2 + $as_echo "$as_me: error: $2" >&2 as_fn_exit $as_status } # as_fn_error @@ -5612,7 +5633,7 @@ $as_echo X"$as_dir" | test -d "$as_dir" && break done test -z "$as_dirs" || eval "mkdir $as_dirs" - } || test -d "$as_dir" || as_fn_error "cannot create directory $as_dir" + } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" } # as_fn_mkdir_p @@ -5666,7 +5687,7 @@ cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # values after options handling. ac_log=" This file was extended by ejabberd $as_me 2.1.x, which was -generated by GNU Autoconf 2.65. Invocation command line was +generated by GNU Autoconf 2.67. Invocation command line was CONFIG_FILES = $CONFIG_FILES CONFIG_HEADERS = $CONFIG_HEADERS @@ -5719,10 +5740,10 @@ cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`" ac_cs_version="\\ ejabberd config.status 2.1.x -configured by $0, generated by GNU Autoconf 2.65, +configured by $0, generated by GNU Autoconf 2.67, with options \\"\$ac_cs_config\\" -Copyright (C) 2009 Free Software Foundation, Inc. +Copyright (C) 2010 Free Software Foundation, Inc. This config.status script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it." @@ -5737,11 +5758,16 @@ ac_need_defaults=: while test $# != 0 do case $1 in - --*=*) + --*=?*) ac_option=`expr "X$1" : 'X\([^=]*\)='` ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'` ac_shift=: ;; + --*=) + ac_option=`expr "X$1" : 'X\([^=]*\)='` + ac_optarg= + ac_shift=: + ;; *) ac_option=$1 ac_optarg=$2 @@ -5763,6 +5789,7 @@ do $ac_shift case $ac_optarg in *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; + '') as_fn_error $? "missing file argument" ;; esac as_fn_append CONFIG_FILES " '$ac_optarg'" ac_need_defaults=false;; @@ -5773,7 +5800,7 @@ do ac_cs_silent=: ;; # This is an error. - -*) as_fn_error "unrecognized option: \`$1' + -*) as_fn_error $? "unrecognized option: \`$1' Try \`$0 --help' for more information." ;; *) as_fn_append ac_config_targets " $1" @@ -5836,7 +5863,7 @@ do "$make_odbc") CONFIG_FILES="$CONFIG_FILES $make_odbc" ;; "$make_ejabberd_zlib") CONFIG_FILES="$CONFIG_FILES $make_ejabberd_zlib" ;; - *) as_fn_error "invalid argument: \`$ac_config_target'" "$LINENO" 5;; + *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5 ;; esac done @@ -5872,7 +5899,7 @@ $debug || { tmp=./conf$$-$RANDOM (umask 077 && mkdir "$tmp") -} || as_fn_error "cannot create a temporary directory in ." "$LINENO" 5 +} || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5 # Set up the scripts for CONFIG_FILES section. # No need to generate them if there are no CONFIG_FILES. @@ -5889,7 +5916,7 @@ if test "x$ac_cr" = x; then fi ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null` if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then - ac_cs_awk_cr='\r' + ac_cs_awk_cr='\\r' else ac_cs_awk_cr=$ac_cr fi @@ -5903,18 +5930,18 @@ _ACEOF echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' && echo "_ACEOF" } >conf$$subs.sh || - as_fn_error "could not make $CONFIG_STATUS" "$LINENO" 5 -ac_delim_num=`echo "$ac_subst_vars" | grep -c '$'` + as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 +ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'` ac_delim='%!_!# ' for ac_last_try in false false false false false :; do . ./conf$$subs.sh || - as_fn_error "could not make $CONFIG_STATUS" "$LINENO" 5 + as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X` if test $ac_delim_n = $ac_delim_num; then break elif $ac_last_try; then - as_fn_error "could not make $CONFIG_STATUS" "$LINENO" 5 + as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 else ac_delim="$ac_delim!$ac_delim _$ac_delim!! " fi @@ -6003,20 +6030,28 @@ if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then else cat fi < "$tmp/subs1.awk" > "$tmp/subs.awk" \ - || as_fn_error "could not setup config files machinery" "$LINENO" 5 + || as_fn_error $? "could not setup config files machinery" "$LINENO" 5 _ACEOF -# VPATH may cause trouble with some makes, so we remove $(srcdir), -# ${srcdir} and @srcdir@ from VPATH if srcdir is ".", strip leading and +# VPATH may cause trouble with some makes, so we remove sole $(srcdir), +# ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and # trailing colons and then remove the whole line if VPATH becomes empty # (actually we leave an empty line to preserve line numbers). if test "x$srcdir" = x.; then - ac_vpsub='/^[ ]*VPATH[ ]*=/{ -s/:*\$(srcdir):*/:/ -s/:*\${srcdir}:*/:/ -s/:*@srcdir@:*/:/ -s/^\([^=]*=[ ]*\):*/\1/ + ac_vpsub='/^[ ]*VPATH[ ]*=[ ]*/{ +h +s/// +s/^/:/ +s/[ ]*$/:/ +s/:\$(srcdir):/:/g +s/:\${srcdir}:/:/g +s/:@srcdir@:/:/g +s/^:*// s/:*$// +x +s/\(=[ ]*\).*/\1/ +G +s/\n// s/^[^=]*=[ ]*$// }' fi @@ -6034,7 +6069,7 @@ do esac case $ac_mode$ac_tag in :[FHL]*:*);; - :L* | :C*:*) as_fn_error "invalid tag \`$ac_tag'" "$LINENO" 5;; + :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5 ;; :[FH]-) ac_tag=-:-;; :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; esac @@ -6062,7 +6097,7 @@ do [\\/$]*) false;; *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; esac || - as_fn_error "cannot find input file: \`$ac_f'" "$LINENO" 5;; + as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5 ;; esac case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac as_fn_append ac_file_inputs " '$ac_f'" @@ -6089,7 +6124,7 @@ $as_echo "$as_me: creating $ac_file" >&6;} case $ac_tag in *:-:* | *:-) cat >"$tmp/stdin" \ - || as_fn_error "could not create $ac_file" "$LINENO" 5 ;; + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; esac ;; esac @@ -6215,22 +6250,22 @@ s&@abs_top_builddir@&$ac_abs_top_builddir&;t t $ac_datarootdir_hack " eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$tmp/subs.awk" >$tmp/out \ - || as_fn_error "could not create $ac_file" "$LINENO" 5 + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && { ac_out=`sed -n '/\${datarootdir}/p' "$tmp/out"`; test -n "$ac_out"; } && { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' "$tmp/out"`; test -z "$ac_out"; } && { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir' -which seems to be undefined. Please make sure it is defined." >&5 +which seems to be undefined. Please make sure it is defined" >&5 $as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' -which seems to be undefined. Please make sure it is defined." >&2;} +which seems to be undefined. Please make sure it is defined" >&2;} rm -f "$tmp/stdin" case $ac_file in -) cat "$tmp/out" && rm -f "$tmp/out";; *) rm -f "$ac_file" && mv "$tmp/out" "$ac_file";; esac \ - || as_fn_error "could not create $ac_file" "$LINENO" 5 + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; @@ -6245,7 +6280,7 @@ _ACEOF ac_clean_files=$ac_clean_files_save test $ac_write_fail = 0 || - as_fn_error "write failure creating $CONFIG_STATUS" "$LINENO" 5 + as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5 # configure is writing to config.log, and then calls config.status. @@ -6266,7 +6301,7 @@ if test "$no_create" != yes; then exec 5>>config.log # Use ||, not &&, to avoid exiting from the if with $? = 1, which # would make configure fail if this is the last instruction. - $ac_cs_success || as_fn_exit $? + $ac_cs_success || as_fn_exit 1 fi if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5 diff --git a/src/configure.ac b/src/configure.ac index 1d25dd871..5492f429a 100644 --- a/src/configure.ac +++ b/src/configure.ac @@ -67,6 +67,15 @@ AC_ARG_ENABLE(roster_gateway_workaround, esac],[roster_gateway_workaround=false]) AC_SUBST(roster_gateway_workaround) +AC_ARG_ENABLE(flash_hack, +[AC_HELP_STRING([--enable-flash-hack], [support Adobe Flash client XML (default: no)])], +[case "${enableval}" in + yes) flash_hack=true ;; + no) flash_hack=false ;; + *) AC_MSG_ERROR(bad value ${enableval} for --enable-flash-hack) ;; +esac],[flash_hack=false]) +AC_SUBST(flash_hack) + AC_ARG_ENABLE(mssql, [AC_HELP_STRING([--enable-mssql], [use Microsoft SQL Server database (default: no, requires --enable-odbc)])], [case "${enableval}" in diff --git a/src/ejabberd.hrl b/src/ejabberd.hrl index e1f0cfd37..fcc2aeac7 100644 --- a/src/ejabberd.hrl +++ b/src/ejabberd.hrl @@ -31,6 +31,13 @@ -define(CONFIG_PATH, "ejabberd.cfg"). -define(LOG_PATH, "ejabberd.log"). +-ifdef(ENABLE_FLASH_HACK). +-define(FLASH_HACK, true). +-else. +-define(FLASH_HACK, false). +-endif. + + -define(EJABBERD_URI, "http://www.process-one.net/en/ejabberd/"). -define(S2STIMEOUT, 600000). diff --git a/src/ejabberd_c2s.erl b/src/ejabberd_c2s.erl index f48f897e9..8a5c53d7c 100644 --- a/src/ejabberd_c2s.erl +++ b/src/ejabberd_c2s.erl @@ -68,6 +68,42 @@ -include("mod_privacy.hrl"). -include("ejabberd_c2s.hrl"). +-define(SETS, gb_sets). +-define(DICT, dict). + +%% pres_a contains all the presence available send (either through roster mechanism or directed). +%% Directed presence unavailable remove user from pres_a. +-record(state, {socket, + sockmod, + socket_monitor, + xml_socket, + streamid, + sasl_state, + access, + shaper, + zlib = false, + tls = false, + tls_required = false, + tls_enabled = false, + tls_options = [], + authenticated = false, + jid, + user = "", server = ?MYNAME, resource = "", + sid, + pres_t = ?SETS:new(), + pres_f = ?SETS:new(), + pres_a = ?SETS:new(), + pres_i = ?SETS:new(), + pres_last, pres_pri, + pres_timestamp, + pres_invis = false, + privacy_list = #userlist{}, + conn = unknown, + auth_module = unknown, + ip, + lang, + flash_connection = false}). + %-define(DBGFSM, true). -ifdef(DBGFSM). @@ -98,6 +134,13 @@ "id='~s' from='~s'~s~s>" ). +-define(FLASH_STREAM_HEADER, + "" + "" + ). + -define(STREAM_TRAILER, ""). -define(INVALID_NS_ERR, ?SERR_INVALID_NAMESPACE). @@ -252,15 +295,25 @@ get_subscribed(FsmRef) -> %% {stop, Reason, NewStateData} %%---------------------------------------------------------------------- -wait_for_stream({xmlstreamstart, _Name, Attrs}, StateData) -> +wait_for_stream({xmlstreamstart, Name, Attrs}, StateData) -> DefaultLang = case ?MYLANG of undefined -> "en"; DL -> DL end, - case xml:get_attr_s("xmlns:stream", Attrs) of - ?NS_STREAM -> + + case {xml:get_attr_s("xmlns:stream", Attrs), + xml:get_attr_s("xmlns:flash", Attrs), + ?FLASH_HACK, + StateData#state.flash_connection} of + {_, ?NS_FLASH_STREAM, true, false} -> + %% Flash client connecting - attention! + %% Some of them don't provide an xmlns:stream attribute - + %% compensate for that. + wait_for_stream({xmlstreamstart, Name, [{"xmlns:stream", ?NS_STREAM}|Attrs]}, + StateData#state{flash_connection = true}); + {?NS_STREAM, _, _, _} -> Server = jlib:nameprep(xml:get_attr_s("to", Attrs)), case lists:member(Server, ?MYHOSTS) of true -> @@ -403,11 +456,17 @@ wait_for_stream({xmlstreamstart, _Name, Attrs}, StateData) -> send_trailer(StateData), {stop, normal, StateData} end; - _ -> - send_header(StateData, ?MYNAME, "", DefaultLang), - send_element(StateData, ?INVALID_NS_ERR), - send_trailer(StateData), - {stop, normal, StateData} + _ -> + case Name of + "policy-file-request" -> + send_text(StateData, flash_policy_string()), + {stop, normal, StateData}; + _ -> + send_header(StateData, ?MYNAME, "", DefaultLang), + send_element(StateData, ?INVALID_NS_ERR), + send_trailer(StateData), + {stop, normal, StateData} + end end; wait_for_stream(timeout, StateData) -> @@ -1509,8 +1568,15 @@ change_shaper(StateData, JID) -> (StateData#state.sockmod):change_shaper(StateData#state.socket, Shaper). send_text(StateData, Text) -> - ?DEBUG("Send XML on stream = ~p", [Text]), - (StateData#state.sockmod):send(StateData#state.socket, Text). + ?DEBUG("Send XML on stream = ~p", [lists:flatten(Text)]), + Text1 = + if ?FLASH_HACK and StateData#state.flash_connection -> + %% send a null byte after each stanza to Flash clients + [Text, 0]; + true -> + Text + end, + (StateData#state.sockmod):send(StateData#state.socket, Text1). send_element(StateData, El) when StateData#state.xml_socket -> (StateData#state.sockmod):send_xml(StateData#state.socket, @@ -1518,6 +1584,15 @@ send_element(StateData, El) when StateData#state.xml_socket -> send_element(StateData, El) -> send_text(StateData, xml:element_to_binary(El)). +send_header(StateData,Server, Version, Lang) + when StateData#state.flash_connection -> + Header = io_lib:format(?FLASH_STREAM_HEADER, + [StateData#state.streamid, + Server, + Version, + Lang]), + send_text(StateData, Header); + send_header(StateData, Server, Version, Lang) when StateData#state.xml_socket -> VersionAttr = @@ -2364,3 +2439,28 @@ pack_string(String, Pack) -> none -> {String, gb_trees:insert(String, String, Pack)} end. + + +%% @spec () -> string() +%% @doc Build the content of a Flash policy file. +%% It specifies as domain "*". +%% It specifies as to-ports the ports that serve ejabberd_c2s. +flash_policy_string() -> + Listen = ejabberd_config:get_local_option(listen), + ClientPortsDeep = ["," ++ integer_to_list(Port) + || {{Port,_,_}, ejabberd_c2s, _Opts} <- Listen], + %% NOTE: The function string:join/2 was introduced in Erlang/OTP R12B-0 + %% so it can't be used yet in ejabberd. + ToPortsString = case lists:flatten(ClientPortsDeep) of + [$, | Tail] -> Tail; + _ -> [] + end, + + "\n" + "\n" + "\n" + " \n" + "\n\0". diff --git a/src/expat_erl.c b/src/expat_erl.c index f6b552c59..60cd72c88 100644 --- a/src/expat_erl.c +++ b/src/expat_erl.c @@ -138,6 +138,35 @@ static int expat_erl_control(ErlDrvData drv_data, case PARSE_COMMAND: case PARSE_FINAL_COMMAND: ei_x_new_with_version(&event_buf); +#ifdef ENABLE_FLASH_HACK + /* Flash hack - Flash clients send a null byte after the stanza. Remove that... */ + { + int i; + int found_null = 0; + + /* Maybe the Flash client sent many stanzas in one packet. + If so, there is a null byte between every stanza. */ + for (i = 0; i < len; i++) { + if (buf[i] == '\0') { + buf[i] = ' '; + found_null = 1; + } + } + + /* And also remove the closing slash if this is a + flash:stream element. Assume that flash:stream is the + last element in the packet, and entirely contained in + it. This requires that a null byte has been found. */ + if (found_null && strstr(buf, " + buf[len - 3] is / (maybe) + */ + if (buf[len - 3] == '/') + buf[len - 3] = ' '; + } +#endif /* ENABLE_FLASH_HACK */ + res = XML_Parse(d->parser, buf, len, command == PARSE_FINAL_COMMAND); if(!res) diff --git a/src/jlib.hrl b/src/jlib.hrl index fe844be02..cb89f91a5 100644 --- a/src/jlib.hrl +++ b/src/jlib.hrl @@ -67,6 +67,7 @@ -define(NS_EJABBERD_CONFIG, "ejabberd:config"). -define(NS_STREAM, "http://etherx.jabber.org/streams"). +-define(NS_FLASH_STREAM, "http://www.jabber.com/streams/flash"). -define(NS_STANZAS, "urn:ietf:params:xml:ns:xmpp-stanzas"). -define(NS_STREAMS, "urn:ietf:params:xml:ns:xmpp-streams"). From 92a60ff7fd16fb36c8b5750ef2d3cfe88a87370c Mon Sep 17 00:00:00 2001 From: Eric Cestari Date: Wed, 8 Sep 2010 17:03:49 +0200 Subject: [PATCH 31/85] flash hack merge fix from BBC --- src/ejabberd_c2s.erl | 36 ------------------------------------ src/ejabberd_c2s.hrl | 3 ++- 2 files changed, 2 insertions(+), 37 deletions(-) diff --git a/src/ejabberd_c2s.erl b/src/ejabberd_c2s.erl index 8a5c53d7c..17539829d 100644 --- a/src/ejabberd_c2s.erl +++ b/src/ejabberd_c2s.erl @@ -68,42 +68,6 @@ -include("mod_privacy.hrl"). -include("ejabberd_c2s.hrl"). --define(SETS, gb_sets). --define(DICT, dict). - -%% pres_a contains all the presence available send (either through roster mechanism or directed). -%% Directed presence unavailable remove user from pres_a. --record(state, {socket, - sockmod, - socket_monitor, - xml_socket, - streamid, - sasl_state, - access, - shaper, - zlib = false, - tls = false, - tls_required = false, - tls_enabled = false, - tls_options = [], - authenticated = false, - jid, - user = "", server = ?MYNAME, resource = "", - sid, - pres_t = ?SETS:new(), - pres_f = ?SETS:new(), - pres_a = ?SETS:new(), - pres_i = ?SETS:new(), - pres_last, pres_pri, - pres_timestamp, - pres_invis = false, - privacy_list = #userlist{}, - conn = unknown, - auth_module = unknown, - ip, - lang, - flash_connection = false}). - %-define(DBGFSM, true). -ifdef(DBGFSM). diff --git a/src/ejabberd_c2s.hrl b/src/ejabberd_c2s.hrl index 485a6e400..e2e3c2439 100644 --- a/src/ejabberd_c2s.hrl +++ b/src/ejabberd_c2s.hrl @@ -59,4 +59,5 @@ ip, fsm_limit_opts, lang, - debug=false}). + debug=false, + flash_connection = false}). \ No newline at end of file From 49a3424a2680a28435c4bccaca00b4672b8451bc Mon Sep 17 00:00:00 2001 From: Eric Cestari Date: Wed, 8 Sep 2010 17:21:49 +0200 Subject: [PATCH 32/85] add *.so to .gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 5b89fb9d5..d68bd6fe6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ Makefile archives .gitignore +*.so contrib/extract_translations/extract_translations.beam doc/contributed_modules.tex doc/features.aux From a77d53d738c411a856a5917fb686789a6831f8ae Mon Sep 17 00:00:00 2001 From: Eric Cestari Date: Wed, 8 Sep 2010 17:25:37 +0200 Subject: [PATCH 33/85] [TECH-1068] Added missing catch in process function --- src/web/pshb_http.erl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/web/pshb_http.erl b/src/web/pshb_http.erl index 20f472812..47efa0fc6 100644 --- a/src/web/pshb_http.erl +++ b/src/web/pshb_http.erl @@ -49,7 +49,7 @@ process([Domain | _Rest] = LocalPath, #request{auth = Auth} = Request)-> UD = get_auth(Auth), Module = backend(Domain), - case out(Module, Request, Request#request.method, LocalPath,UD) of + case catch out(Module, Request, Request#request.method, LocalPath,UD) of {'EXIT', Error} -> ?ERROR_MSG("Error while processing ~p : ~n~p", [LocalPath, Error]), error(500); From 4134edf8de26242a89a775ac2d5eb23bea3aa72e Mon Sep 17 00:00:00 2001 From: Eric Cestari Date: Thu, 9 Sep 2010 16:16:28 +0200 Subject: [PATCH 34/85] Merge ApplePush to branch 2.2.x --- src/ejabberd_c2s.erl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ejabberd_c2s.erl b/src/ejabberd_c2s.erl index 17539829d..eda4ea9ae 100644 --- a/src/ejabberd_c2s.erl +++ b/src/ejabberd_c2s.erl @@ -1532,7 +1532,7 @@ change_shaper(StateData, JID) -> (StateData#state.sockmod):change_shaper(StateData#state.socket, Shaper). send_text(StateData, Text) -> - ?DEBUG("Send XML on stream = ~p", [lists:flatten(Text)]), + ?DEBUG("Send XML on stream = ~p", [Text]), Text1 = if ?FLASH_HACK and StateData#state.flash_connection -> %% send a null byte after each stanza to Flash clients From 8ecf8d7e277edd0da283b390431a3d6caa35cd94 Mon Sep 17 00:00:00 2001 From: Eric Cestari Date: Thu, 9 Sep 2010 16:16:46 +0200 Subject: [PATCH 35/85] A few additions to .gitignore --- .gitignore | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.gitignore b/.gitignore index 5b89fb9d5..3e3000059 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,7 @@ Makefile archives +build/ +*.dSYM/ .gitignore contrib/extract_translations/extract_translations.beam doc/contributed_modules.tex @@ -29,3 +31,5 @@ src/eldap/ELDAPv3.beam src/eldap/ELDAPv3.erl src/eldap/ELDAPv3.hrl src/epam +src/ejabberdctl.example +src/ejabberd.init \ No newline at end of file From b8b6fc0da56e0a58920a52b8d0ec4f82e812aec7 Mon Sep 17 00:00:00 2001 From: Eric Cestari Date: Thu, 9 Sep 2010 17:00:18 +0200 Subject: [PATCH 36/85] Merge ApplePush to 2.2.x --- src/ejabberd_c2s.erl | 914 ++++++++++++++++++++++++++++++++-- src/ejabberd_c2s.hrl | 24 +- src/mod_applepush.erl | 381 ++++++++++++++ src/mod_applepush_service.erl | 586 ++++++++++++++++++++++ src/mod_offline.erl | 168 ++----- src/mod_offline_odbc.erl | 174 +++---- src/xml.erl | 26 + src/xml_stream.erl | 3 + 8 files changed, 2020 insertions(+), 256 deletions(-) create mode 100644 src/mod_applepush.erl create mode 100644 src/mod_applepush_service.erl diff --git a/src/ejabberd_c2s.erl b/src/ejabberd_c2s.erl index eda4ea9ae..ce68316e8 100644 --- a/src/ejabberd_c2s.erl +++ b/src/ejabberd_c2s.erl @@ -114,6 +114,15 @@ ?SERRT_POLICY_VIOLATION(Lang, Text)). -define(INVALID_FROM, ?SERR_INVALID_FROM). +-define(NS_P1_REBIND, "p1:rebind"). +-define(NS_P1_PUSH, "p1:push"). +-define(NS_P1_ACK, "p1:ack"). +-define(NS_P1_PUSHED, "p1:pushed"). +-define(NS_P1_ATTACHMENT, "http://process-one.net/attachement"). + +-define(C2S_P1_ACK_TIMEOUT, 10000). +-define(MAX_OOR_TIMEOUT, 1440). %% Max allowed session duration 24h (24*60) +-define(MAX_OOR_MESSAGES, 1000). %%%---------------------------------------------------------------------- %%% API @@ -345,9 +354,22 @@ wait_for_stream({xmlstreamstart, Name, Attrs}, StateData) -> false -> [] end, + P1PushFeature = + [{xmlelement, "push", + [{"xmlns", ?NS_P1_PUSH}], []}], + P1RebindFeature = + [{xmlelement, "rebind", + [{"xmlns", ?NS_P1_REBIND}], []}], + P1AckFeature = + [{xmlelement, "ack", + [{"xmlns", ?NS_P1_ACK}], []}], send_element(StateData, {xmlelement, "stream:features", [], - TLSFeature ++ CompressFeature ++ + TLSFeature ++ + CompressFeature ++ + P1PushFeature ++ + P1RebindFeature ++ + P1AckFeature ++ [{xmlelement, "mechanisms", [{"xmlns", ?NS_SASL}], Mechs}] ++ @@ -368,7 +390,9 @@ wait_for_stream({xmlstreamstart, Name, Attrs}, StateData) -> roster_get_versioning_feature, Server, [], [Server]), StreamFeatures = - [{xmlelement, "bind", + [{xmlelement, "push", + [{"xmlns", ?NS_P1_PUSH}], []}, + {xmlelement, "bind", [{"xmlns", ?NS_BIND}], []}, {xmlelement, "session", [{"xmlns", ?NS_SESSION}], []}] @@ -577,8 +601,33 @@ wait_for_auth({xmlstreamelement, El}, StateData) -> end end; _ -> - process_unauthenticated_stanza(StateData, El), - fsm_next_state(wait_for_auth, StateData) + {xmlelement, Name, Attrs, _Els} = El, + case {xml:get_attr_s("xmlns", Attrs), Name} of + {?NS_P1_REBIND, "rebind"} -> + SJID = xml:get_path_s(El, [{elem, "jid"}, cdata]), + SID = xml:get_path_s(El, [{elem, "sid"}, cdata]), + case jlib:string_to_jid(SJID) of + error -> + send_element(StateData, + {xmlelement, "failure", + [{"xmlns", ?NS_P1_REBIND}], + [{xmlcdata, "Invalid JID"}]}), + fsm_next_state(wait_for_auth, + StateData); + JID -> + case rebind(StateData, JID, SID) of + {next_state, wait_for_feature_request, + NewStateData, Timeout} -> + {next_state, wait_for_auth, + NewStateData, Timeout}; + Res -> + Res + end + end; + _ -> + process_unauthenticated_stanza(StateData, El), + fsm_next_state(wait_for_auth, StateData) + end end; wait_for_auth(timeout, StateData) -> @@ -709,6 +758,23 @@ wait_for_feature_request({xmlstreamelement, El}, StateData) -> StateData) end end; + {?NS_P1_REBIND, "rebind"} -> + SJID = xml:get_path_s(El, [{elem, "jid"}, cdata]), + SID = xml:get_path_s(El, [{elem, "sid"}, cdata]), + case jlib:string_to_jid(SJID) of + error -> + send_element(StateData, + {xmlelement, "failure", + [{"xmlns", ?NS_P1_REBIND}], + [{xmlcdata, "Invalid JID"}]}), + fsm_next_state(wait_for_feature_request, + StateData); + JID -> + rebind(StateData, JID, SID) + end; + {?NS_P1_ACK, "ack"} -> + fsm_next_state(wait_for_feature_request, + StateData#state{ack_enabled = true}); _ -> if (SockMod == gen_tcp) and TLSRequired -> @@ -954,7 +1020,9 @@ session_established({xmlstreamelement, El}, StateData) -> send_trailer(StateData), {stop, normal, StateData}; _NewEl -> - session_established2(El, StateData) + NSD1 = change_reception(StateData, true), + NSD2 = start_keepalive_timer(NSD1), + session_established2(El, NSD2) end; %% We hibernate the process to reduce memory consumption after a @@ -981,7 +1049,16 @@ session_established({xmlstreamerror, _}, StateData) -> {stop, normal, StateData}; session_established(closed, StateData) -> - {stop, normal, StateData}. + if + not StateData#state.reception -> + fsm_next_state(session_established, StateData); + (StateData#state.keepalive_timer /= undefined) -> + NewState1 = change_reception(StateData, false), + NewState = start_keepalive_timer(NewState1), + fsm_next_state(session_established, NewState); + true -> + {stop, normal, StateData} + end. %% Process packets sent by user (coming from user on c2s XMPP %% connection) @@ -1052,6 +1129,8 @@ session_established2(El, StateData) -> [StateData#state.debug, FromJID, ToJID, NewEl]), process_privacy_iq( FromJID, ToJID, IQ, StateData); + #iq{xmlns = ?NS_P1_PUSH} = IQ -> + process_push_iq(FromJID, ToJID, IQ, StateData); _ -> ejabberd_hooks:run( user_send_packet, @@ -1068,6 +1147,12 @@ session_established2(El, StateData) -> check_privacy_route(FromJID, StateData, FromJID, ToJID, NewEl), StateData; + "standby" -> + StandBy = xml:get_tag_cdata(NewEl) == "true", + change_standby(StateData, StandBy); + "a" -> + SCounter = xml:get_tag_attr_s("h", NewEl), + receive_ack(StateData, SCounter); _ -> StateData end @@ -1299,6 +1384,17 @@ handle_info({route, From, To, Packet}, StateName, StateData) -> _ -> {false, Attrs, StateData} end; + rebind -> + {Pid2, StreamID2} = Els, + if + StreamID2 == StateData#state.streamid -> + Pid2 ! {rebind, prepare_acks_for_rebind(StateData)}, + receive after 1000 -> ok end, + {exit, Attrs, rebind}; + true -> + Pid2 ! {rebind, false}, + {false, Attrs, StateData} + end; "iq" -> IQ = jlib:iq_query_info(Packet), case IQ of @@ -1344,18 +1440,22 @@ handle_info({route, From, To, Packet}, StateName, StateData) -> {From, To, Packet}, in]) of allow -> - case ejabberd_hooks:run_fold( - feature_check_packet, StateData#state.server, - allow, - [StateData#state.jid, - StateData#state.server, - StateData#state.pres_last, - {From, To, Packet}, - in]) of - allow -> - {true, Attrs, StateData}; - deny -> - {false, Attrs, StateData} + if StateData#state.reception -> + case ejabberd_hooks:run_fold( + feature_check_packet, StateData#state.server, + allow, + [StateData#state.jid, + StateData#state.server, + StateData#state.pres_last, + {From, To, Packet}, + in]) of + allow -> + {true, Attrs, StateData}; + deny -> + {false, Attrs, StateData} + end; + true -> + {true, Attrs, StateData} end; deny -> {false, Attrs, StateData} @@ -1365,29 +1465,85 @@ handle_info({route, From, To, Packet}, StateName, StateData) -> end, if Pass == exit -> - %% When Pass==exit, NewState contains a string instead of a #state{} - Lang = StateData#state.lang, - send_element(StateData, ?SERRT_CONFLICT(Lang, NewState)), - send_trailer(StateData), - {stop, normal, StateData}; + catch send_trailer(StateData), + case NewState of + rebind -> + {stop, normal, StateData#state{authenticated = rebinded}}; + _ -> + {stop, normal, StateData} + end; Pass -> Attrs2 = jlib:replace_from_to_attrs(jlib:jid_to_string(From), jlib:jid_to_string(To), NewAttrs), FixedPacket = {xmlelement, Name, Attrs2, Els}, - send_element(StateData, FixedPacket), + NewState2 = + if + NewState#state.reception and + not (NewState#state.standby and (Name /= "message")) -> + send_element(NewState, FixedPacket), + ack(NewState, From, To, FixedPacket); + true -> + NewState1 = send_out_of_reception_message( + NewState, From, To, Packet), + enqueue(NewState1, From, To, FixedPacket) + end, ejabberd_hooks:run(user_receive_packet, StateData#state.server, [StateData#state.debug, StateData#state.jid, From, To, FixedPacket]), ejabberd_hooks:run(c2s_loop_debug, [{route, From, To, Packet}]), - fsm_next_state(StateName, NewState); + fsm_next_state(StateName, NewState2); true -> ejabberd_hooks:run(c2s_loop_debug, [{route, From, To, Packet}]), fsm_next_state(StateName, NewState) end; -handle_info({'DOWN', Monitor, _Type, _Object, _Info}, _StateName, StateData) - when Monitor == StateData#state.socket_monitor -> +handle_info({timeout, Timer, _}, StateName, + #state{keepalive_timer = Timer, reception = true} = StateData) -> + NewState1 = change_reception(StateData, false), + NewState = start_keepalive_timer(NewState1), + fsm_next_state(StateName, NewState); +handle_info({timeout, Timer, _}, _StateName, + #state{keepalive_timer = Timer, reception = false} = StateData) -> {stop, normal, StateData}; +handle_info({timeout, Timer, PrevCounter}, StateName, + #state{ack_timer = Timer} = StateData) -> + AckCounter = StateData#state.ack_counter, + NewState = + if + PrevCounter >= AckCounter -> + StateData#state{ack_timer = undefined}; + true -> + send_ack_request(StateData#state{ack_timer = undefined}) + end, + fsm_next_state(StateName, NewState); +handle_info({ack_timeout, Counter}, StateName, StateData) -> + AckQueue = StateData#state.ack_queue, + case queue:is_empty(AckQueue) of + true -> + fsm_next_state(StateName, StateData); + false -> + C = element(1, queue:head(AckQueue)), + if + C =< Counter -> + {stop, normal, StateData}; + true -> + fsm_next_state(StateName, StateData) + end + end; +handle_info({'DOWN', Monitor, _Type, _Object, _Info}, StateName, StateData) + when Monitor == StateData#state.socket_monitor -> + if + (StateName == session_established) and + (not StateData#state.reception) -> + fsm_next_state(StateName, StateData); + (StateName == session_established) and + (StateData#state.keepalive_timer /= undefined) -> + NewState1 = change_reception(StateData, false), + NewState = start_keepalive_timer(NewState1), + fsm_next_state(StateName, NewState); + true -> + {stop, normal, StateData} + end; handle_info(system_shutdown, StateName, StateData) -> case StateName of wait_for_stream -> @@ -1484,6 +1640,13 @@ terminate(_Reason, StateName, StateData) -> StateData, From, StateData#state.pres_a, Packet), presence_broadcast( StateData, From, StateData#state.pres_i, Packet); + rebinded -> + ejabberd_sm:close_session( + StateData#state.sid, + StateData#state.user, + StateData#state.server, + StateData#state.resource), + ok; _ -> ?INFO_MSG("(~w) Close session for ~s", [StateData#state.socket, @@ -1515,6 +1678,36 @@ terminate(_Reason, StateName, StateData) -> StateData, From, StateData#state.pres_i, Packet) end end, + case StateData#state.authenticated of + rebinded -> + ok; + _ -> + if + not StateData#state.reception, not StateData#state.oor_offline -> + SFrom = jlib:jid_to_string(StateData#state.jid), + ejabberd_hooks:run( + p1_push_notification, + StateData#state.server, + [StateData#state.server, + StateData#state.jid, + StateData#state.oor_notification, + "Instant messaging session expired", + 0, + false, + StateData#state.oor_appid, + SFrom]); + true -> + ok + end, + lists:foreach( + fun({_Counter, From, To, FixedPacket}) -> + ejabberd_router:route(From, To, FixedPacket) + end, queue:to_list(StateData#state.ack_queue)), + lists:foreach( + fun({From, To, FixedPacket}) -> + ejabberd_router:route(From, To, FixedPacket) + end, queue:to_list(StateData#state.queue)) + end, bounce_messages(); _ -> ok @@ -1684,9 +1877,39 @@ process_presence_probe(From, To, StateData) -> andalso ?SETS:is_element(LFrom, StateData#state.pres_a), if Cond1 -> + Packet = + case StateData#state.reception of + true -> + StateData#state.pres_last; + false -> + case StateData#state.oor_show of + "" -> + StateData#state.pres_last; + _ -> + {xmlelement, _, PresAttrs, PresEls} = + StateData#state.pres_last, + PresEls1 = + lists:flatmap( + fun({xmlelement, Name, _, _}) + when Name == "show"; + Name == "status" -> + []; + (E) -> + [E] + end, PresEls), + {xmlelement, "presence", PresAttrs, + [{xmlelement, "show", [], + [{xmlcdata, + StateData#state.oor_show}]}, + {xmlelement, "status", [], + [{xmlcdata, + StateData#state.oor_status}]}] + ++ PresEls1} + end + end, Timestamp = StateData#state.pres_timestamp, - Packet = xml:append_subtags( - StateData#state.pres_last, + Packet1 = xml:append_subtags( + Packet, %% To is the one sending the presence (the target of the probe) [jlib:timestamp_to_xml(Timestamp, utc, To, ""), %% TODO: Delete the next line once XEP-0091 is Obsolete @@ -1697,7 +1920,7 @@ process_presence_probe(From, To, StateData) -> [StateData#state.user, StateData#state.server, StateData#state.privacy_list, - {To, From, Packet}, + {To, From, Packet1}, out]) of deny -> ok; @@ -1707,7 +1930,7 @@ process_presence_probe(From, To, StateData) -> %% Don't route a presence probe to oneself case From == To of false -> - ejabberd_router:route(To, From, Packet); + ejabberd_router:route(To, From, Packet1); true -> ok end @@ -2035,8 +2258,8 @@ roster_change(IJID, ISubscription, StateData) -> P -> ?DEBUG("roster changed for ~p~n", [StateData#state.user]), From = StateData#state.jid, -% To = jlib:make_jid(IJID) - To = IJID, + To = jlib:make_jid(IJID), +% To = IJID, Cond1 = (not StateData#state.pres_invis) and IsFrom and (not OldIsFrom), Cond2 = (not IsFrom) and OldIsFrom @@ -2333,6 +2556,631 @@ check_from(El, FromJID) -> end end. +start_keepalive_timer(StateData) -> + if + is_reference(StateData#state.keepalive_timer) -> + cancel_timer(StateData#state.keepalive_timer); + true -> + ok + end, + Timeout = + if + StateData#state.reception -> StateData#state.keepalive_timeout; + true -> StateData#state.oor_timeout + end, + Timer = + if + is_integer(Timeout) -> + erlang:start_timer(Timeout * 1000, self(), []); + true -> + undefined + end, + StateData#state{keepalive_timer = Timer}. + +change_reception(#state{reception = Reception} = StateData, Reception) -> + StateData; +change_reception(#state{reception = true} = StateData, false) -> + ?DEBUG("reception -> false", []), + case StateData#state.oor_show of + "" -> + ok; + _ -> + Packet = + {xmlelement, "presence", [], + [{xmlelement, "show", [], + [{xmlcdata, StateData#state.oor_show}]}, + {xmlelement, "status", [], + [{xmlcdata, StateData#state.oor_status}]}]}, + update_priority(0, Packet, StateData), + presence_broadcast_to_trusted( + StateData, + StateData#state.jid, + StateData#state.pres_f, + StateData#state.pres_a, + Packet) + end, + StateData#state{reception = false}; +change_reception(#state{reception = false, standby = true} = StateData, true) -> + ?DEBUG("reception -> standby", []), + NewQueue = + lists:foldl( + fun({_From, _To, {xmlelement, "message", _, _} = FixedPacket}, Q) -> + send_element(StateData, FixedPacket), + Q; + (Item, Q) -> + queue:in(Item, Q) + end, queue:new(), queue:to_list(StateData#state.queue)), + StateData#state{queue = NewQueue, + queue_len = queue:len(NewQueue), + reception = true, + oor_unread = 0, + oor_unread_users = ?SETS:new()}; +change_reception(#state{reception = false} = StateData, true) -> + ?DEBUG("reception -> true", []), + case StateData#state.oor_show of + "" -> + ok; + _ -> + Packet = StateData#state.pres_last, + NewPriority = get_priority_from_presence(Packet), + update_priority(NewPriority, Packet, StateData), + presence_broadcast_to_trusted( + StateData, + StateData#state.jid, + StateData#state.pres_f, + StateData#state.pres_a, + Packet) + end, + lists:foreach( + fun({_From, _To, FixedPacket}) -> + send_element(StateData, FixedPacket) + end, queue:to_list(StateData#state.queue)), + lists:foreach( + fun(FixedPacket) -> + send_element(StateData, FixedPacket) + end, gb_trees:values(StateData#state.pres_queue)), + StateData#state{queue = queue:new(), + queue_len = 0, + pres_queue = gb_trees:empty(), + reception = true, + oor_unread = 0, + oor_unread_users = ?SETS:new()}. + +change_standby(#state{standby = StandBy} = StateData, StandBy) -> + StateData; +change_standby(#state{standby = false} = StateData, true) -> + ?DEBUG("standby -> true", []), + StateData#state{standby = true}; +change_standby(#state{standby = true} = StateData, false) -> + ?DEBUG("standby -> false", []), + lists:foreach( + fun({_From, _To, FixedPacket}) -> + send_element(StateData, FixedPacket) + end, queue:to_list(StateData#state.queue)), + lists:foreach( + fun(FixedPacket) -> + send_element(StateData, FixedPacket) + end, gb_trees:values(StateData#state.pres_queue)), + StateData#state{queue = queue:new(), + queue_len = 0, + pres_queue = gb_trees:empty(), + standby = false}. + +send_out_of_reception_message(StateData, From, To, + {xmlelement, "message", _, _} = Packet) -> + Type = xml:get_tag_attr_s("type", Packet), + if + (Type == "normal") or + (Type == "") or + (Type == "chat") or + (StateData#state.oor_send_groupchat and (Type == "groupchat"))-> + %Lang = case xml:get_tag_attr_s("xml:lang", Packet) of + % "" -> + % StateData#state.lang; + % L -> + % L + % end, + %Text = translate:translate( + % Lang, "User is temporarily out of reception"), + %MsgType = "error", + %Message = {xmlelement, "message", + % [{"type", MsgType}], + % [{xmlelement, "body", [], + % [{xmlcdata, Text}]}]}, + %ejabberd_router:route(To, From, Message), + Body1 = xml:get_path_s(Packet, [{elem, "body"}, cdata]), + Body = + case check_x_attachment(Packet) of + true -> + case Body1 of + "" -> [238, 128, 136]; + _ -> + [238, 128, 136, 32 | Body1] + end; + false -> + Body1 + end, + Pushed = check_x_pushed(Packet), + if + Body == ""; + Pushed -> + StateData; + true -> + BFrom = jlib:jid_remove_resource(From), + LBFrom = jlib:jid_tolower(BFrom), + UnreadUsers = ?SETS:add_element( + LBFrom, + StateData#state.oor_unread_users), + IncludeBody = + case StateData#state.oor_send_body of + all -> + true; + first_per_user -> + not ?SETS:is_element( + LBFrom, + StateData#state.oor_unread_users); + first -> + StateData#state.oor_unread == 0; + none -> + false + end, + Unread = StateData#state.oor_unread + 1, + SFrom = jlib:jid_to_string(BFrom), + Msg = + if + IncludeBody -> + CBody = utf8_cut(Body, 100), + case StateData#state.oor_send_from of + jid -> SFrom ++ ": " ++ CBody; + username -> BFrom#jid.user ++ ": " ++ CBody; + _ -> CBody + end; + true -> + "" + end, + Sound = IncludeBody, + AppID = StateData#state.oor_appid, + ejabberd_hooks:run( + p1_push_notification, + StateData#state.server, + [StateData#state.server, + StateData#state.jid, + StateData#state.oor_notification, + Msg, + Unread, + Sound, + AppID, + SFrom]), + %% This hook is intended to give other module a + %% chance to notify the sender that the message is + %% not directly delivered to the client (almost + %% equivalent to offline). + ejabberd_hooks:run(delayed_message_hook, + StateData#state.server, + [From, To, Packet]), + StateData#state{oor_unread = Unread, + oor_unread_users = UnreadUsers} + end; + true -> + StateData + end; +send_out_of_reception_message(StateData, _From, _To, _Packet) -> + StateData. + +utf8_cut(S, Bytes) -> + utf8_cut(S, [], [], Bytes + 1). + +utf8_cut(_S, _Cur, Prev, 0) -> + lists:reverse(Prev); +utf8_cut([], Cur, _Prev, _Bytes) -> + lists:reverse(Cur); +utf8_cut([C | S], Cur, Prev, Bytes) -> + if + C bsr 6 == 2 -> + utf8_cut(S, [C | Cur], Prev, Bytes - 1); + true -> + utf8_cut(S, [C | Cur], Cur, Bytes - 1) + end. + + +cancel_timer(Timer) -> + erlang:cancel_timer(Timer), + receive + {timeout, Timer, _} -> + ok + after 0 -> + ok + end. + +enqueue(StateData, From, To, Packet) -> + IsPresence = + case Packet of + {xmlelement, "presence", _, _} -> + case xml:get_tag_attr_s("type", Packet) of + "subscribe" -> + false; + "subscribed" -> + false; + "unsubscribe" -> + false; + "unsubscribed" -> + false; + _ -> + true + end; + _ -> + false + end, + Messages = + StateData#state.queue_len + gb_trees:size(StateData#state.pres_queue), + if + Messages >= ?MAX_OOR_MESSAGES -> + self() ! {timeout, StateData#state.keepalive_timer, []}; + true -> + ok + end, + if + IsPresence -> + LFrom = jlib:jid_tolower(From), + case is_own_presence(StateData#state.jid, LFrom) of + true -> StateData; + false -> + NewQueue = gb_trees:enter(LFrom, Packet, + StateData#state.pres_queue), + StateData#state{pres_queue = NewQueue} + end; + true -> + CleanPacket = xml:remove_subtags(Packet, "x", {"xmlns", ?NS_P1_PUSHED}), + Packet2 = + case CleanPacket of + {xmlelement, "message" = Name, Attrs, Els} -> + {xmlelement, Name, Attrs, + Els ++ + [jlib:timestamp_to_xml( + calendar:now_to_universal_time(now())), + {xmlelement, "x", [{"xmlns", ?NS_P1_PUSHED}], []}]}; + _ -> + Packet + end, + NewQueue = queue:in({From, To, Packet2}, + StateData#state.queue), + NewQueueLen = StateData#state.queue_len + 1, + StateData#state{queue = NewQueue, + queue_len = NewQueueLen} + end. + +%% Is my own presence packet ? +is_own_presence(MyFullJID, MyFullJID) -> + true; +is_own_presence(_MyFullJID, _LFrom) -> + false. + +ack(StateData, From, To, Packet) -> + if + StateData#state.ack_enabled -> + NeedsAck = + case Packet of + {xmlelement, "presence", _, _} -> + case xml:get_tag_attr_s("type", Packet) of + "subscribe" -> + true; + "subscribed" -> + true; + "unsubscribe" -> + true; + "unsubscribed" -> + true; + _ -> + false + end; + {xmlelement, "message", _, _} -> + true; + _ -> + false + end, + if + NeedsAck -> + Counter = StateData#state.ack_counter + 1, + NewAckQueue = queue:in({Counter, From, To, Packet}, + StateData#state.ack_queue), + send_ack_request(StateData#state{ack_queue = NewAckQueue, + ack_counter = Counter}); + true -> + StateData + end; + true -> + StateData + end. + +send_ack_request(StateData) -> + case StateData#state.ack_timer of + undefined -> + AckCounter = StateData#state.ack_counter, + AckTimer = + erlang:start_timer(?C2S_P1_ACK_TIMEOUT, self(), AckCounter), + AckTimeout = StateData#state.keepalive_timeout + + StateData#state.oor_timeout, + erlang:send_after(AckTimeout * 1000, self(), + {ack_timeout, AckTimeout}), + send_element( + StateData, + {xmlelement, "r", + [{"h", integer_to_list(AckCounter)}], []}), + StateData#state{ack_timer = AckTimer}; + _ -> + StateData + end. + +receive_ack(StateData, SCounter) -> + case catch list_to_integer(SCounter) of + Counter when is_integer(Counter) -> + NewQueue = clean_queue(StateData#state.ack_queue, Counter), + StateData#state{ack_queue = NewQueue}; + _ -> + StateData + end. + +clean_queue(Queue, Counter) -> + case queue:is_empty(Queue) of + true -> + Queue; + false -> + C = element(1, queue:head(Queue)), + if + C =< Counter -> + clean_queue(queue:tail(Queue), Counter); + true -> + Queue + end + end. + +prepare_acks_for_rebind(StateData) -> + AckQueue = StateData#state.ack_queue, + case queue:is_empty(AckQueue) of + true -> + StateData; + false -> + Unsent = + lists:map( + fun({_Counter, From, To, FixedPacket}) -> + {From, To, FixedPacket} + end, queue:to_list(AckQueue)), + NewQueue = queue:join(queue:from_list(Unsent), + StateData#state.queue), + StateData#state{queue = NewQueue, + queue_len = queue:len(NewQueue), + ack_queue = queue:new(), + reception = false} + end. + + +rebind(StateData, JID, StreamID) -> + case JID#jid.lresource of + "" -> + send_element(StateData, + {xmlelement, "failure", + [{"xmlns", ?NS_P1_REBIND}], + [{xmlcdata, "Invalid JID"}]}), + fsm_next_state(wait_for_feature_request, + StateData); + _ -> + ejabberd_sm:route( + ?MODULE, JID, + {xmlelement, rebind, [], {self(), StreamID}}), + receive + {rebind, false} -> + send_element(StateData, + {xmlelement, "failure", + [{"xmlns", ?NS_P1_REBIND}], + [{xmlcdata, "Session not found"}]}), + fsm_next_state(wait_for_feature_request, + StateData); + {rebind, NewStateData} -> + ?INFO_MSG("(~w) Reopened session for ~s", + [StateData#state.socket, + jlib:jid_to_string(JID)]), + SID = {now(), self()}, + Conn = get_conn_type(NewStateData), + Info = [{ip, StateData#state.ip}, {conn, Conn}, + {auth_module, NewStateData#state.auth_module}], + ejabberd_sm:open_session( + SID, + NewStateData#state.user, + NewStateData#state.server, + NewStateData#state.resource, + Info), + StateData2 = + NewStateData#state{ + socket = StateData#state.socket, + sockmod = StateData#state.sockmod, + socket_monitor = StateData#state.socket_monitor, + sid = SID, + ip = StateData#state.ip, + keepalive_timer = StateData#state.keepalive_timer, + ack_timer = undefined + }, + Presence = StateData2#state.pres_last, + case Presence of + undefined -> + ok; + _ -> + NewPriority = get_priority_from_presence(Presence), + update_priority(NewPriority, Presence, StateData2) + end, + send_element(StateData2, + {xmlelement, "rebind", + [{"xmlns", ?NS_P1_REBIND}], + []}), + StateData3 = change_reception(StateData2, true), + StateData4 = start_keepalive_timer(StateData3), + fsm_next_state(session_established, + StateData4) + after 1000 -> + send_element(StateData, + {xmlelement, "failure", + [{"xmlns", ?NS_P1_REBIND}], + [{xmlcdata, "Session not found"}]}), + fsm_next_state(wait_for_feature_request, + StateData) + end + end. + +process_push_iq(From, To, + #iq{type = _Type, sub_el = El} = IQ, + StateData) -> + {Res, NewStateData} = + case El of + {xmlelement, "push", _, _} -> + SKeepAlive = + xml:get_path_s(El, [{elem, "keepalive"}, {attr, "max"}]), + SOORTimeout = + xml:get_path_s(El, [{elem, "session"}, {attr, "duration"}]), + Status = xml:get_path_s(El, [{elem, "status"}, cdata]), + Show = xml:get_path_s(El, [{elem, "status"}, {attr, "type"}]), + SSendBody = xml:get_path_s(El, [{elem, "body"}, {attr, "send"}]), + SendBody = + case SSendBody of + "all" -> all; + "first-per-user" -> first_per_user; + "first" -> first; + "none" -> none; + _ -> none + end, + SendGroupchat = + xml:get_path_s(El, [{elem, "body"}, + {attr, "groupchat"}]) == "true", + SendFrom = send_from(El), + AppID = xml:get_path_s(El, [{elem, "appid"}, cdata]), + {Offline, Keep} = + case xml:get_path_s(El, [{elem, "offline"}, cdata]) of + "true" -> {true, false}; + "keep" -> {false, true}; + _ -> {false, false} + end, + Notification1 = xml:get_path_s(El, [{elem, "notification"}]), + Notification = + case Notification1 of + {xmlelement, _, _, _} -> + Notification1; + _ -> + {xmlelement, "notification", [], + [{xmlelement, "type", [], + [{xmlcdata, "none"}]}]} + end, + case catch {list_to_integer(SKeepAlive), + list_to_integer(SOORTimeout)} of + {KeepAlive, OORTimeout} + when OORTimeout =< ?MAX_OOR_TIMEOUT -> + if + Offline -> + ejabberd_hooks:run( + p1_push_enable_offline, + StateData#state.server, + [StateData#state.jid, + Notification, SendBody, SendFrom, AppID]); + Keep -> + ok; + true -> + ejabberd_hooks:run( + p1_push_disable, + StateData#state.server, + [StateData#state.jid, + Notification, + AppID]) + end, + NSD1 = + StateData#state{keepalive_timeout = KeepAlive, + oor_timeout = OORTimeout * 60, + oor_status = Status, + oor_show = Show, + oor_notification = Notification, + oor_send_body = SendBody, + oor_send_groupchat = SendGroupchat, + oor_send_from = SendFrom, + oor_appid = AppID, + oor_offline = Offline}, + NSD2 = start_keepalive_timer(NSD1), + {{result, []}, NSD2}; + _ -> + {{error, ?ERR_BAD_REQUEST}, StateData} + end; + {xmlelement, "disable", _, _} -> + ejabberd_hooks:run( + p1_push_disable, + StateData#state.server, + [StateData#state.jid, + StateData#state.oor_notification, + StateData#state.oor_appid]), + NSD1 = + StateData#state{keepalive_timeout = undefined, + oor_timeout = undefined, + oor_status = "", + oor_show = "", + oor_notification = undefined, + oor_send_body = all}, + NSD2 = start_keepalive_timer(NSD1), + {{result, []}, NSD2}; + _ -> + {{error, ?ERR_BAD_REQUEST}, StateData} + end, + IQRes = + case Res of + {result, Result} -> + IQ#iq{type = result, sub_el = Result}; + {error, Error} -> + IQ#iq{type = error, sub_el = [El, Error]} + end, + ejabberd_router:route( + To, From, jlib:iq_to_xml(IQRes)), + NewStateData. + +check_x_pushed({xmlelement, _Name, _Attrs, Els}) -> + check_x_pushed1(Els). + +check_x_pushed1([]) -> + false; +check_x_pushed1([{xmlcdata, _} | Els]) -> + check_x_pushed1(Els); +check_x_pushed1([El | Els]) -> + case xml:get_tag_attr_s("xmlns", El) of + ?NS_P1_PUSHED -> + true; + _ -> + check_x_pushed1(Els) + end. + +check_x_attachment({xmlelement, _Name, _Attrs, Els}) -> + check_x_attachment1(Els). + +check_x_attachment1([]) -> + false; +check_x_attachment1([{xmlcdata, _} | Els]) -> + check_x_attachment1(Els); +check_x_attachment1([El | Els]) -> + case xml:get_tag_attr_s("xmlns", El) of + ?NS_P1_ATTACHMENT -> + true; + _ -> + check_x_attachment1(Els) + end. + + +send_from(El) -> + %% First test previous version attribute: + case xml:get_path_s(El, [{elem, "body"}, {attr, "jid"}]) of + "false" -> + none; + "true" -> + jid; + "" -> + case xml:get_path_s(El, [{elem, "body"}, {attr, "from"}]) of + "jid" -> jid; + "username" -> username; + "none" -> none; + _ -> jid + end + end. + fsm_limit_opts(Opts) -> case lists:keysearch(max_fsm_queue, 1, Opts) of {value, {_, N}} when is_integer(N) -> diff --git a/src/ejabberd_c2s.hrl b/src/ejabberd_c2s.hrl index e2e3c2439..381e042ba 100644 --- a/src/ejabberd_c2s.hrl +++ b/src/ejabberd_c2s.hrl @@ -60,4 +60,26 @@ fsm_limit_opts, lang, debug=false, - flash_connection = false}). \ No newline at end of file + flash_connection = false, + reception = true, + standby = false, + queue = queue:new(), + queue_len = 0, + pres_queue = gb_trees:empty(), + keepalive_timer, + keepalive_timeout, + oor_timeout, + oor_status = "", + oor_show = "", + oor_notification, + oor_send_body = all, + oor_send_groupchat = false, + oor_send_from = jid, + oor_appid = "", + oor_unread = 0, + oor_unread_users = ?SETS:new(), + oor_offline = false, + ack_enabled = false, + ack_counter = 0, + ack_queue = queue:new(), + ack_timer}). \ No newline at end of file diff --git a/src/mod_applepush.erl b/src/mod_applepush.erl new file mode 100644 index 000000000..b8659615c --- /dev/null +++ b/src/mod_applepush.erl @@ -0,0 +1,381 @@ +%%%---------------------------------------------------------------------- +%%% File : mod_applepush.erl +%%% Author : Alexey Shchepin +%%% Purpose : Push module support +%%% Created : 5 Jun 2009 by Alexey Shchepin +%%% +%%% ejabberd, Copyright (C) 2002-2009 ProcessOne +%%%---------------------------------------------------------------------- + +-module(mod_applepush). +-author('alexey@process-one.net'). + +-behaviour(gen_mod). + +-export([start/2, + stop/1, + push_notification/8, + enable_offline_notification/5, + disable_notification/3, + receive_offline_packet/3]). + +%% Debug commands +-export([get_token_by_jid/1]). + + +-include("ejabberd.hrl"). +-include("jlib.hrl"). +-include("mod_privacy.hrl"). + +-define(NS_P1_PUSH, "p1:push"). +-define(NS_P1_PUSHED, "p1:pushed"). +-define(NS_P1_ATTACHMENT, "http://process-one.net/attachement"). + +-record(applepush_cache, {us, device_id, options}). + +start(Host, _Opts) -> + case init_host(Host) of + true -> + mnesia:create_table( + applepush_cache, + [{disc_copies, [node()]}, + {attributes, record_info(fields, applepush_cache)}]), + mnesia:add_table_copy(muc_online_room, node(), ram_copies), + ejabberd_hooks:add(p1_push_notification, Host, + ?MODULE, push_notification, 50), + ejabberd_hooks:add(p1_push_enable_offline, Host, + ?MODULE, enable_offline_notification, 50), + ejabberd_hooks:add(p1_push_disable, Host, + ?MODULE, disable_notification, 50), + ejabberd_hooks:add(offline_message_hook, Host, + ?MODULE, receive_offline_packet, 35); + false -> + ok + end. + +stop(Host) -> + ejabberd_hooks:delete(p1_push_notification, Host, + ?MODULE, push_notification, 50), + ejabberd_hooks:delete(p1_push_disable, Host, + ?MODULE, disable_notification, 50), + ejabberd_hooks:delete(offline_message_hook, Host, + ?MODULE, receive_offline_packet, 35). + + +push_notification(Host, JID, Notification, Msg, Unread, Sound, AppID, Sender) -> + Type = xml:get_path_s(Notification, [{elem, "type"}, cdata]), + case Type of + "applepush" -> + DeviceID = xml:get_path_s(Notification, [{elem, "id"}, cdata]), + PushService = get_push_service(Host, JID, AppID), + ServiceJID = jlib:make_jid("", PushService, ""), + Badge = integer_to_list(Unread), + SSound = + if + Sound -> "true"; + true -> "false" + end, + Receiver = jlib:jid_to_string(JID), + Packet = + {xmlelement, "message", [], + [{xmlelement, "push", [{"xmlns", ?NS_P1_PUSH}], + [{xmlelement, "id", [], [{xmlcdata, DeviceID}]}, + {xmlelement, "msg", [], [{xmlcdata, Msg}]}, + {xmlelement, "badge", [], [{xmlcdata, Badge}]}, + {xmlelement, "sound", [], [{xmlcdata, SSound}]}, + {xmlelement, "from", [], [{xmlcdata, Sender}]}, + {xmlelement, "to", [], [{xmlcdata, Receiver}]}]}]}, + ejabberd_router:route(JID, ServiceJID, Packet), + stop; + _ -> + ok + end. + +enable_offline_notification(JID, Notification, SendBody, SendFrom, AppID1) -> + Type = xml:get_path_s(Notification, [{elem, "type"}, cdata]), + case Type of + "applepush" -> + DeviceID = xml:get_path_s(Notification, [{elem, "id"}, cdata]), + case catch erlang:list_to_integer(DeviceID, 16) of + ID1 when is_integer(ID1) -> + AppID = + case xml:get_path_s(Notification, + [{elem, "appid"}, cdata]) of + "" -> AppID1; + A -> A + end, + {MegaSecs, Secs, _MicroSecs} = now(), + TimeStamp = MegaSecs * 1000000 + Secs, + Options = + [{appid, AppID}, + {send_body, SendBody}, + {send_from, SendFrom}, + {timestamp, TimeStamp}], + store_cache(JID, ID1, Options); + _ -> + ok + end, + stop; + _ -> + ok + end. + +disable_notification(JID, Notification, _AppID) -> + Type = xml:get_path_s(Notification, [{elem, "type"}, cdata]), + case Type of + "applepush" -> + delete_cache(JID), + stop; + _ -> + ok + end. + +receive_offline_packet(From, To, Packet) -> + ?DEBUG("mod_applepush offline~n\tfrom ~p~n\tto ~p~n\tpacket ~P~n", + [From, To, Packet, 8]), + Host = To#jid.lserver, + case gen_mod:is_loaded(Host, mod_applepush) of + true -> + case lookup_cache(To) of + false -> + ok; + {ID, AppID, SendBody, SendFrom} -> + ?DEBUG("lookup: ~p~n", [{ID, AppID, SendBody, SendFrom}]), + Body1 = xml:get_path_s(Packet, [{elem, "body"}, cdata]), + Body = + case check_x_attachment(Packet) of + true -> + case Body1 of + "" -> [238, 128, 136]; + _ -> + [238, 128, 136, 32 | Body1] + end; + false -> + Body1 + end, + Pushed = check_x_pushed(Packet), + PushService = get_push_service(Host, To, AppID), + ServiceJID = jlib:make_jid("", PushService, ""), + if + Body == ""; + Pushed -> + if + From#jid.lserver == ServiceJID#jid.lserver -> + Disable = + xml:get_path_s( + Packet, [{elem, "disable"}]) /= "", + if + Disable -> + delete_cache(To); + true -> + ok + end; + true -> + ok + end, + ok; + true -> + BFrom = jlib:jid_remove_resource(From), + SFrom = jlib:jid_to_string(BFrom), + Offline = ejabberd_hooks:run_fold( + count_offline_messages, + Host, + 0, + [To#jid.luser, Host]), + IncludeBody = + case SendBody of + all -> + true; + first_per_user -> + Offline == 0; + first -> + Offline == 0; + none -> + false + end, + Msg = + if + IncludeBody -> + CBody = utf8_cut(Body, 100), + case SendFrom of + jid -> SFrom ++ ": " ++ CBody; + username -> BFrom#jid.user ++ ": " ++ CBody; + _ -> CBody + end; + true -> + "" + end, + SSound = + if + IncludeBody -> "true"; + true -> "false" + end, + Badge = integer_to_list(Offline + 1), + DeviceID = erlang:integer_to_list(ID, 16), + Packet1 = + {xmlelement, "message", [], + [{xmlelement, "push", [{"xmlns", ?NS_P1_PUSH}], + [{xmlelement, "id", [], + [{xmlcdata, DeviceID}]}, + {xmlelement, "msg", [], + [{xmlcdata, Msg}]}, + {xmlelement, "badge", [], + [{xmlcdata, Badge}]}, + {xmlelement, "sound", [], + [{xmlcdata, SSound}]}, + {xmlelement, "from", [], + [{xmlcdata, SFrom}]}]}]}, + ejabberd_router:route(To, ServiceJID, Packet1) + end + end; + false -> + ok + end. + +lookup_cache(JID) -> + #jid{luser = LUser, lserver = LServer} = JID, + LUS = {LUser, LServer}, + case catch mnesia:dirty_read(applepush_cache, LUS) of + [#applepush_cache{device_id = DeviceID, options = Options}] -> + AppID = proplists:get_value(appid, Options, "applepush.localhost"), + SendBody = proplists:get_value(send_body, Options, none), + SendFrom = proplists:get_value(send_from, Options, true), + {DeviceID, AppID, SendBody, SendFrom}; + _ -> + false + end. + +store_cache(JID, DeviceID, Options) -> + #jid{luser = LUser, lserver = LServer} = JID, + LUS = {LUser, LServer}, + R = #applepush_cache{us = LUS, + device_id = DeviceID, + options = Options}, + case catch mnesia:dirty_read(applepush_cache, LUS) of + [R] -> + ok; + _ -> + catch mnesia:dirty_write(R) + end. + +delete_cache(JID) -> + #jid{luser = LUser, lserver = LServer} = JID, + LUS = {LUser, LServer}, + catch mnesia:dirty_delete(applepush_cache, LUS). + + +utf8_cut(S, Bytes) -> + utf8_cut(S, [], [], Bytes + 1). + +utf8_cut(_S, _Cur, Prev, 0) -> + lists:reverse(Prev); +utf8_cut([], Cur, _Prev, _Bytes) -> + lists:reverse(Cur); +utf8_cut([C | S], Cur, Prev, Bytes) -> + if + C bsr 6 == 2 -> + utf8_cut(S, [C | Cur], Prev, Bytes - 1); + true -> + utf8_cut(S, [C | Cur], Cur, Bytes - 1) + end. + +check_x_pushed({xmlelement, _Name, _Attrs, Els}) -> + check_x_pushed1(Els). + +check_x_pushed1([]) -> + false; +check_x_pushed1([{xmlcdata, _} | Els]) -> + check_x_pushed1(Els); +check_x_pushed1([El | Els]) -> + case xml:get_tag_attr_s("xmlns", El) of + ?NS_P1_PUSHED -> + true; + _ -> + check_x_pushed1(Els) + end. + +check_x_attachment({xmlelement, _Name, _Attrs, Els}) -> + check_x_attachment1(Els). + +check_x_attachment1([]) -> + false; +check_x_attachment1([{xmlcdata, _} | Els]) -> + check_x_attachment1(Els); +check_x_attachment1([El | Els]) -> + case xml:get_tag_attr_s("xmlns", El) of + ?NS_P1_ATTACHMENT -> + true; + _ -> + check_x_attachment1(Els) + end. + + +get_push_service(Host, JID, AppID) -> + PushServices = + gen_mod:get_module_opt( + Host, ?MODULE, + push_services, []), + PushService = + case lists:keysearch(AppID, 1, PushServices) of + false -> + DefaultServices = + gen_mod:get_module_opt( + Host, ?MODULE, + default_services, []), + case lists:keysearch(JID#jid.lserver, 1, DefaultServices) of + false -> + gen_mod:get_module_opt( + Host, ?MODULE, + default_service, "applepush.localhost"); + {value, {_, PS}} -> + PS + end; + {value, {AppID, PS}} -> + PS + end, + PushService. + + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% Internal module protection + +-define(VALID_HOSTS, []). % default is unlimited use +-define(MAX_USERS, 0). % default is unlimited use + +init_host(VHost) -> + case ?VALID_HOSTS of + [] -> % unlimited use + true; + ValidList -> % limited use + init_host(VHost, ValidList) + end. +init_host([], _) -> + false; +init_host(VHost, ValidEncryptedList) -> + EncryptedHost = erlang:md5(lists:reverse(VHost)), + case lists:member(EncryptedHost, ValidEncryptedList) of + true -> + case ?MAX_USERS of + 0 -> true; + N -> ejabberd_auth:get_vh_registered_users_number(VHost) =< N + end; + false -> + case string:chr(VHost, $.) of + 0 -> false; + Pos -> init_host(string:substr(VHost, Pos+1), ValidEncryptedList) + end + end. + +%% Debug commands +%% JID is of form +get_token_by_jid(JIDString) -> + #jid{luser = LUser, lserver = LServer} = jlib:string_to_jid(JIDString), + LUS = {LUser, LServer}, + case mnesia:dirty_read(applepush_cache, LUS) of + [{applepush_cache,_,I,_}] -> + erlang:integer_to_list(I, 16); + _ -> + undefined + end. + diff --git a/src/mod_applepush_service.erl b/src/mod_applepush_service.erl new file mode 100644 index 000000000..5469550eb --- /dev/null +++ b/src/mod_applepush_service.erl @@ -0,0 +1,586 @@ +%%%---------------------------------------------------------------------- +%%% File : mod_applepush_service.erl +%%% Author : Alexey Shchepin +%%% Purpose : Central push infrastructure +%%% Created : 5 Jun 2009 by Alexey Shchepin +%%% +%%% ejabberd, Copyright (C) 2002-2009 ProcessOne +%%%---------------------------------------------------------------------- + +-module(mod_applepush_service). +-author('alexey@process-one.net'). + +-behaviour(gen_server). +-behaviour(gen_mod). + +%% API +-export([start_link/2, start/2, stop/1]). + +%% gen_server callbacks +-export([init/1, handle_call/3, handle_cast/2, handle_info/2, + terminate/2, code_change/3]). + +-include("ejabberd.hrl"). +-include("jlib.hrl"). + +-record(state, {host, + socket, + gateway, + port, + feedback_socket, + feedback, + feedback_port, + feedback_buf = <<>>, + certfile, + queue, + soundfile, + cmd_id = 0, + cmd_cache = dict:new(), + device_cache = dict:new()}). + +-define(PROCNAME, ejabberd_mod_applepush_service). +-define(RECONNECT_TIMEOUT, 5000). +-define(FEEDBACK_RECONNECT_TIMEOUT, 30000). +-define(MAX_QUEUE_SIZE, 1000). +-define(CACHE_SIZE, 4096). +-define(MAX_PAYLOAD_SIZE, 255). + +-define(NS_P1_PUSH, "p1:push"). + +%%==================================================================== +%% API +%%==================================================================== +%%-------------------------------------------------------------------- +%% Function: start_link() -> {ok,Pid} | ignore | {error,Error} +%% Description: Starts the server +%%-------------------------------------------------------------------- +start_link(Host, Opts) -> + Proc = gen_mod:get_module_proc(Host, ?PROCNAME), + gen_server:start_link({local, Proc}, ?MODULE, [Host, Opts], []). + +start(Host, Opts) -> + ssl:start(), + MyHosts = + case catch gen_mod:get_opt(hosts, Opts) of + {'EXIT', _} -> + [{gen_mod:get_opt_host(Host, Opts, "applepush.@HOST@"), Opts}]; + Hs -> + Hs + end, + lists:foreach( + fun({MyHost, MyOpts}) -> + Proc = gen_mod:get_module_proc(MyHost, ?PROCNAME), + ChildSpec = + {Proc, + {?MODULE, start_link, [MyHost, MyOpts]}, + transient, + 1000, + worker, + [?MODULE]}, + supervisor:start_child(ejabberd_sup, ChildSpec) + end, MyHosts). + +stop(Host) -> + MyHosts = + case catch gen_mod:get_module_opt(Host, ?MODULE, hosts, []) of + [] -> + [gen_mod:get_module_opt_host( + Host, ?MODULE, "applepush.@HOST@")]; + Hs -> + [H || {H, _} <- Hs] + end, + lists:foreach( + fun(MyHost) -> + Proc = gen_mod:get_module_proc(MyHost, ?PROCNAME), + gen_server:call(Proc, stop), + supervisor:terminate_child(ejabberd_sup, Proc), + supervisor:delete_child(ejabberd_sup, Proc) + end, MyHosts). + + +%%==================================================================== +%% gen_server callbacks +%%==================================================================== + +%%-------------------------------------------------------------------- +%% Function: init(Args) -> {ok, State} | +%% {ok, State, Timeout} | +%% ignore | +%% {stop, Reason} +%% Description: Initiates the server +%%-------------------------------------------------------------------- +init([MyHost, Opts]) -> + CertFile = gen_mod:get_opt(certfile, Opts, ""), + SoundFile = gen_mod:get_opt(sound_file, Opts, "pushalert.wav"), + Gateway = gen_mod:get_opt(gateway, Opts, "gateway.push.apple.com"), + Feedback = gen_mod:get_opt(feedback, Opts, undefined), + Port = gen_mod:get_opt(port, Opts, 2195), + FeedbackPort = gen_mod:get_opt(feedback_port, Opts, 2196), + %MyHost = gen_mod:get_opt_host(Host, Opts, "applepush.@HOST@"), + self() ! connect, + case Feedback of + undefined -> + ok; + _ -> + self() ! connect_feedback + end, + ejabberd_router:register_route(MyHost), + {ok, #state{host = MyHost, + gateway = Gateway, + port = Port, + feedback = Feedback, + feedback_port = FeedbackPort, + certfile = CertFile, + queue = {0, queue:new()}, + soundfile = SoundFile}}. + +%%-------------------------------------------------------------------- +%% 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, From, To, Packet}, State) -> + case catch do_route(From, To, Packet, State) of + {'EXIT', Reason} -> + ?ERROR_MSG("~p", [Reason]), + {noreply, State}; + Res -> + Res + end; +handle_info(connect, State) -> + connect(State); +handle_info(connect_feedback, State) + when State#state.feedback /= undefined, + State#state.feedback_socket == undefined -> + Feedback = State#state.feedback, + FeedbackPort = State#state.feedback_port, + CertFile = State#state.certfile, + case ssl:connect(Feedback, FeedbackPort, + [{certfile, CertFile}, + {active, true}, + binary]) of + {ok, Socket} -> + {noreply, State#state{feedback_socket = Socket}}; + {error, Reason} -> + ?ERROR_MSG("(~p) Connection to ~p:~p failed: ~p, " + "retrying after ~p seconds", + [State#state.host, Feedback, FeedbackPort, + Reason, ?FEEDBACK_RECONNECT_TIMEOUT div 1000]), + erlang:send_after(?FEEDBACK_RECONNECT_TIMEOUT, self(), + connect_feedback), + {noreply, State} + end; +handle_info({ssl, Socket, Packet}, State) + when Socket == State#state.socket -> + case Packet of + <<8, Status, CmdID:32>> when Status /= 0 -> + case dict:find(CmdID, State#state.cmd_cache) of + {ok, {JID, _DeviceID}} -> + From = jlib:make_jid("", State#state.host, ""), + ejabberd_router:route( + From, JID, + {xmlelement, "message", [], + [{xmlelement, "disable", + [{"xmlns", ?NS_P1_PUSH}, + {"status", integer_to_list(Status)}], + []}]}); + error -> + ?ERROR_MSG("Unknown cmd ID ~p~n", [CmdID]), + ok + end; + _ -> + ?ERROR_MSG("Received unknown packet ~p~n", [Packet]) + end, + {noreply, State}; +handle_info({ssl, Socket, Packet}, State) + when Socket == State#state.feedback_socket -> + Buf = <<(State#state.feedback_buf)/binary, Packet/binary>>, + Buf2 = parse_feedback_buf(Buf, State), + {noreply, State#state{feedback_buf = Buf2}}; +handle_info({ssl_closed, Socket}, State) + when Socket == State#state.feedback_socket -> + ssl:close(Socket), + erlang:send_after(?FEEDBACK_RECONNECT_TIMEOUT, self(), + connect_feedback), + {noreply, State#state{feedback_socket = undefined, + feedback_buf = <<>>}}; +handle_info(_Info, State) -> + %io:format("got info: ~p~n", [_Info]), + {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) -> + ejabberd_router:unregister_route(State#state.host), + 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(From, To, Packet, State) -> + #jid{user = User, resource = Resource} = To, + if + (User /= "") or (Resource /= "") -> + Err = jlib:make_error_reply(Packet, ?ERR_SERVICE_UNAVAILABLE), + ejabberd_router:route(To, From, Err), + {noreply, State}; + true -> + case Packet of + {xmlelement, "iq", _, _} -> + IQ = jlib:iq_query_info(Packet), + case IQ of + #iq{type = get, xmlns = ?NS_DISCO_INFO = XMLNS, + sub_el = _SubEl, lang = Lang} = IQ -> + Res = IQ#iq{type = result, + sub_el = [{xmlelement, "query", + [{"xmlns", XMLNS}], + iq_disco(Lang)}]}, + ejabberd_router:route(To, + From, + jlib:iq_to_xml(Res)), + {noreply, State}; + #iq{type = get, xmlns = ?NS_DISCO_ITEMS = XMLNS} = IQ -> + Res = IQ#iq{type = result, + sub_el = [{xmlelement, "query", + [{"xmlns", XMLNS}], + []}]}, + ejabberd_router:route(To, + From, + jlib:iq_to_xml(Res)), + {noreply, State}; + %%#iq{type = get, xmlns = ?NS_VCARD, lang = Lang} -> + %% ResIQ = + %% IQ#iq{type = result, + %% sub_el = [{xmlelement, + %% "vCard", + %% [{"xmlns", ?NS_VCARD}], + %% iq_get_vcard(Lang)}]}, + %% ejabberd_router:route(To, + %% From, + %% jlib:iq_to_xml(ResIQ)); + _ -> + Err = jlib:make_error_reply(Packet, + ?ERR_SERVICE_UNAVAILABLE), + ejabberd_router:route(To, From, Err), + {noreply, State} + end; + {xmlelement, "message", _, Els} -> + case xml:remove_cdata(Els) of + [{xmlelement, "push", _, _}] -> + NewState = handle_message(From, To, Packet, State), + {noreply, NewState}; + [{xmlelement, "disable", _, _}] -> + {noreply, State}; + _ -> + {noreply, State} + end; + _ -> + {noreply, State} + end + end. + + +handle_message(From, To, Packet, #state{socket = undefined} = State) -> + queue_message(From, To, Packet, State); +handle_message(From, To, Packet, State) -> + DeviceID = + xml:get_path_s(Packet, + [{elem, "push"}, {elem, "id"}, cdata]), + Msg = + xml:get_path_s(Packet, + [{elem, "push"}, {elem, "msg"}, cdata]), + Badge = + xml:get_path_s(Packet, + [{elem, "push"}, {elem, "badge"}, cdata]), + Sound = + xml:get_path_s(Packet, + [{elem, "push"}, {elem, "sound"}, cdata]), + Sender = + xml:get_path_s(Packet, + [{elem, "push"}, {elem, "from"}, cdata]), + Receiver = + xml:get_path_s(Packet, + [{elem, "push"}, {elem, "to"}, cdata]), + Payload = make_payload(State, Msg, Badge, Sound, Sender), + ID = + case catch erlang:list_to_integer(DeviceID, 16) of + ID1 when is_integer(ID1) -> + ID1; + _ -> + false + end, + if + is_integer(ID) -> + Command = 1, + CmdID = State#state.cmd_id, + {MegaSecs, Secs, _MicroSecs} = now(), + Expiry = MegaSecs * 1000000 + Secs + 24 * 60 * 60, + BDeviceID = <>, + BPayload = list_to_binary(Payload), + IDLen = size(BDeviceID), + PayloadLen = size(BPayload), + Notification = + <>, + ?INFO_MSG("(~p) sending notification for ~s~n~p~npayload:~n~s~n" + "Sender: ~s~n" + "Receiver: ~s~n" + "Device ID: ~s~n", + [State#state.host, erlang:integer_to_list(ID, 16), + Notification, Payload, + jlib:jid_to_string(From), + Receiver, DeviceID]), + case ssl:send(State#state.socket, Notification) of + ok -> + cache(From, ID, State); + {error, Reason} -> + ?INFO_MSG("(~p) Connection closed: ~p, reconnecting", + [State#state.host, Reason]), + ssl:close(State#state.socket), + self() ! connect, + queue_message(From, To, Packet, + State#state{socket = undefined}) + end; + true -> + State + end. + +make_payload(State, Msg, Badge, Sound, Sender) -> + Msg2 = json_escape(Msg), + AlertPayload = + case Msg2 of + "" -> ""; + _ -> "\"alert\":\"" ++ Msg2 ++ "\"" + end, + BadgePayload = + case catch list_to_integer(Badge) of + B when is_integer(B) -> + "\"badge\":" ++ Badge; + _ -> "" + end, + SoundPayload = + case Sound of + "true" -> + SoundFile = State#state.soundfile, + "\"sound\":\"" ++ json_escape(SoundFile) ++ "\""; + _ -> "" + end, + Payloads = lists:filter(fun(S) -> S /= "" end, + [AlertPayload, BadgePayload, SoundPayload]), + Payload = + "{\"aps\":{" ++ join(Payloads, ",") ++ "}," + "\"from\":\"" ++ json_escape(Sender) ++ "\"}", + PayloadLen = length(Payload), + if + PayloadLen > ?MAX_PAYLOAD_SIZE -> + Delta = PayloadLen - ?MAX_PAYLOAD_SIZE, + MsgLen = length(Msg), + if + MsgLen /= 0 -> + CutMsg = + if + MsgLen > Delta -> + lists:sublist(Msg, MsgLen - Delta); + true -> + "" + end, + make_payload(State, CutMsg, Badge, Sound, Sender); + true -> + Payload2 = + "{\"aps\":{" ++ join(Payloads, ",") ++ "}}", + %PayloadLen2 = length(Payload2), + Payload2 + end; + true -> + Payload + end. + +connect(#state{socket = undefined} = State) -> + Gateway = State#state.gateway, + Port = State#state.port, + CertFile = State#state.certfile, + case ssl:connect(Gateway, Port, [{certfile, CertFile}, + {active, true}, + binary]) of + {ok, Socket} -> + {noreply, resend_messages(State#state{socket = Socket})}; + {error, Reason} -> + ?ERROR_MSG("(~p) Connection to ~p:~p failed: ~p, " + "retrying after ~p seconds", + [State#state.host, Gateway, Port, + Reason, ?RECONNECT_TIMEOUT div 1000]), + erlang:send_after(?RECONNECT_TIMEOUT, self(), connect), + {noreply, State} + end; +connect(State) -> + {noreply, State}. + +bounce_message(From, To, Packet, Reason) -> + {xmlelement, _, Attrs, _} = Packet, + Type = xml:get_attr_s("type", Attrs), + if Type /= "error"; Type /= "result" -> + ejabberd_router:route( + To, From, + jlib:make_error_reply( + Packet, + ?ERRT_INTERNAL_SERVER_ERROR( + xml:get_attr_s("xml:lang", Attrs), + Reason))); + true -> + ok + end. + +queue_message(From, To, Packet, State) -> + case State#state.queue of + {?MAX_QUEUE_SIZE, Queue} -> + {{value, {From1, To1, Packet1}}, Queue1} = queue:out(Queue), + bounce_message(From1, To1, Packet1, + "Unable to connect to push service"), + Queue2 = queue:in({From, To, Packet}, Queue1), + State#state{queue = {?MAX_QUEUE_SIZE, Queue2}}; + {Size, Queue} -> + Queue1 = queue:in({From, To, Packet}, Queue), + State#state{queue = {Size+1, Queue1}} + end. + +resend_messages(#state{queue = {_, Queue}} = State) -> + lists:foldl( + fun({From, To, Packet}, AccState) -> + case catch handle_message(From, To, Packet, AccState) of + {'EXIT', _} = Err -> + ?ERROR_MSG("error while processing message:~n" + "** From: ~p~n" + "** To: ~p~n" + "** Packet: ~p~n" + "** Reason: ~p", + [From, To, Packet, Err]), + AccState; + NewAccState -> + NewAccState + end + end, State#state{queue = {0, queue:new()}}, queue:to_list(Queue)). + +cache(JID, DeviceID, State) -> + CmdID = State#state.cmd_id, + Key = CmdID rem ?CACHE_SIZE, + C1 = State#state.cmd_cache, + D1 = State#state.device_cache, + D2 = case dict:find(Key, C1) of + {ok, {_, OldDeviceID}} -> + del_device_cache(D1, OldDeviceID); + error -> + D1 + end, + D3 = add_device_cache(D2, DeviceID, JID), + C2 = dict:store(Key, {JID, DeviceID}, C1), + State#state{cmd_id = CmdID + 1, + cmd_cache = C2, + device_cache = D3}. + +add_device_cache(DeviceCache, DeviceID, JID) -> + dict:update( + DeviceID, + fun({Counter, _}) -> {Counter + 1, JID} end, + {1, JID}, + DeviceCache). + +del_device_cache(DeviceCache, DeviceID) -> + case dict:find(DeviceID, DeviceCache) of + {ok, {Counter, JID}} -> + case Counter of + 1 -> + dict:erase(DeviceID, DeviceCache); + _ -> + dict:store(DeviceID, {Counter - 1, JID}, DeviceCache) + end; + error -> + DeviceCache + end. + +json_escape(S) -> + [case C of + $" -> "\\\""; + $\\ -> "\\\\"; + _ when C < 16 -> ["\\u000", erlang:integer_to_list(C, 16)]; + _ when C < 32 -> ["\\u00", erlang:integer_to_list(C, 16)]; + _ -> C + end || C <- S]. + +join(List, Sep) -> + lists:foldr(fun(A, "") -> A; + (A, Acc) -> A ++ Sep ++ Acc + end, "", List). + + + +iq_disco(Lang) -> + [{xmlelement, "identity", + [{"category", "gateway"}, + {"type", "apple"}, + {"name", translate:translate(Lang, "Apple Push Service")}], []}, + {xmlelement, "feature", [{"var", ?NS_DISCO_INFO}], []}]. + + +parse_feedback_buf(Buf, State) -> + case Buf of + <> -> + IDLen8 = IDLen * 8, + <> = BDeviceID, + case dict:find(DeviceID, State#state.device_cache) of + {ok, {_Counter, JID}} -> + From = jlib:make_jid("", State#state.host, ""), + ejabberd_router:route( + From, JID, + {xmlelement, "message", [], + [{xmlelement, "disable", + [{"xmlns", ?NS_P1_PUSH}, + {"status", "feedback"}, + {"ts", integer_to_list(TimeStamp)}], + []}]}); + error -> + ok + end, + parse_feedback_buf(Rest, State); + _ -> + Buf + end. diff --git a/src/mod_offline.erl b/src/mod_offline.erl index dfa2f46c2..2448a17c0 100644 --- a/src/mod_offline.erl +++ b/src/mod_offline.erl @@ -30,19 +30,18 @@ -behaviour(gen_mod). -export([start/2, - loop/1, + init/1, stop/1, store_packet/3, resend_offline_messages/2, pop_offline_messages/3, - get_sm_features/5, remove_expired_messages/0, remove_old_messages/1, remove_user/2, - get_queue_length/2, webadmin_page/3, webadmin_user/4, - webadmin_user_parse_query/5]). + webadmin_user_parse_query/5, + count_offline_messages/3]). -include("ejabberd.hrl"). -include("jlib.hrl"). @@ -54,9 +53,6 @@ -define(PROCNAME, ejabberd_offline). -define(OFFLINE_TABLE_LOCK_THRESHOLD, 1000). -%% default value for the maximum number of user messages --define(MAX_USER_MESSAGES, infinity). - start(Host, Opts) -> mnesia:create_table(offline_msg, [{disc_only_copies, [node()]}, @@ -71,28 +67,30 @@ start(Host, Opts) -> ?MODULE, remove_user, 50), ejabberd_hooks:add(anonymous_purge_hook, Host, ?MODULE, remove_user, 50), - ejabberd_hooks:add(disco_sm_features, Host, - ?MODULE, get_sm_features, 50), - ejabberd_hooks:add(disco_local_features, Host, - ?MODULE, get_sm_features, 50), ejabberd_hooks:add(webadmin_page_host, Host, ?MODULE, webadmin_page, 50), ejabberd_hooks:add(webadmin_user, Host, ?MODULE, webadmin_user, 50), ejabberd_hooks:add(webadmin_user_parse_query, Host, ?MODULE, webadmin_user_parse_query, 50), - AccessMaxOfflineMsgs = gen_mod:get_opt(access_max_user_messages, Opts, max_user_offline_messages), + ejabberd_hooks:add(count_offline_messages, Host, + ?MODULE, count_offline_messages, 50), + MaxOfflineMsgs = gen_mod:get_opt(user_max_messages, Opts, infinity), register(gen_mod:get_module_proc(Host, ?PROCNAME), - spawn(?MODULE, loop, [AccessMaxOfflineMsgs])). + spawn(?MODULE, init, [MaxOfflineMsgs])). -loop(AccessMaxOfflineMsgs) -> +%% MaxOfflineMsgs is either infinity of integer > 0 +init(infinity) -> + loop(infinity); +init(MaxOfflineMsgs) + when is_integer(MaxOfflineMsgs), MaxOfflineMsgs > 0 -> + loop(MaxOfflineMsgs). + +loop(MaxOfflineMsgs) -> receive #offline_msg{us=US} = Msg -> Msgs = receive_all(US, [Msg]), Len = length(Msgs), - {User, Host} = US, - MaxOfflineMsgs = get_max_user_messages(AccessMaxOfflineMsgs, - User, Host), F = fun() -> %% Only count messages if needed: Count = if MaxOfflineMsgs =/= infinity -> @@ -118,18 +116,9 @@ loop(AccessMaxOfflineMsgs) -> end end, mnesia:transaction(F), - loop(AccessMaxOfflineMsgs); + loop(MaxOfflineMsgs); _ -> - loop(AccessMaxOfflineMsgs) - end. - -%% Function copied from ejabberd_sm.erl: -get_max_user_messages(AccessRule, LUser, Host) -> - case acl:match_rule( - Host, AccessRule, jlib:make_jid(LUser, Host, "")) of - Max when is_integer(Max) -> Max; - infinity -> infinity; - _ -> ?MAX_USER_MESSAGES + loop(MaxOfflineMsgs) end. receive_all(US, Msgs) -> @@ -150,8 +139,6 @@ stop(Host) -> ?MODULE, remove_user, 50), ejabberd_hooks:delete(anonymous_purge_hook, Host, ?MODULE, remove_user, 50), - ejabberd_hooks:delete(disco_sm_features, Host, ?MODULE, get_sm_features, 50), - ejabberd_hooks:delete(disco_local_features, Host, ?MODULE, get_sm_features, 50), ejabberd_hooks:delete(webadmin_page_host, Host, ?MODULE, webadmin_page, 50), ejabberd_hooks:delete(webadmin_user, Host, @@ -162,27 +149,12 @@ stop(Host) -> exit(whereis(Proc), stop), {wait, Proc}. -get_sm_features(Acc, _From, _To, "", _Lang) -> - Feats = case Acc of - {result, I} -> I; - _ -> [] - end, - {result, Feats ++ [?NS_FEATURE_MSGOFFLINE]}; - -get_sm_features(_Acc, _From, _To, ?NS_FEATURE_MSGOFFLINE, _Lang) -> - %% override all lesser features... - {result, []}; - -get_sm_features(Acc, _From, _To, _Node, _Lang) -> - Acc. - - store_packet(From, To, Packet) -> Type = xml:get_tag_attr_s("type", Packet), if (Type /= "error") and (Type /= "groupchat") and (Type /= "headline") -> - case check_event_chatstates(From, To, Packet) of + case check_event(From, To, Packet) of true -> #jid{luser = LUser, lserver = LServer} = To, TimeStamp = now(), @@ -203,22 +175,12 @@ store_packet(From, To, Packet) -> ok end. -%% Check if the packet has any content about XEP-0022 or XEP-0085 -check_event_chatstates(From, To, Packet) -> +check_event(From, To, Packet) -> {xmlelement, Name, Attrs, Els} = Packet, - case find_x_event_chatstates(Els, {false, false, false}) of - %% There wasn't any x:event or chatstates subelements - {false, false, _} -> + case find_x_event(Els) of + false -> true; - %% There a chatstates subelement and other stuff, but no x:event - {false, CEl, true} when CEl /= false -> - true; - %% There was only a subelement: a chatstates - {false, CEl, false} when CEl /= false -> - %% Don't allow offline storage - false; - %% There was an x:event element, and maybe also other stuff - {El, _, _} when El /= false -> + El -> case xml:get_subtag(El, "id") of false -> case xml:get_subtag(El, "offline") of @@ -246,19 +208,16 @@ check_event_chatstates(From, To, Packet) -> end end. -%% Check if the packet has subelements about XEP-0022, XEP-0085 or other -find_x_event_chatstates([], Res) -> - Res; -find_x_event_chatstates([{xmlcdata, _} | Els], Res) -> - find_x_event_chatstates(Els, Res); -find_x_event_chatstates([El | Els], {A, B, C}) -> +find_x_event([]) -> + false; +find_x_event([{xmlcdata, _} | Els]) -> + find_x_event(Els); +find_x_event([El | Els]) -> case xml:get_tag_attr_s("xmlns", El) of ?NS_EVENT -> - find_x_event_chatstates(Els, {El, B, C}); - ?NS_CHATSTATES -> - find_x_event_chatstates(Els, {A, El, C}); + El; _ -> - find_x_event_chatstates(Els, {A, B, true}) + find_x_event(Els) end. find_x_expire(_, []) -> @@ -307,13 +266,6 @@ resend_offline_messages(User, Server) -> {xmlelement, Name, Attrs, Els ++ [jlib:timestamp_to_xml( - calendar:now_to_universal_time( - R#offline_msg.timestamp), - utc, - jlib:make_jid("", Server, ""), - "Offline Storage"), - %% TODO: Delete the next three lines once XEP-0091 is Obsolete - jlib:timestamp_to_xml( calendar:now_to_universal_time( R#offline_msg.timestamp))]}} end, @@ -343,14 +295,7 @@ pop_offline_messages(Ls, User, Server) -> {xmlelement, Name, Attrs, Els ++ [jlib:timestamp_to_xml( - calendar:now_to_universal_time( - R#offline_msg.timestamp), - utc, - jlib:make_jid("", Server, ""), - "Offline Storage"), - %% TODO: Delete the next three lines once XEP-0091 is Obsolete - jlib:timestamp_to_xml( - calendar:now_to_universal_time( + calendar:now_to_universal_time( R#offline_msg.timestamp))]}} end, lists:filter( @@ -367,7 +312,6 @@ pop_offline_messages(Ls, User, Server) -> Ls end. - remove_expired_messages() -> TimeStamp = now(), F = fun() -> @@ -530,9 +474,8 @@ webadmin_page(Acc, _, _) -> Acc. user_queue(User, Server, Query, Lang) -> US = {jlib:nodeprep(User), jlib:nameprep(Server)}, Res = user_queue_parse_query(US, Query), - MsgsAll = lists:keysort(#offline_msg.timestamp, - mnesia:dirty_read({offline_msg, US})), - Msgs = get_messages_subset(User, Server, MsgsAll), + Msgs = lists:keysort(#offline_msg.timestamp, + mnesia:dirty_read({offline_msg, US})), FMsgs = lists:map( fun(#offline_msg{timestamp = TimeStamp, from = From, to = To, @@ -614,32 +557,9 @@ user_queue_parse_query(US, Query) -> us_to_list({User, Server}) -> jlib:jid_to_string({User, Server, ""}). -get_queue_length(User, Server) -> - length(mnesia:dirty_read({offline_msg, {User, Server}})). - -get_messages_subset(User, Host, MsgsAll) -> - Access = gen_mod:get_module_opt(Host, ?MODULE, access_max_user_messages, - max_user_offline_messages), - MaxOfflineMsgs = case get_max_user_messages(Access, User, Host) of - Number when is_integer(Number) -> Number; - _ -> 100 - end, - Length = length(MsgsAll), - get_messages_subset2(MaxOfflineMsgs, Length, MsgsAll). - -get_messages_subset2(Max, Length, MsgsAll) when Length =< Max*2 -> - MsgsAll; -get_messages_subset2(Max, Length, MsgsAll) -> - FirstN = Max, - {MsgsFirstN, Msgs2} = lists:split(FirstN, MsgsAll), - MsgsLastN = lists:nthtail(Length - FirstN - FirstN, Msgs2), - NoJID = jlib:make_jid("...", "...", ""), - IntermediateMsg = #offline_msg{timestamp = now(), from = NoJID, to = NoJID, - packet = {xmlelement, "...", [], []}}, - MsgsFirstN ++ [IntermediateMsg] ++ MsgsLastN. - webadmin_user(Acc, User, Server, Lang) -> - QueueLen = get_queue_length(jlib:nodeprep(User), jlib:nameprep(Server)), + US = {jlib:nodeprep(User), jlib:nameprep(Server)}, + QueueLen = length(mnesia:dirty_read({offline_msg, US})), FQueueLen = [?AC("queue/", integer_to_list(QueueLen))], Acc ++ [?XCT("h3", "Offline Messages:")] ++ FQueueLen ++ [?C(" "), ?INPUTT("submit", "removealloffline", "Remove All Offline Messages")]. @@ -663,3 +583,23 @@ webadmin_user_parse_query(_, "removealloffline", User, Server, _Query) -> end; webadmin_user_parse_query(Acc, _Action, _User, _Server, _Query) -> Acc. + + +%% ------------------------------------------------ +%% mod_offline: number of messages quota management + +count_offline_messages(_Acc, User, Server) -> + LUser = jlib:nodeprep(User), + LServer = jlib:nameprep(Server), + US = {LUser, LServer}, + F = fun () -> + p1_mnesia:count_records( + offline_msg, + #offline_msg{us=US, _='_'}) + end, + N = case catch mnesia:async_dirty(F) of + I when is_integer(I) -> I; + _ -> 0 + end, + {stop, N}. + diff --git a/src/mod_offline_odbc.erl b/src/mod_offline_odbc.erl index 063ea709e..420ff581f 100644 --- a/src/mod_offline_odbc.erl +++ b/src/mod_offline_odbc.erl @@ -32,16 +32,15 @@ -export([count_offline_messages/2]). -export([start/2, - loop/2, + init/2, stop/1, store_packet/3, pop_offline_messages/3, - get_sm_features/5, remove_user/2, - get_queue_length/2, webadmin_page/3, webadmin_user/4, - webadmin_user_parse_query/5]). + webadmin_user_parse_query/5, + count_offline_messages/3]). -include("ejabberd.hrl"). -include("jlib.hrl"). @@ -53,9 +52,6 @@ -define(PROCNAME, ejabberd_offline). -define(OFFLINE_TABLE_LOCK_THRESHOLD, 1000). -%% default value for the maximum number of user messages --define(MAX_USER_MESSAGES, infinity). - start(Host, Opts) -> ejabberd_hooks:add(offline_message_hook, Host, ?MODULE, store_packet, 50), @@ -65,27 +61,30 @@ start(Host, Opts) -> ?MODULE, remove_user, 50), ejabberd_hooks:add(anonymous_purge_hook, Host, ?MODULE, remove_user, 50), - ejabberd_hooks:add(disco_sm_features, Host, - ?MODULE, get_sm_features, 50), - ejabberd_hooks:add(disco_local_features, Host, - ?MODULE, get_sm_features, 50), ejabberd_hooks:add(webadmin_page_host, Host, ?MODULE, webadmin_page, 50), ejabberd_hooks:add(webadmin_user, Host, ?MODULE, webadmin_user, 50), ejabberd_hooks:add(webadmin_user_parse_query, Host, ?MODULE, webadmin_user_parse_query, 50), - AccessMaxOfflineMsgs = gen_mod:get_opt(access_max_user_messages, Opts, max_user_offline_messages), + ejabberd_hooks:add(count_offline_messages, Host, + ?MODULE, count_offline_messages, 50), + MaxOfflineMsgs = gen_mod:get_opt(user_max_messages, Opts, infinity), register(gen_mod:get_module_proc(Host, ?PROCNAME), - spawn(?MODULE, loop, [Host, AccessMaxOfflineMsgs])). + spawn(?MODULE, init, [Host, MaxOfflineMsgs])). -loop(Host, AccessMaxOfflineMsgs) -> +%% MaxOfflineMsgs is either infinity of integer > 0 +init(Host, infinity) -> + loop(Host, infinity); +init(Host, MaxOfflineMsgs) + when is_integer(MaxOfflineMsgs), MaxOfflineMsgs > 0 -> + loop(Host, MaxOfflineMsgs). + +loop(Host, MaxOfflineMsgs) -> receive #offline_msg{user = User} = Msg -> Msgs = receive_all(User, [Msg]), Len = length(Msgs), - MaxOfflineMsgs = get_max_user_messages(AccessMaxOfflineMsgs, - User, Host), %% Only count existing messages if needed: Count = if MaxOfflineMsgs =/= infinity -> @@ -113,17 +112,11 @@ loop(Host, AccessMaxOfflineMsgs) -> Els ++ [jlib:timestamp_to_xml( calendar:now_to_universal_time( - M#offline_msg.timestamp), - utc, - jlib:make_jid("", Host, ""), - "Offline Storage"), - %% TODO: Delete the next three lines once XEP-0091 is Obsolete - jlib:timestamp_to_xml( - calendar:now_to_universal_time( M#offline_msg.timestamp))]}, XML = ejabberd_odbc:escape( - xml:element_to_binary(Packet)), + lists:flatten( + xml:element_to_string(Packet))), odbc_queries:add_spool_sql(Username, XML) end, Msgs), case catch odbc_queries:add_spool(Host, Query) of @@ -135,18 +128,9 @@ loop(Host, AccessMaxOfflineMsgs) -> ok end end, - loop(Host, AccessMaxOfflineMsgs); + loop(Host, MaxOfflineMsgs); _ -> - loop(Host, AccessMaxOfflineMsgs) - end. - -%% Function copied from ejabberd_sm.erl: -get_max_user_messages(AccessRule, LUser, Host) -> - case acl:match_rule( - Host, AccessRule, jlib:make_jid(LUser, Host, "")) of - Max when is_integer(Max) -> Max; - infinity -> infinity; - _ -> ?MAX_USER_MESSAGES + loop(Host, MaxOfflineMsgs) end. receive_all(Username, Msgs) -> @@ -167,8 +151,6 @@ stop(Host) -> ?MODULE, remove_user, 50), ejabberd_hooks:delete(anonymous_purge_hook, Host, ?MODULE, remove_user, 50), - ejabberd_hooks:delete(disco_sm_features, Host, ?MODULE, get_sm_features, 50), - ejabberd_hooks:delete(disco_local_features, Host, ?MODULE, get_sm_features, 50), ejabberd_hooks:delete(webadmin_page_host, Host, ?MODULE, webadmin_page, 50), ejabberd_hooks:delete(webadmin_user, Host, @@ -179,27 +161,12 @@ stop(Host) -> exit(whereis(Proc), stop), ok. -get_sm_features(Acc, _From, _To, "", _Lang) -> - Feats = case Acc of - {result, I} -> I; - _ -> [] - end, - {result, Feats ++ [?NS_FEATURE_MSGOFFLINE]}; - -get_sm_features(_Acc, _From, _To, ?NS_FEATURE_MSGOFFLINE, _Lang) -> - %% override all lesser features... - {result, []}; - -get_sm_features(Acc, _From, _To, _Node, _Lang) -> - Acc. - - store_packet(From, To, Packet) -> Type = xml:get_tag_attr_s("type", Packet), if (Type /= "error") and (Type /= "groupchat") and (Type /= "headline") -> - case check_event_chatstates(From, To, Packet) of + case check_event(From, To, Packet) of true -> #jid{luser = LUser} = To, TimeStamp = now(), @@ -220,22 +187,12 @@ store_packet(From, To, Packet) -> ok end. -%% Check if the packet has any content about XEP-0022 or XEP-0085 -check_event_chatstates(From, To, Packet) -> +check_event(From, To, Packet) -> {xmlelement, Name, Attrs, Els} = Packet, - case find_x_event_chatstates(Els, {false, false, false}) of - %% There wasn't any x:event or chatstates subelements - {false, false, _} -> + case find_x_event(Els) of + false -> true; - %% There a chatstates subelement and other stuff, but no x:event - {false, CEl, true} when CEl /= false -> - true; - %% There was only a subelement: a chatstates - {false, CEl, false} when CEl /= false -> - %% Don't allow offline storage - false; - %% There was an x:event element, and maybe also other stuff - {El, _, _} when El /= false -> + El -> case xml:get_subtag(El, "id") of false -> case xml:get_subtag(El, "offline") of @@ -257,25 +214,22 @@ check_event_chatstates(From, To, Packet) -> {xmlelement, "offline", [], []}]}] }), true - end; + end; _ -> false end end. -%% Check if the packet has subelements about XEP-0022, XEP-0085 or other -find_x_event_chatstates([], Res) -> - Res; -find_x_event_chatstates([{xmlcdata, _} | Els], Res) -> - find_x_event_chatstates(Els, Res); -find_x_event_chatstates([El | Els], {A, B, C}) -> +find_x_event([]) -> + false; +find_x_event([{xmlcdata, _} | Els]) -> + find_x_event(Els); +find_x_event([El | Els]) -> case xml:get_tag_attr_s("xmlns", El) of ?NS_EVENT -> - find_x_event_chatstates(Els, {El, B, C}); - ?NS_CHATSTATES -> - find_x_event_chatstates(Els, {A, El, C}); + El; _ -> - find_x_event_chatstates(Els, {A, B, true}) + find_x_event(Els) end. find_x_expire(_, []) -> @@ -375,7 +329,7 @@ user_queue(User, Server, Query, Lang) -> Username = ejabberd_odbc:escape(LUser), US = {LUser, LServer}, Res = user_queue_parse_query(Username, LServer, Query), - MsgsAll = case catch ejabberd_odbc:sql_query( + Msgs = case catch ejabberd_odbc:sql_query( LServer, ["select username, xml from spool" " where username='", Username, "'" @@ -393,7 +347,6 @@ user_queue(User, Server, Query, Lang) -> _ -> [] end, - Msgs = get_messages_subset(User, Server, MsgsAll), FMsgs = lists:map( fun({xmlelement, _Name, _Attrs, _Els} = Msg) -> @@ -480,8 +433,11 @@ user_queue_parse_query(Username, LServer, Query) -> us_to_list({User, Server}) -> jlib:jid_to_string({User, Server, ""}). -get_queue_length(Username, LServer) -> - case catch ejabberd_odbc:sql_query( +webadmin_user(Acc, User, Server, Lang) -> + LUser = jlib:nodeprep(User), + LServer = jlib:nameprep(Server), + Username = ejabberd_odbc:escape(LUser), + QueueLen = case catch ejabberd_odbc:sql_query( LServer, ["select count(*) from spool" " where username='", Username, "';"]) of @@ -489,32 +445,7 @@ get_queue_length(Username, LServer) -> SCount; _ -> 0 - end. - -get_messages_subset(User, Host, MsgsAll) -> - Access = gen_mod:get_module_opt(Host, ?MODULE, access_max_user_messages, - max_user_offline_messages), - MaxOfflineMsgs = case get_max_user_messages(Access, User, Host) of - Number when is_integer(Number) -> Number; - _ -> 100 - end, - Length = length(MsgsAll), - get_messages_subset2(MaxOfflineMsgs, Length, MsgsAll). - -get_messages_subset2(Max, Length, MsgsAll) when Length =< Max*2 -> - MsgsAll; -get_messages_subset2(Max, Length, MsgsAll) -> - FirstN = Max, - {MsgsFirstN, Msgs2} = lists:split(FirstN, MsgsAll), - MsgsLastN = lists:nthtail(Length - FirstN - FirstN, Msgs2), - IntermediateMsg = {xmlelement, "...", [], []}, - MsgsFirstN ++ [IntermediateMsg] ++ MsgsLastN. - -webadmin_user(Acc, User, Server, Lang) -> - LUser = jlib:nodeprep(User), - LServer = jlib:nameprep(Server), - Username = ejabberd_odbc:escape(LUser), - QueueLen = get_queue_length(Username, LServer), + end, FQueueLen = [?AC("queue/", QueueLen)], Acc ++ [?XCT("h3", "Offline Messages:")] ++ FQueueLen ++ [?C(" "), ?INPUTT("submit", "removealloffline", "Remove All Offline Messages")]. @@ -546,3 +477,30 @@ count_offline_messages(LUser, LServer) -> _ -> 0 end. + +count_offline_messages(_Acc, User, Server) -> + LUser = jlib:nodeprep(User), + LServer = jlib:nameprep(Server), + Num = case catch ejabberd_odbc:sql_query( + LServer, + ["select xml from spool" + " where username='", LUser, "';"]) of + {selected, ["xml"], Rs} -> + lists:foldl( + fun({XML}, Acc) -> + case xml_stream:parse_element(XML) of + {error, _Reason} -> + Acc; + El -> + case xml:get_subtag(El, "body") of + false -> + Acc; + _ -> + Acc + 1 + end + end + end, 0, Rs); + _ -> + 0 + end, + {stop, Num}. diff --git a/src/xml.erl b/src/xml.erl index 22746b10a..3e0157313 100644 --- a/src/xml.erl +++ b/src/xml.erl @@ -31,6 +31,7 @@ element_to_binary/1, crypt/1, make_text_node/1, remove_cdata/1, + remove_subtags/3, get_cdata/1, get_tag_cdata/1, get_attr/2, get_attr_s/2, get_tag_attr/2, get_tag_attr_s/2, @@ -186,6 +187,31 @@ remove_cdata_p(_) -> false. remove_cdata(L) -> [E || E <- L, remove_cdata_p(E)]. +%% TODO: Make more generic. +%% For now only support all parameters: +%% xml:remove_subtags({xmlelement,"message", [{"id","81be72"}],[{xmlelement,"on-sender-server",[{"xmlns","urn:xmpp:receipts"},{"server","text-one.com"}], []}]}, "on-sender-server", {"xmlns","urn:xmpp:receipts"}). +remove_subtags({xmlelement, TagName, TagAttrs, Els}, Name, Attr) -> + {xmlelement, TagName, TagAttrs, remove_subtags1(Els, [], Name, Attr)}. + +remove_subtags1([], NewEls, _Name, _Attr) -> + lists:reverse(NewEls); +remove_subtags1([El | Els], NewEls, Name, {AttrName, AttrValue} = Attr) -> + case El of + {xmlelement, Name, Attrs, _} -> + case get_attr(AttrName, Attrs) of + false -> + remove_subtags1(Els, [El|NewEls], Name, Attr); + {value, AttrValue} -> + remove_subtags1(Els, NewEls, Name, Attr); + _ -> + remove_subtags1(Els, [El|NewEls], Name, Attr) + end; + _ -> + remove_subtags1(Els, [El|NewEls], Name, Attr) + end. + + + get_cdata(L) -> binary_to_list(list_to_binary(get_cdata(L, ""))). diff --git a/src/xml_stream.erl b/src/xml_stream.erl index b98e3291b..f3aa5502d 100644 --- a/src/xml_stream.erl +++ b/src/xml_stream.erl @@ -76,6 +76,9 @@ process_data(CallbackPid, Stack, Data) -> {?XML_CDATA, CData} -> case Stack of [El] -> + catch gen_fsm:send_all_state_event( + CallbackPid, + {xmlstreamcdata, CData}), [El]; %% Merge CDATA nodes if they are contiguous %% This does not change the semantic: the split in From 77136bccdf9e680f7b241b606215e54e99e14336 Mon Sep 17 00:00:00 2001 From: Eric Cestari Date: Fri, 10 Sep 2010 14:06:26 +0200 Subject: [PATCH 37/85] [TECH-1151] websocket initial code --- src/web/ejabberd_websocket.erl | 159 +++++++++++++++++++++++++++++++++ 1 file changed, 159 insertions(+) create mode 100644 src/web/ejabberd_websocket.erl diff --git a/src/web/ejabberd_websocket.erl b/src/web/ejabberd_websocket.erl new file mode 100644 index 000000000..ae855af54 --- /dev/null +++ b/src/web/ejabberd_websocket.erl @@ -0,0 +1,159 @@ +%%%---------------------------------------------------------------------- +%%% File : ejabberd_websocket.erl +%%% Author : Eric Cestari +%%% Purpose : XMPP Websocket support +%%% Created : 09-10-2010 by Eric Cestari +%%% +%%% Some code lifted from MISULTIN - WebSocket misultin_websocket.erl - >-|-|-(°> +%%% (http://github.com/ostinelli/misultin/blob/master/src/misultin_websocket.erl) +%%% Copyright (C) 2010, Roberto Ostinelli , Joe Armstrong. +%%% All rights reserved. +%%% +%%% Code portions from Joe Armstrong have been originally taken under MIT license at the address: +%%% +%%% +%%% BSD License +%%% +%%% Redistribution and use in source and binary forms, with or without modification, are permitted provided +%%% that the following conditions are met: +%%% +%%% * Redistributions of source code must retain the above copyright notice, this list of conditions and the +%%% following disclaimer. +%%% * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and +%%% the following disclaimer in the documentation and/or other materials provided with the distribution. +%%% * Neither the name of the authors nor the names of its contributors may be used to endorse or promote +%%% products derived from this software without specific prior written permission. +%%% +%%% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED +%%% WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +%%% PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +%%% ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +%%% TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +%%% HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +%%% NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +%%% POSSIBILITY OF SUCH DAMAGE. +%%% ========================================================================================================== +%%% ejabberd, Copyright (C) 2002-2010 ProcessOne +%%%---------------------------------------------------------------------- + +-module (ejabberd_websocket). +-author('ecestari@process-one.net'). +-compile(export_all). + +-include ("ejabberd_http.hrl"). +-include ("ejabberd.hrl"). + +check(Headers)-> + ?DEBUG("testing for a websocket request path: ~p headers: ~p", [_Path, Headers]), + % set supported websocket protocols, order does matter + VsnSupported = [{'draft-hixie', 76}, {'draft-hixie', 68}], + % checks + check_websockets(VsnSupported, Headers). + +check_websockets([], _Headers) -> false; +check_websockets([Vsn|T], Headers) -> + case check_websocket(Vsn, Headers) of + false -> check_websockets(T, Headers); + {true, Vsn} -> {true, Vsn} + end. + +% Function: {true, Vsn} | false +% Description: Check if the incoming request is a websocket request. +check_websocket({'draft-hixie', 76} = Vsn, Headers) -> + ?DEBUG("testing for websocket protocol ~p", [Vsn]), + % set required headers + RequiredHeaders = [ + {'Upgrade', "WebSocket"}, {'Connection', "Upgrade"}, {'Host', ignore}, {'Origin', ignore}, + {'Sec-WebSocket-Key1', ignore}, {'Sec-WebSocket-Key2', ignore} + ], + % check for headers existance + case check_headers(Headers, RequiredHeaders) of + true -> + % return + {true, Vsn}; + _RemainingHeaders -> + ?LOG_DEBUG("not protocol ~p, remaining headers: ~p", [Vsn, _RemainingHeaders]), + false + end; +check_websocket({'draft-hixie', 68} = Vsn, Headers) -> + ?DEBUG("testing for websocket protocol ~p", [Vsn]), + % set required headers + RequiredHeaders = [ + {'Upgrade', "WebSocket"}, {'Connection', "Upgrade"}, {'Host', ignore}, {'Origin', ignore} + ], + % check for headers existance + case check_headers(Headers, RequiredHeaders) of + true -> {true, Vsn}; + _RemainingHeaders -> + ?LOG_DEBUG("not protocol ~p, remaining headers: ~p", [Vsn, _RemainingHeaders]), + false + end; +check_websocket(_Vsn, _Headers) -> false. % not implemented + +% Function: true | [{RequiredTag, RequiredVal}, ..] +% Description: Check if headers correspond to headers requirements. +check_headers(Headers, RequiredHeaders) -> + F = fun({Tag, Val}) -> + % see if the required Tag is in the Headers + case lists:keysearch(Tag, 1, Headers) of + false -> true; % header not found, keep in list + HVal -> + case Val of + ignore -> false; % ignore value -> ok, remove from list + HVal -> false; % expected val -> ok, remove from list + _ -> true % val is different, keep in list + end + end + end, + case lists:filter(F, RequiredHeaders) of + [] -> true; + MissingHeaders -> MissingHeaders + end. + +% Function: List +% Description: Builds the server handshake response. +handshake({'draft-hixie', 76}, #req{socket = Sock, socket_mode = SocketMode}, Headers, {Path, Origin, Host}) -> + % build data + Key1 = lists:keysearch('Sec-WebSocket-Key1',1, Headers), + Key2 = lists:keysearch('Sec-WebSocket-Key2',1, Headers), + % handshake needs body of the request, still need to read it [TODO: default recv timeout hard set, will be exported when WS protocol is final] + misultin_socket:setopts(Sock, [{packet, raw}, {active, false}], SocketMode), + Body = case misultin_socket:recv(Sock, 8, 30*1000, SocketMode) of + {ok, Bin} -> Bin; + {error, timeout} -> + ?WARNING_MSG("timeout in reading websocket body", []), + <<>>; + _Other -> + ?ERROR_MSG("tcp error treating data: ~p", [_Other]), + <<>> + end, + ?DEBUG("got content in body of websocket request: ~p", [Body]), + % prepare handhsake response + ["HTTP/1.1 101 WebSocket Protocol Handshake\r\n", + "Upgrade: WebSocket\r\n", + "Connection: Upgrade\r\n", + "Sec-WebSocket-Origin: ", Origin, "\r\n", + "Sec-WebSocket-Location: ws://", lists:concat([Host, Path]), "\r\n\r\n", + build_challenge({'draft-hixie', 76}, {Key1, Key2, Body}) + ]; +handshake({'draft-hixie', 68}, _Req, _Headers, {Path, Origin, Host}) -> + % prepare handhsake response + ["HTTP/1.1 101 Web Socket Protocol Handshake\r\n", + "Upgrade: WebSocket\r\n", + "Connection: Upgrade\r\n", + "WebSocket-Origin: ", Origin , "\r\n", + "WebSocket-Location: ws://", lists:concat([Host, Path]), "\r\n\r\n" + ]. + +% Function: List +% Description: Builds the challenge for a handshake response. +% Code portions from Sergio Veiga +build_challenge({'draft-hixie', 76}, {Key1, Key2, Key3}) -> + Ikey1 = [D || D <- Key1, $0 =< D, D =< $9], + Ikey2 = [D || D <- Key2, $0 =< D, D =< $9], + Blank1 = length([D || D <- Key1, D =:= 32]), + Blank2 = length([D || D <- Key2, D =:= 32]), + Part1 = list_to_integer(Ikey1) div Blank1, + Part2 = list_to_integer(Ikey2) div Blank2, + Ckey = <>, + erlang:md5(Ckey). \ No newline at end of file From 660a2735f04308a5cf58aac7df51f18d2ff18931 Mon Sep 17 00:00:00 2001 From: Eric Cestari Date: Fri, 10 Sep 2010 14:11:56 +0200 Subject: [PATCH 38/85] mod_keepalive added to repos --- src/keepalive.hrl | 1 + src/mod_keepalive.erl | 71 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 src/keepalive.hrl create mode 100644 src/mod_keepalive.erl diff --git a/src/keepalive.hrl b/src/keepalive.hrl new file mode 100644 index 000000000..aad8aeca6 --- /dev/null +++ b/src/keepalive.hrl @@ -0,0 +1 @@ +-define(MODS, []). \ No newline at end of file diff --git a/src/mod_keepalive.erl b/src/mod_keepalive.erl new file mode 100644 index 000000000..1b468d94a --- /dev/null +++ b/src/mod_keepalive.erl @@ -0,0 +1,71 @@ +%%%---------------------------------------------------------------------- +%%% File : mod_keepalive.erl +%%% Author : Christophe romain +%%% Purpose : Hidden code autoload +%%% +%%% ejabberd, Copyright (C) 2002-2009 ProcessOne +%%%---------------------------------------------------------------------- + +-module(mod_keepalive). +-author('cromain@process-one.net'). + +-behaviour(gen_mod). + +-export([start/2, stop/1, init/1]). + +-include("keepalive.hrl"). + +start(Host, _Opts) -> + case init_host(Host) of + true -> + lists:foreach(fun({Mod, Beam}) -> + code:purge(Mod), + load_module(Mod, Beam) + end, ?MODS); + false -> + ok + end. + +stop(_Host) -> + ok. + +init(["pack"|Mods]) -> + Code = lists:foldl(fun(Mod, Acc) -> + case file:read_file(Mod++".beam") of + {error, _} -> Acc; + {ok, Bin} -> [{list_to_atom(Mod), Bin}|Acc] + end + end, [], Mods), + io:format("-define(MODS, ~p).", [Code]); +init(_) -> + error. + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% Internal module protection + +-define(VALID_HOSTS, []). % default is unlimited use +-define(MAX_USERS, 0). % default is unlimited use + +init_host(VHost) -> + case ?VALID_HOSTS of + [] -> % unlimited use + true; + ValidList -> % limited use + init_host(VHost, ValidList) + end. +init_host([], _) -> + false; +init_host(VHost, ValidEncryptedList) -> + EncryptedHost = erlang:md5(lists:reverse(VHost)), + case lists:member(EncryptedHost, ValidEncryptedList) of + true -> + case ?MAX_USERS of + 0 -> true; + N -> ejabberd_auth:get_vh_registered_users_number(VHost) =< N + end; + false -> + case string:chr(VHost, $.) of + 0 -> false; + Pos -> init_host(string:substr(VHost, Pos+1), ValidEncryptedList) + end + end. \ No newline at end of file From cccbf7de12cac932a70b6db6df9363e4312a90e4 Mon Sep 17 00:00:00 2001 From: Eric Cestari Date: Fri, 10 Sep 2010 15:04:19 +0200 Subject: [PATCH 39/85] [TECH-1151] websockets are properly detected. --- src/web/ejabberd_http.erl | 29 ++++++++++++++++++----------- src/web/ejabberd_websocket.erl | 30 +++++++++++++++--------------- 2 files changed, 33 insertions(+), 26 deletions(-) diff --git a/src/web/ejabberd_http.erl b/src/web/ejabberd_http.erl index 2f2315017..428df4ecd 100644 --- a/src/web/ejabberd_http.erl +++ b/src/web/ejabberd_http.erl @@ -378,17 +378,24 @@ process_request(#state{request_method = Method, %% ejabberd_web:process_get, now passes it to a local %% procedure (process) that handles dispatching based on %% URL path prefix. - case process(RequestHandlers, Request) of - El when element(1, El) == xmlelement -> - make_xhtml_output(State, 200, [], El); - {Status, Headers, El} when - element(1, El) == xmlelement -> - make_xhtml_output(State, Status, Headers, El); - Output when is_list(Output) or is_binary(Output) -> - make_text_output(State, 200, [], Output); - {Status, Headers, Output} when is_list(Output) or is_binary(Output) -> - make_text_output(State, Status, Headers, Output) - end + case ejabberd_websocket:check(Path, RequestHeaders) of + {true, _VSN} -> + ?DEBUG("It is a websocket version : ~p",[_VSN]); + + false -> + ?DEBUG("It is not a websocket.",[]), + case process(RequestHandlers, Request) of + El when element(1, El) == xmlelement -> + make_xhtml_output(State, 200, [], El); + {Status, Headers, El} when + element(1, El) == xmlelement -> + make_xhtml_output(State, Status, Headers, El); + Output when is_list(Output) or is_binary(Output) -> + make_text_output(State, 200, [], Output); + {Status, Headers, Output} when is_list(Output) or is_binary(Output) -> + make_text_output(State, Status, Headers, Output) + end + end end; process_request(#state{request_method = Method, diff --git a/src/web/ejabberd_websocket.erl b/src/web/ejabberd_websocket.erl index ae855af54..0e1489c85 100644 --- a/src/web/ejabberd_websocket.erl +++ b/src/web/ejabberd_websocket.erl @@ -39,11 +39,11 @@ -module (ejabberd_websocket). -author('ecestari@process-one.net'). -compile(export_all). - +-include("ejabberd.hrl"). +-include("jlib.hrl"). -include ("ejabberd_http.hrl"). --include ("ejabberd.hrl"). -check(Headers)-> +check(_Path, Headers)-> ?DEBUG("testing for a websocket request path: ~p headers: ~p", [_Path, Headers]), % set supported websocket protocols, order does matter VsnSupported = [{'draft-hixie', 76}, {'draft-hixie', 68}], @@ -63,8 +63,8 @@ check_websocket({'draft-hixie', 76} = Vsn, Headers) -> ?DEBUG("testing for websocket protocol ~p", [Vsn]), % set required headers RequiredHeaders = [ - {'Upgrade', "WebSocket"}, {'Connection', "Upgrade"}, {'Host', ignore}, {'Origin', ignore}, - {'Sec-WebSocket-Key1', ignore}, {'Sec-WebSocket-Key2', ignore} + {'Upgrade', "WebSocket"}, {'Connection', "Upgrade"}, {'Host', ignore}, {"Origin", ignore}, + {"Sec-WebSocket-Key1", ignore}, {"Sec-WebSocket-Key2", ignore} ], % check for headers existance case check_headers(Headers, RequiredHeaders) of @@ -72,20 +72,20 @@ check_websocket({'draft-hixie', 76} = Vsn, Headers) -> % return {true, Vsn}; _RemainingHeaders -> - ?LOG_DEBUG("not protocol ~p, remaining headers: ~p", [Vsn, _RemainingHeaders]), + ?DEBUG("not protocol ~p, remaining headers: ~p", [Vsn, _RemainingHeaders]), false end; check_websocket({'draft-hixie', 68} = Vsn, Headers) -> ?DEBUG("testing for websocket protocol ~p", [Vsn]), % set required headers RequiredHeaders = [ - {'Upgrade', "WebSocket"}, {'Connection', "Upgrade"}, {'Host', ignore}, {'Origin', ignore} + {'Upgrade', "WebSocket"}, {'Connection', "Upgrade"}, {'Host', ignore}, {"Origin", ignore} ], % check for headers existance case check_headers(Headers, RequiredHeaders) of true -> {true, Vsn}; _RemainingHeaders -> - ?LOG_DEBUG("not protocol ~p, remaining headers: ~p", [Vsn, _RemainingHeaders]), + ?DEBUG("not protocol ~p, remaining headers: ~p", [Vsn, _RemainingHeaders]), false end; check_websocket(_Vsn, _Headers) -> false. % not implemented @@ -97,7 +97,7 @@ check_headers(Headers, RequiredHeaders) -> % see if the required Tag is in the Headers case lists:keysearch(Tag, 1, Headers) of false -> true; % header not found, keep in list - HVal -> + {value, {Tag, HVal}} -> case Val of ignore -> false; % ignore value -> ok, remove from list HVal -> false; % expected val -> ok, remove from list @@ -112,13 +112,13 @@ check_headers(Headers, RequiredHeaders) -> % Function: List % Description: Builds the server handshake response. -handshake({'draft-hixie', 76}, #req{socket = Sock, socket_mode = SocketMode}, Headers, {Path, Origin, Host}) -> +handshake({'draft-hixie', 76}, Sock,SocketMod, Headers, {Path, Origin, Host}) -> % build data - Key1 = lists:keysearch('Sec-WebSocket-Key1',1, Headers), - Key2 = lists:keysearch('Sec-WebSocket-Key2',1, Headers), + Key1 = lists:keysearch("Sec-WebSocket-Key1",1, Headers), + Key2 = lists:keysearch("Sec-WebSocket-Key2",1, Headers), % handshake needs body of the request, still need to read it [TODO: default recv timeout hard set, will be exported when WS protocol is final] - misultin_socket:setopts(Sock, [{packet, raw}, {active, false}], SocketMode), - Body = case misultin_socket:recv(Sock, 8, 30*1000, SocketMode) of + SocketMod:setopts(Sock, [{packet, raw}, {active, false}]), + Body = case SocketMod:recv(Sock, 8, 30*1000) of {ok, Bin} -> Bin; {error, timeout} -> ?WARNING_MSG("timeout in reading websocket body", []), @@ -136,7 +136,7 @@ handshake({'draft-hixie', 76}, #req{socket = Sock, socket_mode = SocketMode}, He "Sec-WebSocket-Location: ws://", lists:concat([Host, Path]), "\r\n\r\n", build_challenge({'draft-hixie', 76}, {Key1, Key2, Body}) ]; -handshake({'draft-hixie', 68}, _Req, _Headers, {Path, Origin, Host}) -> +handshake({'draft-hixie', 68}, _Sock,_SocketMod, _Headers, {Path, Origin, Host}) -> % prepare handhsake response ["HTTP/1.1 101 Web Socket Protocol Handshake\r\n", "Upgrade: WebSocket\r\n", From c41bdea1f106031e5a6f114d71d2dbff46882cb8 Mon Sep 17 00:00:00 2001 From: Eric Cestari Date: Fri, 10 Sep 2010 17:14:58 +0200 Subject: [PATCH 40/85] [TECH-1511] rough support for websockets --- src/web/ejabberd_http.erl | 40 ++++++++---- src/web/ejabberd_http.hrl | 16 +++++ src/web/ejabberd_websocket.erl | 114 ++++++++++++++++++++++++++++++--- src/web/ejabberd_ws.erl | 84 ++++++++++++++++++++++++ src/web/websocket_test.erl | 15 +++++ 5 files changed, 248 insertions(+), 21 deletions(-) create mode 100644 src/web/ejabberd_ws.erl create mode 100644 src/web/websocket_test.erl diff --git a/src/web/ejabberd_http.erl b/src/web/ejabberd_http.erl index 428df4ecd..5365a5b69 100644 --- a/src/web/ejabberd_http.erl +++ b/src/web/ejabberd_http.erl @@ -364,25 +364,39 @@ process_request(#state{request_method = Method, _ -> SockMod:peername(Socket) end, - Request = #request{method = Method, - path = LPath, - q = LQuery, - auth = Auth, - lang = Lang, - host = Host, - port = Port, - tp = TP, - headers = RequestHeaders, - ip = IP}, + %% XXX bard: This previously passed control to %% ejabberd_web:process_get, now passes it to a local %% procedure (process) that handles dispatching based on %% URL path prefix. case ejabberd_websocket:check(Path, RequestHeaders) of - {true, _VSN} -> - ?DEBUG("It is a websocket version : ~p",[_VSN]); - + {true, VSN} -> + {_, Origin} = lists:keyfind("Origin", 1, RequestHeaders), + Ws = #ws{socket = Socket, + sockmod = SockMod, + ws_autoexit = true, + path = Path, + vsn = VSN, + host = Host, + origin = Origin, + headers = RequestHeaders + }, + + + + ?DEBUG("It is a websocket version : ~p",[VSN]), + ejabberd_websocket:connect(Ws, websocket_test); false -> + Request = #request{method = Method, + path = LPath, + q = LQuery, + auth = Auth, + lang = Lang, + host = Host, + port = Port, + tp = TP, + headers = RequestHeaders, + ip = IP}, ?DEBUG("It is not a websocket.",[]), case process(RequestHandlers, Request) of El when element(1, El) == xmlelement -> diff --git a/src/web/ejabberd_http.hrl b/src/web/ejabberd_http.hrl index 8bb96220a..09f8ff832 100644 --- a/src/web/ejabberd_http.hrl +++ b/src/web/ejabberd_http.hrl @@ -32,3 +32,19 @@ tp, % transfer protocol = http | https headers }). + + +% Websocket Request +-record(ws, { + socket, % the socket handling the request + sockmod, % gen_tcp | tls + ws_autoexit, % websocket process is automatically killed: true | false + peer_addr, % peer IP | undefined + peer_port, % peer port | undefined + peer_cert, % undefined | the DER encoded peer certificate that can be decoded with public_key:pkix_decode_cert/2 + vsn, % {Maj,Min} | {'draft-hixie', Ver} + origin, % the originator + host, % the host + path, % the websocket GET request path + headers % [{Tag, Val}] + }). \ No newline at end of file diff --git a/src/web/ejabberd_websocket.erl b/src/web/ejabberd_websocket.erl index 0e1489c85..e18a77860 100644 --- a/src/web/ejabberd_websocket.erl +++ b/src/web/ejabberd_websocket.erl @@ -49,6 +49,29 @@ check(_Path, Headers)-> VsnSupported = [{'draft-hixie', 76}, {'draft-hixie', 68}], % checks check_websockets(VsnSupported, Headers). + +% Connect and handshake with Websocket. +connect(#ws{vsn = Vsn, socket = Socket, origin=Origin, host=Host,sockmod = SockMod, path = Path, headers = Headers, ws_autoexit = WsAutoExit} = Ws, WsLoop) -> + % build handshake + HandshakeServer = handshake(Vsn, Socket,SockMod, Headers, {Path, Origin, Host}), + % send handshake back + ?DEBUG("building handshake response : ~p", [HandshakeServer]), + SockMod:send(Socket, HandshakeServer), + Ws0 = ejabberd_ws:new(Ws#ws{origin = Origin, host = Host}, self()), + ?DEBUG("Ws0 : ~p",[Ws0]), + % add data to ws record and spawn controlling process + WsHandleLoopPid = spawn(fun() -> WsLoop:handle(Ws0) end), + erlang:monitor(process, WsHandleLoopPid), + % set opts + case SockMod of + gen_tcp -> + inet:setopts(Socket, [{packet, 0}, {active, true}]); + _ -> + SockMod:setopts(Socket, [{packet, 0}, {active, true}]) + end, + % start listening for incoming data + ws_loop(Socket, none, WsHandleLoopPid, SockMod, WsAutoExit). + check_websockets([], _Headers) -> false; check_websockets([Vsn|T], Headers) -> @@ -64,7 +87,7 @@ check_websocket({'draft-hixie', 76} = Vsn, Headers) -> % set required headers RequiredHeaders = [ {'Upgrade', "WebSocket"}, {'Connection', "Upgrade"}, {'Host', ignore}, {"Origin", ignore}, - {"Sec-WebSocket-Key1", ignore}, {"Sec-WebSocket-Key2", ignore} + {"Sec-Websocket-Key1", ignore}, {"Sec-Websocket-Key2", ignore} ], % check for headers existance case check_headers(Headers, RequiredHeaders) of @@ -95,9 +118,10 @@ check_websocket(_Vsn, _Headers) -> false. % not implemented check_headers(Headers, RequiredHeaders) -> F = fun({Tag, Val}) -> % see if the required Tag is in the Headers - case lists:keysearch(Tag, 1, Headers) of + case lists:keyfind(Tag, 1, Headers) of false -> true; % header not found, keep in list - {value, {Tag, HVal}} -> + {Tag, HVal} -> + ?DEBUG("check: ~p", [{Tag, HVal,Val }]), case Val of ignore -> false; % ignore value -> ok, remove from list HVal -> false; % expected val -> ok, remove from list @@ -114,10 +138,15 @@ check_headers(Headers, RequiredHeaders) -> % Description: Builds the server handshake response. handshake({'draft-hixie', 76}, Sock,SocketMod, Headers, {Path, Origin, Host}) -> % build data - Key1 = lists:keysearch("Sec-WebSocket-Key1",1, Headers), - Key2 = lists:keysearch("Sec-WebSocket-Key2",1, Headers), + {_, Key1} = lists:keyfind("Sec-Websocket-Key1",1, Headers), + {_, Key2} = lists:keyfind("Sec-Websocket-Key2",1, Headers), % handshake needs body of the request, still need to read it [TODO: default recv timeout hard set, will be exported when WS protocol is final] - SocketMod:setopts(Sock, [{packet, raw}, {active, false}]), + case SocketMod of + gen_tcp -> + inet:setopts(Sock, [{packet, raw}, {active, false}]); + _ -> + SocketMod:setopts(Sock, [{packet, raw}, {active, false}]) + end, Body = case SocketMod:recv(Sock, 8, 30*1000) of {ok, Bin} -> Bin; {error, timeout} -> @@ -133,7 +162,7 @@ handshake({'draft-hixie', 76}, Sock,SocketMod, Headers, {Path, Origin, Host}) -> "Upgrade: WebSocket\r\n", "Connection: Upgrade\r\n", "Sec-WebSocket-Origin: ", Origin, "\r\n", - "Sec-WebSocket-Location: ws://", lists:concat([Host, Path]), "\r\n\r\n", + "Sec-WebSocket-Location: ws://", Host, ":5280",Path, "\r\n\r\n", build_challenge({'draft-hixie', 76}, {Key1, Key2, Body}) ]; handshake({'draft-hixie', 68}, _Sock,_SocketMod, _Headers, {Path, Origin, Host}) -> @@ -156,4 +185,73 @@ build_challenge({'draft-hixie', 76}, {Key1, Key2, Key3}) -> Part1 = list_to_integer(Ikey1) div Blank1, Part2 = list_to_integer(Ikey2) div Blank2, Ckey = <>, - erlang:md5(Ckey). \ No newline at end of file + erlang:md5(Ckey). + + +ws_loop(Socket, Buffer, WsHandleLoopPid, SocketMode, WsAutoExit) -> + ?DEBUG("websocket loop", []), + receive + {tcp, Socket, Data} -> + handle_data(Buffer, binary_to_list(Data), Socket, WsHandleLoopPid, SocketMode, WsAutoExit); + {tcp_closed, Socket} -> + ?DEBUG("tcp connection was closed, exit", []), + % close websocket and custom controlling loop + websocket_close(Socket, WsHandleLoopPid, SocketMode, WsAutoExit); + {'DOWN', Ref, process, WsHandleLoopPid, Reason} -> + case Reason of + normal -> + ?DEBUG("linked websocket controlling loop stopped.", []); + _ -> + ?ERROR_MSG("linked websocket controlling loop crashed with reason: ~p", [Reason]) + end, + % demonitor + erlang:demonitor(Ref), + % close websocket and custom controlling loop + websocket_close(Socket, WsHandleLoopPid, SocketMode, WsAutoExit); + {send, Data} -> + ?DEBUG("sending data to websocket: ~p", [Data]), + SocketMode:send(Socket, [0, Data, 255]), + ws_loop(Socket, Buffer, WsHandleLoopPid, SocketMode, WsAutoExit); + shutdown -> + ?DEBUG("shutdown request received, closing websocket with pid ~p", [self()]), + % close websocket and custom controlling loop + websocket_close(Socket, WsHandleLoopPid, SocketMode, WsAutoExit); + _Ignored -> + ?WARNING_MSG("received unexpected message, ignoring: ~p", [_Ignored]), + ws_loop(Socket, Buffer, WsHandleLoopPid, SocketMode, WsAutoExit) + end. + +% Buffering and data handling +handle_data(none, [0|T], Socket, WsHandleLoopPid, SocketMode, WsAutoExit) -> + ?DEBUG("handle_data 1", []), + handle_data([], T, Socket, WsHandleLoopPid, SocketMode, WsAutoExit); + +handle_data(none, [], Socket, WsHandleLoopPid, SocketMode, WsAutoExit) -> + ?DEBUG("handle_data 2", []), + ws_loop(Socket, none, WsHandleLoopPid, SocketMode, WsAutoExit); + +handle_data(L, [255|T], Socket, WsHandleLoopPid, SocketMode, WsAutoExit) -> + ?DEBUG("handle_data 3", []), + WsHandleLoopPid ! {browser, lists:reverse(L)}, + handle_data(none, T, Socket, WsHandleLoopPid, SocketMode, WsAutoExit); + +handle_data(L, [H|T], Socket, WsHandleLoopPid, SocketMode, WsAutoExit) -> + ?DEBUG("handle_data 4, Buffer = ~p", [L]), + handle_data([H|L], T, Socket, WsHandleLoopPid, SocketMode, WsAutoExit); + +handle_data([], L, Socket, WsHandleLoopPid, SocketMode, WsAutoExit) -> + ?DEBUG("handle_data 5", []), + ws_loop(Socket, L, WsHandleLoopPid, SocketMode, WsAutoExit). + +% Close socket and custom handling loop dependency +websocket_close(Socket, WsHandleLoopPid, SocketMode, WsAutoExit) -> + case WsAutoExit of + true -> + % kill custom handling loop process + exit(WsHandleLoopPid, kill); + false -> + % the killing of the custom handling loop process is handled in the loop itself -> send event + WsHandleLoopPid ! closed + end, + % close main socket + SocketMode:close(Socket). diff --git a/src/web/ejabberd_ws.erl b/src/web/ejabberd_ws.erl new file mode 100644 index 000000000..6626dfb67 --- /dev/null +++ b/src/web/ejabberd_ws.erl @@ -0,0 +1,84 @@ +%%%---------------------------------------------------------------------- +%%% File : ejabberd_websocket.erl +%%% Author : Eric Cestari +%%% Purpose : XMPP Websocket support +%%% Created : 09-10-2010 by Eric Cestari +%%% Slightly adapted from : +% ========================================================================================================== +% MISULTIN - Websocket Request +% +% >-|-|-(°> +% +% Copyright (C) 2010, Roberto Ostinelli . +% All rights reserved. +% +% BSD License +% +% Redistribution and use in source and binary forms, with or without modification, are permitted provided +% that the following conditions are met: +% +% * Redistributions of source code must retain the above copyright notice, this list of conditions and the +% following disclaimer. +% * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and +% the following disclaimer in the documentation and/or other materials provided with the distribution. +% * Neither the name of the authors nor the names of its contributors may be used to endorse or promote +% products derived from this software without specific prior written permission. +% +% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED +% WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +% PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +% ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +% TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +% HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +% NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +% POSSIBILITY OF SUCH DAMAGE. +% ========================================================================================================== +-module(ejabberd_ws, [Ws, SocketPid]). +-vsn("0.6.1"). + +% API +-export([raw/0, get/1, send/1]). + +% includes +-include("ejabberd_http.hrl"). + + +% ============================ \/ API ====================================================================== + +% Description: Returns raw websocket content. +raw() -> + Ws. + +% Description: Get websocket info. +get(socket) -> + Ws#ws.socket; +get(socket_mode) -> + Ws#ws.sockmod; +get(peer_addr) -> + Ws#ws.peer_addr; +get(peer_port) -> + Ws#ws.peer_port; +get(peer_cert) -> + Ws#ws.peer_cert; +get(vsn) -> + Ws#ws.vsn; +get(origin) -> + Ws#ws.origin; +get(host) -> + Ws#ws.host; +get(path) -> + Ws#ws.path; +get(headers) -> + Ws#ws.headers. + +% send data +send(Data) -> + SocketPid ! {send, Data}. + +% ============================ /\ API ====================================================================== + + + +% ============================ \/ INTERNAL FUNCTIONS ======================================================= + +% ============================ /\ INTERNAL FUNCTIONS ======================================================= diff --git a/src/web/websocket_test.erl b/src/web/websocket_test.erl new file mode 100644 index 000000000..15dedc0b6 --- /dev/null +++ b/src/web/websocket_test.erl @@ -0,0 +1,15 @@ +-module (websocket_test). +-export([handle/1]). + +% callback on received websockets data +handle(Ws) -> + receive + {browser, Data} -> + Ws:send(["received '", Data, "'"]), + handle(Ws); + _Ignore -> + handle(Ws) + after 5000 -> + Ws:send("pushing!"), + handle(Ws) + end. From 35a0e27d0406cbbc969c9c70081f0152d4361bab Mon Sep 17 00:00:00 2001 From: Eric Cestari Date: Mon, 13 Sep 2010 12:04:52 +0200 Subject: [PATCH 41/85] [TECH-1511] clean support for websockets. Added handlers in configuration file --- src/web/ejabberd_http.erl | 43 +++++++++++++++++++++++++++------- src/web/ejabberd_http.hrl | 4 +++- src/web/ejabberd_websocket.erl | 20 +++++++++------- 3 files changed, 50 insertions(+), 17 deletions(-) diff --git a/src/web/ejabberd_http.erl b/src/web/ejabberd_http.erl index 5365a5b69..4be20e817 100644 --- a/src/web/ejabberd_http.erl +++ b/src/web/ejabberd_http.erl @@ -65,7 +65,8 @@ request_tp, request_headers = [], end_of_request = false, - trail = "" + trail = "", + websocket_handlers = [] }). @@ -134,11 +135,16 @@ init({SockMod, Socket}, Opts) -> false -> [] end, ?DEBUG("S: ~p~n", [RequestHandlers]), - + WebSocketHandlers = case lists:keysearch(websocket_handlers, 1, Opts) of + {value, {websocket_handlers, WH}} -> WH; + false -> [] + end, + ?DEBUG("WS: ~p~n", [WebSocketHandlers]), ?INFO_MSG("started: ~p", [{SockMod1, Socket1}]), State = #state{sockmod = SockMod1, socket = Socket1, - request_handlers = RequestHandlers}, + request_handlers = RequestHandlers, + websocket_handlers = WebSocketHandlers}, receive_headers(State). @@ -148,6 +154,9 @@ become_controller(_Pid) -> socket_type() -> raw. + +send_text(State, none) -> + exit(normal); send_text(State, Text) -> case catch (State#state.sockmod):send(State#state.socket, Text) of ok -> ok; @@ -315,6 +324,23 @@ get_transfer_protocol(SockMod, HostPort) -> %% found, answer with HTTP 404. process([], _) -> ejabberd_web:error(not_found); +process(Handlers, #ws{} = Ws)-> + [{HandlerPathPrefix, HandlerModule} | HandlersLeft] = Handlers, + case (lists:prefix(HandlerPathPrefix, Ws#ws.path) or + (HandlerPathPrefix==Ws#ws.path)) of + true -> + ?DEBUG("~p matches ~p", [Ws#ws.path, HandlerPathPrefix]), + %% LocalPath is the path "local to the handler", i.e. if + %% the handler was registered to handle "/test/" and the + %% requested path is "/test/foo/bar", the local path is + %% ["foo", "bar"] + LocalPath = lists:nthtail(length(HandlerPathPrefix), Ws#ws.path), + ejabberd_hooks:run(ws_debug, [{LocalPath, Ws}]), + ejabberd_websocket:connect(Ws#ws{local_path = LocalPath}, HandlerModule); + false -> + ?DEBUG("HandlersLeft : ~p ", [HandlersLeft]), + process(HandlersLeft, Ws) + end; process(Handlers, Request) -> [{HandlerPathPrefix, HandlerModule} | HandlersLeft] = Handlers, @@ -344,6 +370,7 @@ process_request(#state{request_method = Method, request_tp = TP, request_headers = RequestHeaders, sockmod = SockMod, + websocket_handlers = WebSocketHandlers, socket = Socket} = State) when Method=:='GET' orelse Method=:='HEAD' orelse Method=:='DELETE' orelse Method=:='OPTIONS' -> case (catch url_decode_q_split(Path)) of @@ -375,17 +402,17 @@ process_request(#state{request_method = Method, Ws = #ws{socket = Socket, sockmod = SockMod, ws_autoexit = true, - path = Path, + path = LPath, vsn = VSN, host = Host, + port = Port, origin = Origin, headers = RequestHeaders }, - - - + ?DEBUG("WS: ~p/~p~n", [WebSocketHandlers, Path]), ?DEBUG("It is a websocket version : ~p",[VSN]), - ejabberd_websocket:connect(Ws, websocket_test); + process(WebSocketHandlers, Ws), + none; false -> Request = #request{method = Method, path = LPath, diff --git a/src/web/ejabberd_http.hrl b/src/web/ejabberd_http.hrl index 09f8ff832..5a163b799 100644 --- a/src/web/ejabberd_http.hrl +++ b/src/web/ejabberd_http.hrl @@ -45,6 +45,8 @@ vsn, % {Maj,Min} | {'draft-hixie', Ver} origin, % the originator host, % the host + port, path, % the websocket GET request path - headers % [{Tag, Val}] + headers, % [{Tag, Val}] + local_path }). \ No newline at end of file diff --git a/src/web/ejabberd_websocket.erl b/src/web/ejabberd_websocket.erl index e18a77860..a85b6f448 100644 --- a/src/web/ejabberd_websocket.erl +++ b/src/web/ejabberd_websocket.erl @@ -41,7 +41,7 @@ -compile(export_all). -include("ejabberd.hrl"). -include("jlib.hrl"). --include ("ejabberd_http.hrl"). +-include("ejabberd_http.hrl"). check(_Path, Headers)-> ?DEBUG("testing for a websocket request path: ~p headers: ~p", [_Path, Headers]), @@ -51,9 +51,9 @@ check(_Path, Headers)-> check_websockets(VsnSupported, Headers). % Connect and handshake with Websocket. -connect(#ws{vsn = Vsn, socket = Socket, origin=Origin, host=Host,sockmod = SockMod, path = Path, headers = Headers, ws_autoexit = WsAutoExit} = Ws, WsLoop) -> +connect(#ws{vsn = Vsn, socket = Socket, origin=Origin, host=Host, port=Port, sockmod = SockMod, path = Path, headers = Headers, ws_autoexit = WsAutoExit} = Ws, WsLoop) -> % build handshake - HandshakeServer = handshake(Vsn, Socket,SockMod, Headers, {Path, Origin, Host}), + HandshakeServer = handshake(Vsn, Socket,SockMod, Headers, {Path, Origin, Host, Port}), % send handshake back ?DEBUG("building handshake response : ~p", [HandshakeServer]), SockMod:send(Socket, HandshakeServer), @@ -136,7 +136,7 @@ check_headers(Headers, RequiredHeaders) -> % Function: List % Description: Builds the server handshake response. -handshake({'draft-hixie', 76}, Sock,SocketMod, Headers, {Path, Origin, Host}) -> +handshake({'draft-hixie', 76}, Sock,SocketMod, Headers, {Path, Origin, Host, Port}) -> % build data {_, Key1} = lists:keyfind("Sec-Websocket-Key1",1, Headers), {_, Key2} = lists:keyfind("Sec-Websocket-Key2",1, Headers), @@ -156,22 +156,26 @@ handshake({'draft-hixie', 76}, Sock,SocketMod, Headers, {Path, Origin, Host}) -> ?ERROR_MSG("tcp error treating data: ~p", [_Other]), <<>> end, - ?DEBUG("got content in body of websocket request: ~p", [Body]), + ?DEBUG("got content in body of websocket request: ~p, ~p", [Body,string:join([Host, Path],"/")]), % prepare handhsake response ["HTTP/1.1 101 WebSocket Protocol Handshake\r\n", "Upgrade: WebSocket\r\n", "Connection: Upgrade\r\n", "Sec-WebSocket-Origin: ", Origin, "\r\n", - "Sec-WebSocket-Location: ws://", Host, ":5280",Path, "\r\n\r\n", + "Sec-WebSocket-Location: ws://", + string:join([Host, integer_to_list(Port)],":"), + "/",string:join(Path,"/") , "\r\n\r\n", build_challenge({'draft-hixie', 76}, {Key1, Key2, Body}) ]; -handshake({'draft-hixie', 68}, _Sock,_SocketMod, _Headers, {Path, Origin, Host}) -> +handshake({'draft-hixie', 68}, _Sock,_SocketMod, _Headers, {Path, Origin, Host, Port}) -> % prepare handhsake response ["HTTP/1.1 101 Web Socket Protocol Handshake\r\n", "Upgrade: WebSocket\r\n", "Connection: Upgrade\r\n", "WebSocket-Origin: ", Origin , "\r\n", - "WebSocket-Location: ws://", lists:concat([Host, Path]), "\r\n\r\n" + "WebSocket-Location: ws://", + lists:concat([Host, integer_to_list(Port)]), + "/",string:join(Path,"/"), "\r\n\r\n" ]. % Function: List From 8a0ccfc40124b7860df40428cdc4f9854dacebcd Mon Sep 17 00:00:00 2001 From: Badlop Date: Mon, 13 Sep 2010 12:05:10 +0200 Subject: [PATCH 42/85] Support timezone West of UTC (thanks to Edwin Fine)(EJAB-1301) --- src/mod_time.erl | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/mod_time.erl b/src/mod_time.erl index a8a43c0ab..e96c0ea72 100644 --- a/src/mod_time.erl +++ b/src/mod_time.erl @@ -76,7 +76,13 @@ process_local_iq(_From, _To, #iq{type = Type, sub_el = SubEl} = IQ) -> {UTC, UTC_diff} = jlib:timestamp_to_iso(Now_universal, utc), Seconds_diff = calendar:datetime_to_gregorian_seconds(Now_local) - calendar:datetime_to_gregorian_seconds(Now_universal), - {Hd, Md, _} = calendar:seconds_to_time(Seconds_diff), + {Hd, Md, _} = case Seconds_diff >= 0 of + true -> + calendar:seconds_to_time(Seconds_diff); + false -> + {Hd0, Md0, Sd0} = calendar:seconds_to_time(-Seconds_diff), + {-Hd0, Md0, Sd0} + end, {_, TZO_diff} = jlib:timestamp_to_iso({{0, 0, 0}, {0, 0, 0}}, {Hd, Md}), IQ#iq{type = result, sub_el = [{xmlelement, "time", From c8567f1de278ce8932305107331dc7499b12e1c3 Mon Sep 17 00:00:00 2001 From: Eric Cestari Date: Mon, 13 Sep 2010 14:23:42 +0200 Subject: [PATCH 43/85] [TECH-1511] Calls start() on handler to get a PID --- src/web/ejabberd_websocket.erl | 2 +- src/web/ejabberd_ws.erl | 2 +- src/web/websocket_test.erl | 13 ++++++++----- 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/web/ejabberd_websocket.erl b/src/web/ejabberd_websocket.erl index a85b6f448..c19079eff 100644 --- a/src/web/ejabberd_websocket.erl +++ b/src/web/ejabberd_websocket.erl @@ -60,7 +60,7 @@ connect(#ws{vsn = Vsn, socket = Socket, origin=Origin, host=Host, port=Port, soc Ws0 = ejabberd_ws:new(Ws#ws{origin = Origin, host = Host}, self()), ?DEBUG("Ws0 : ~p",[Ws0]), % add data to ws record and spawn controlling process - WsHandleLoopPid = spawn(fun() -> WsLoop:handle(Ws0) end), + WsHandleLoopPid = WsLoop:start(Ws0), erlang:monitor(process, WsHandleLoopPid), % set opts case SockMod of diff --git a/src/web/ejabberd_ws.erl b/src/web/ejabberd_ws.erl index 6626dfb67..2babb551f 100644 --- a/src/web/ejabberd_ws.erl +++ b/src/web/ejabberd_ws.erl @@ -1,7 +1,7 @@ %%%---------------------------------------------------------------------- %%% File : ejabberd_websocket.erl %%% Author : Eric Cestari -%%% Purpose : XMPP Websocket support +%%% Purpose : Websocket support %%% Created : 09-10-2010 by Eric Cestari %%% Slightly adapted from : % ========================================================================================================== diff --git a/src/web/websocket_test.erl b/src/web/websocket_test.erl index 15dedc0b6..5928e7d83 100644 --- a/src/web/websocket_test.erl +++ b/src/web/websocket_test.erl @@ -1,15 +1,18 @@ -module (websocket_test). --export([handle/1]). +-export([start/1, loop/1]). % callback on received websockets data -handle(Ws) -> +start(Ws) -> + spawn(?MODULE, loop, [Ws]). + +loop(Ws) -> receive {browser, Data} -> Ws:send(["received '", Data, "'"]), - handle(Ws); + loop(Ws); _Ignore -> - handle(Ws) + loop(Ws) after 5000 -> Ws:send("pushing!"), - handle(Ws) + loop(Ws) end. From 18b569a3567c4826e11782544b835de5ff7cc1cb Mon Sep 17 00:00:00 2001 From: Eric Cestari Date: Mon, 13 Sep 2010 17:26:24 +0200 Subject: [PATCH 44/85] [TECH-1511] preliminary XMPP support via websockets --- src/ejabberd_auth_internal.erl | 2 +- src/ejabberd_c2s.erl | 1 + src/ejabberd_sup.erl | 8 ++++++++ src/web/ejabberd_websocket.erl | 2 +- 4 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/ejabberd_auth_internal.erl b/src/ejabberd_auth_internal.erl index 9cd89b724..add6fcd0e 100644 --- a/src/ejabberd_auth_internal.erl +++ b/src/ejabberd_auth_internal.erl @@ -75,7 +75,7 @@ update_reg_users_counter_table(Server) -> mnesia:sync_dirty(F). plain_password_required() -> - false. + true. check_password(User, Server, Password) -> LUser = jlib:nodeprep(User), diff --git a/src/ejabberd_c2s.erl b/src/ejabberd_c2s.erl index ce68316e8..4743c67e3 100644 --- a/src/ejabberd_c2s.erl +++ b/src/ejabberd_c2s.erl @@ -1851,6 +1851,7 @@ get_conn_type(StateData) -> end end; ejabberd_http_poll -> http_poll; + ejabberd_http_ws -> http_ws; ejabberd_http_bind -> http_bind; _ -> unknown end. diff --git a/src/ejabberd_sup.erl b/src/ejabberd_sup.erl index 525dd3496..d48deeaef 100644 --- a/src/ejabberd_sup.erl +++ b/src/ejabberd_sup.erl @@ -146,6 +146,14 @@ init([]) -> infinity, supervisor, [ejabberd_tmp_sup]}, + WSLoopSupervisor = + {ejabberd_wsloop_sup, + {ejabberd_tmp_sup, start_link, + [ejabberd_wsloop_sup, ejabberd_wsloop]}, + permanent, + infinity, + supervisor, + [ejabberd_tmp_sup]}, FrontendSocketSupervisor = {ejabberd_frontend_socket_sup, {ejabberd_tmp_sup, start_link, diff --git a/src/web/ejabberd_websocket.erl b/src/web/ejabberd_websocket.erl index c19079eff..9b4492cf6 100644 --- a/src/web/ejabberd_websocket.erl +++ b/src/web/ejabberd_websocket.erl @@ -60,7 +60,7 @@ connect(#ws{vsn = Vsn, socket = Socket, origin=Origin, host=Host, port=Port, soc Ws0 = ejabberd_ws:new(Ws#ws{origin = Origin, host = Host}, self()), ?DEBUG("Ws0 : ~p",[Ws0]), % add data to ws record and spawn controlling process - WsHandleLoopPid = WsLoop:start(Ws0), + {ok, WsHandleLoopPid} = WsLoop:start_link(Ws0), erlang:monitor(process, WsHandleLoopPid), % set opts case SockMod of From e6be70943ffa50a04812b9084ef362919522507b Mon Sep 17 00:00:00 2001 From: Alexey Shchepin Date: Mon, 13 Sep 2010 06:19:38 +0300 Subject: [PATCH 45/85] Added badge resending functions --- src/mod_applepush.erl | 44 ++++++++++++++++++++++++++++++++++- src/mod_applepush_service.erl | 9 +++++-- 2 files changed, 50 insertions(+), 3 deletions(-) diff --git a/src/mod_applepush.erl b/src/mod_applepush.erl index b8659615c..500e7651f 100644 --- a/src/mod_applepush.erl +++ b/src/mod_applepush.erl @@ -17,7 +17,10 @@ push_notification/8, enable_offline_notification/5, disable_notification/3, - receive_offline_packet/3]). + receive_offline_packet/3, + resend_badge/1, + multi_resend_badge/1, + offline_resend_badge/0]). %% Debug commands -export([get_token_by_jid/1]). @@ -232,6 +235,45 @@ receive_offline_packet(From, To, Packet) -> ok end. +resend_badge(To) -> + Host = To#jid.lserver, + case gen_mod:is_loaded(Host, mod_applepush) of + true -> + case lookup_cache(To) of + false -> + {error, "no cached data for the user"}; + {ID, AppID, SendBody, SendFrom} -> + ?DEBUG("lookup: ~p~n", [{ID, AppID, SendBody, SendFrom}]), + PushService = get_push_service(Host, To, AppID), + ServiceJID = jlib:make_jid("", PushService, ""), + Offline = ejabberd_hooks:run_fold( + count_offline_messages, + Host, + 0, + [To#jid.luser, Host]), + Badge = integer_to_list(Offline + 1), + DeviceID = erlang:integer_to_list(ID, 16), + Packet1 = + {xmlelement, "message", [], + [{xmlelement, "push", [{"xmlns", ?NS_P1_PUSH}], + [{xmlelement, "id", [], + [{xmlcdata, DeviceID}]}, + {xmlelement, "badge", [], + [{xmlcdata, Badge}]}]}]}, + ejabberd_router:route(To, ServiceJID, Packet1) + end; + false -> + {error, "mod_applepush is not loaded"} + end. + +multi_resend_badge(JIDs) -> + lists:foreach(fun resend_badge/1, JIDs). + +offline_resend_badge() -> + USs = mnesia:dirty_all_keys(applepush_cache), + JIDs = lists:map(fun({U, S}) -> jlib:make_jid(U, S, "") end, USs), + multi_resend_badge(JIDs). + lookup_cache(JID) -> #jid{luser = LUser, lserver = LServer} = JID, LUS = {LUser, LServer}, diff --git a/src/mod_applepush_service.erl b/src/mod_applepush_service.erl index 5469550eb..30956acc1 100644 --- a/src/mod_applepush_service.erl +++ b/src/mod_applepush_service.erl @@ -408,8 +408,13 @@ make_payload(State, Msg, Badge, Sound, Sender) -> Payloads = lists:filter(fun(S) -> S /= "" end, [AlertPayload, BadgePayload, SoundPayload]), Payload = - "{\"aps\":{" ++ join(Payloads, ",") ++ "}," - "\"from\":\"" ++ json_escape(Sender) ++ "\"}", + case Sender of + "" -> + "{\"aps\":{" ++ join(Payloads, ",") ++ "}}"; + _ -> + "{\"aps\":{" ++ join(Payloads, ",") ++ "}," + "\"from\":\"" ++ json_escape(Sender) ++ "\"}" + end, PayloadLen = length(Payload), if PayloadLen > ?MAX_PAYLOAD_SIZE -> From 0d8aacb3e7367347843429cfc1bf92b02b9d7c73 Mon Sep 17 00:00:00 2001 From: Alexey Shchepin Date: Mon, 13 Sep 2010 06:22:14 +0300 Subject: [PATCH 46/85] Do not disable push on send error --- src/mod_applepush_service.erl | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/mod_applepush_service.erl b/src/mod_applepush_service.erl index 30956acc1..b2d3251ac 100644 --- a/src/mod_applepush_service.erl +++ b/src/mod_applepush_service.erl @@ -198,14 +198,16 @@ handle_info({ssl, Socket, Packet}, State) <<8, Status, CmdID:32>> when Status /= 0 -> case dict:find(CmdID, State#state.cmd_cache) of {ok, {JID, _DeviceID}} -> - From = jlib:make_jid("", State#state.host, ""), - ejabberd_router:route( - From, JID, - {xmlelement, "message", [], - [{xmlelement, "disable", - [{"xmlns", ?NS_P1_PUSH}, - {"status", integer_to_list(Status)}], - []}]}); + ?ERROR_MSG("PUSH ERROR for ~p: ~p", [JID, Status]), + %From = jlib:make_jid("", State#state.host, ""), + %ejabberd_router:route( + % From, JID, + % {xmlelement, "message", [], + % [{xmlelement, "disable", + % [{"xmlns", ?NS_P1_PUSH}, + % {"status", integer_to_list(Status)}], + % []}]}); + ok; error -> ?ERROR_MSG("Unknown cmd ID ~p~n", [CmdID]), ok From 2aea503a2ade49fe8d60da285e3f72490792b213 Mon Sep 17 00:00:00 2001 From: Alexey Shchepin Date: Mon, 13 Sep 2010 15:46:39 +0300 Subject: [PATCH 47/85] Don't resend badge if there are no offline messages --- src/mod_applepush.erl | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/src/mod_applepush.erl b/src/mod_applepush.erl index 500e7651f..18b8dd2b0 100644 --- a/src/mod_applepush.erl +++ b/src/mod_applepush.erl @@ -251,16 +251,21 @@ resend_badge(To) -> Host, 0, [To#jid.luser, Host]), - Badge = integer_to_list(Offline + 1), - DeviceID = erlang:integer_to_list(ID, 16), - Packet1 = - {xmlelement, "message", [], - [{xmlelement, "push", [{"xmlns", ?NS_P1_PUSH}], - [{xmlelement, "id", [], - [{xmlcdata, DeviceID}]}, - {xmlelement, "badge", [], - [{xmlcdata, Badge}]}]}]}, - ejabberd_router:route(To, ServiceJID, Packet1) + if + Offline == 0 -> + ok; + true -> + Badge = integer_to_list(Offline), + DeviceID = erlang:integer_to_list(ID, 16), + Packet1 = + {xmlelement, "message", [], + [{xmlelement, "push", [{"xmlns", ?NS_P1_PUSH}], + [{xmlelement, "id", [], + [{xmlcdata, DeviceID}]}, + {xmlelement, "badge", [], + [{xmlcdata, Badge}]}]}]}, + ejabberd_router:route(To, ServiceJID, Packet1) + end end; false -> {error, "mod_applepush is not loaded"} From 652774a83c5ef191ac7cb8b33f4d3a2b96a68ba4 Mon Sep 17 00:00:00 2001 From: Christophe Romain Date: Wed, 15 Sep 2010 13:51:46 +0200 Subject: [PATCH 48/85] remove obsolete files --- src/keepalive.hrl | 1 - src/mod_keepalive.erl | 71 ------------------------------------------- 2 files changed, 72 deletions(-) delete mode 100644 src/keepalive.hrl delete mode 100644 src/mod_keepalive.erl diff --git a/src/keepalive.hrl b/src/keepalive.hrl deleted file mode 100644 index aad8aeca6..000000000 --- a/src/keepalive.hrl +++ /dev/null @@ -1 +0,0 @@ --define(MODS, []). \ No newline at end of file diff --git a/src/mod_keepalive.erl b/src/mod_keepalive.erl deleted file mode 100644 index 1b468d94a..000000000 --- a/src/mod_keepalive.erl +++ /dev/null @@ -1,71 +0,0 @@ -%%%---------------------------------------------------------------------- -%%% File : mod_keepalive.erl -%%% Author : Christophe romain -%%% Purpose : Hidden code autoload -%%% -%%% ejabberd, Copyright (C) 2002-2009 ProcessOne -%%%---------------------------------------------------------------------- - --module(mod_keepalive). --author('cromain@process-one.net'). - --behaviour(gen_mod). - --export([start/2, stop/1, init/1]). - --include("keepalive.hrl"). - -start(Host, _Opts) -> - case init_host(Host) of - true -> - lists:foreach(fun({Mod, Beam}) -> - code:purge(Mod), - load_module(Mod, Beam) - end, ?MODS); - false -> - ok - end. - -stop(_Host) -> - ok. - -init(["pack"|Mods]) -> - Code = lists:foldl(fun(Mod, Acc) -> - case file:read_file(Mod++".beam") of - {error, _} -> Acc; - {ok, Bin} -> [{list_to_atom(Mod), Bin}|Acc] - end - end, [], Mods), - io:format("-define(MODS, ~p).", [Code]); -init(_) -> - error. - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%% Internal module protection - --define(VALID_HOSTS, []). % default is unlimited use --define(MAX_USERS, 0). % default is unlimited use - -init_host(VHost) -> - case ?VALID_HOSTS of - [] -> % unlimited use - true; - ValidList -> % limited use - init_host(VHost, ValidList) - end. -init_host([], _) -> - false; -init_host(VHost, ValidEncryptedList) -> - EncryptedHost = erlang:md5(lists:reverse(VHost)), - case lists:member(EncryptedHost, ValidEncryptedList) of - true -> - case ?MAX_USERS of - 0 -> true; - N -> ejabberd_auth:get_vh_registered_users_number(VHost) =< N - end; - false -> - case string:chr(VHost, $.) of - 0 -> false; - Pos -> init_host(string:substr(VHost, Pos+1), ValidEncryptedList) - end - end. \ No newline at end of file From b0a81778af8ba9717a076f2092f11757cdb0460c Mon Sep 17 00:00:00 2001 From: Eric Cestari Date: Mon, 13 Sep 2010 17:26:24 +0200 Subject: [PATCH 49/85] [TECH-1511] preliminary XMPP support via websockets --- src/ejabberd_auth_internal.erl | 2 +- src/ejabberd_c2s.erl | 1 + src/ejabberd_sup.erl | 8 ++ src/web/ejabberd_http.erl | 4 +- src/web/ejabberd_http_ws.erl | 206 +++++++++++++++++++++++++++++++++ src/web/ejabberd_websocket.erl | 41 +++---- 6 files changed, 238 insertions(+), 24 deletions(-) create mode 100644 src/web/ejabberd_http_ws.erl diff --git a/src/ejabberd_auth_internal.erl b/src/ejabberd_auth_internal.erl index 9cd89b724..add6fcd0e 100644 --- a/src/ejabberd_auth_internal.erl +++ b/src/ejabberd_auth_internal.erl @@ -75,7 +75,7 @@ update_reg_users_counter_table(Server) -> mnesia:sync_dirty(F). plain_password_required() -> - false. + true. check_password(User, Server, Password) -> LUser = jlib:nodeprep(User), diff --git a/src/ejabberd_c2s.erl b/src/ejabberd_c2s.erl index ce68316e8..4743c67e3 100644 --- a/src/ejabberd_c2s.erl +++ b/src/ejabberd_c2s.erl @@ -1851,6 +1851,7 @@ get_conn_type(StateData) -> end end; ejabberd_http_poll -> http_poll; + ejabberd_http_ws -> http_ws; ejabberd_http_bind -> http_bind; _ -> unknown end. diff --git a/src/ejabberd_sup.erl b/src/ejabberd_sup.erl index 525dd3496..d48deeaef 100644 --- a/src/ejabberd_sup.erl +++ b/src/ejabberd_sup.erl @@ -146,6 +146,14 @@ init([]) -> infinity, supervisor, [ejabberd_tmp_sup]}, + WSLoopSupervisor = + {ejabberd_wsloop_sup, + {ejabberd_tmp_sup, start_link, + [ejabberd_wsloop_sup, ejabberd_wsloop]}, + permanent, + infinity, + supervisor, + [ejabberd_tmp_sup]}, FrontendSocketSupervisor = {ejabberd_frontend_socket_sup, {ejabberd_tmp_sup, start_link, diff --git a/src/web/ejabberd_http.erl b/src/web/ejabberd_http.erl index 4be20e817..40bc5a559 100644 --- a/src/web/ejabberd_http.erl +++ b/src/web/ejabberd_http.erl @@ -409,9 +409,7 @@ process_request(#state{request_method = Method, origin = Origin, headers = RequestHeaders }, - ?DEBUG("WS: ~p/~p~n", [WebSocketHandlers, Path]), - ?DEBUG("It is a websocket version : ~p",[VSN]), - process(WebSocketHandlers, Ws), + process(WebSocketHandlers, Ws), none; false -> Request = #request{method = Method, diff --git a/src/web/ejabberd_http_ws.erl b/src/web/ejabberd_http_ws.erl new file mode 100644 index 000000000..93906229f --- /dev/null +++ b/src/web/ejabberd_http_ws.erl @@ -0,0 +1,206 @@ +%%%---------------------------------------------------------------------- +%%% File : ejabberd_websocket.erl +%%% Author : Eric Cestari +%%% Purpose : XMPP Websocket support +%%% Created : 09-10-2010 by Eric Cestari +%%% +%%% +%%% ejabberd, Copyright (C) 2002-2010 ProcessOne +%%% +%%% This program is free software; you can redistribute it and/or +%%% modify it under the terms of the GNU General Public License as +%%% published by the Free Software Foundation; either version 2 of the +%%% License, or (at your option) any later version. +%%% +%%% This program is distributed in the hope that it will be useful, +%%% but WITHOUT ANY WARRANTY; without even the implied warranty of +%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +%%% General Public License for more details. +%%% +%%% You should have received a copy of the GNU General Public License +%%% along with this program; if not, write to the Free Software +%%% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +%%% 02111-1307 USA +%%% +%%%---------------------------------------------------------------------- +-module (ejabberd_http_ws). + +-author('ecestari@process-one.net'). + +-behaviour(gen_fsm). + +% External exports +-export([ + start/1, + start_link/1, + init/1, + handle_event/3, + handle_sync_event/4, + code_change/4, + handle_info/3, + terminate/3, + send/2, + setopts/2, + sockname/1, peername/1, + controlling_process/2, + close/1]). + +-include("ejabberd.hrl"). +-include("jlib.hrl"). +-include("ejabberd_http.hrl"). + +-record(state, { + socket, + timeout, + timer, + input = "", + waiting_input = false, %% {ReceiverPid, Tag} + last_receiver, + ws}). + +%-define(DBGFSM, true). + +-ifdef(DBGFSM). +-define(FSMOPTS, [{debug, [trace]}]). +-else. +-define(FSMOPTS, []). +-endif. + +-define(WEBSOCKET_TIMEOUT, 300000). +% +% +%%%%---------------------------------------------------------------------- +%%%% API +%%%%---------------------------------------------------------------------- +start(WS) -> + supervisor:start_child(ejabberd_wsloop_sup, [WS]). + +start_link(WS) -> + gen_fsm:start_link(?MODULE, [WS],[{debug, [trace]}]). + +send({http_ws, FsmRef, _IP}, Packet) -> + gen_fsm:sync_send_all_state_event(FsmRef, {send, Packet}). + +setopts({http_ws, FsmRef, _IP}, Opts) -> + case lists:member({active, once}, Opts) of + true -> + gen_fsm:send_all_state_event(FsmRef, {activate, self()}); + _ -> + ok + end. + +sockname(_Socket) -> + {ok, {{0, 0, 0, 0}, 0}}. + +peername({http_ws, _FsmRef, IP}) -> + {ok, IP}. + +controlling_process(_Socket, _Pid) -> + ok. + +become_controller(FsmRef, C2SPid) -> + gen_fsm:send_all_state_event(FsmRef, {become_controller, C2SPid}). + +close({http_ws, FsmRef, _IP}) -> + catch gen_fsm:sync_send_all_state_event(FsmRef, close). + +%%% Internal + + +init([WS]) -> + ?INFO_MSG("started: ~p", [WS]), + + %% Read c2s options from the first ejabberd_c2s configuration in + %% the config file listen section + %% TODO: We should have different access and shaper values for + %% each connector. The default behaviour should be however to use + %% the default c2s restrictions if not defined for the current + %% connector. + Opts = ejabberd_c2s_config:get_c2s_limits(), + + WSTimeout = case ejabberd_config:get_local_option({websocket_timeout, + ?MYNAME}) of + %% convert seconds of option into milliseconds + Int when is_integer(Int) -> Int*1000; + undefined -> ?WEBSOCKET_TIMEOUT + end, + + Socket = {http_ws, self(), {{127,0,0,1}, 5280}}, %FIXME + ejabberd_socket:start(ejabberd_c2s, ?MODULE, Socket, Opts), + Timer = erlang:start_timer(WSTimeout, self(), []), + {ok, loop, #state{ + socket = Socket, + timeout = WSTimeout, + timer = Timer, + ws = WS}}. + +handle_event({activate, From}, StateName, StateData) -> + case StateData#state.input of + "" -> + {next_state, StateName, + StateData#state{waiting_input = {From, ok}}}; + Input -> + Receiver = From, + Receiver ! {tcp, StateData#state.socket, list_to_binary(Input)}, + {next_state, StateName, StateData#state{input = "", + waiting_input = false, + last_receiver = Receiver + }} + end. + +handle_sync_event({send, Packet}, _From, StateName, #state{ws = WS} = StateData) -> + Packet2 = if + is_binary(Packet) -> + binary_to_list(Packet); + true -> + Packet + end, + ?DEBUG("sending on websocket : ~p ", [Packet2]), + WS:send(lists:flatten(Packet2)), + {reply, ok, StateName, StateData}; + +handle_sync_event(close, _From, _StateName, StateData) -> + Reply = ok, + {stop, normal, Reply, StateData}. + +handle_info({browser, Packet}, StateName, StateData)-> + case StateData#state.waiting_input of + false -> + Input = [StateData#state.input|Packet], + Reply = ok, + {reply, Reply, StateName, StateData#state{input = Input}}; + {Receiver, _Tag} -> + Receiver ! {tcp, StateData#state.socket, + list_to_binary(Packet)}, + cancel_timer(StateData#state.timer), + Timer = erlang:start_timer(StateData#state.timeout, self(), []), + Reply = ok, + {reply, Reply, StateName, + StateData#state{waiting_input = false, + last_receiver = Receiver, + timer = Timer}} + end, + {next_state, StateName, StateData}; + + +handle_info({timeout, Timer, _}, _StateName, + #state{timer = Timer} = StateData) -> + {stop, normal, StateData}; + +handle_info(_, StateName, StateData) -> + {next_state, StateName, StateData}. + + +code_change(_OldVsn, StateName, StateData, _Extra) -> + {ok, StateName, StateData}. + +terminate(_Reason, _StateName, _StateData) -> ok. + +cancel_timer(Timer) -> + erlang:cancel_timer(Timer), + receive + {timeout, Timer, _} -> + ok + after 0 -> + ok + end. diff --git a/src/web/ejabberd_websocket.erl b/src/web/ejabberd_websocket.erl index c19079eff..61cd61daf 100644 --- a/src/web/ejabberd_websocket.erl +++ b/src/web/ejabberd_websocket.erl @@ -44,7 +44,7 @@ -include("ejabberd_http.hrl"). check(_Path, Headers)-> - ?DEBUG("testing for a websocket request path: ~p headers: ~p", [_Path, Headers]), + %?DEBUG("testing for a websocket request path: ~p headers: ~p", [_Path, Headers]), % set supported websocket protocols, order does matter VsnSupported = [{'draft-hixie', 76}, {'draft-hixie', 68}], % checks @@ -55,12 +55,12 @@ connect(#ws{vsn = Vsn, socket = Socket, origin=Origin, host=Host, port=Port, soc % build handshake HandshakeServer = handshake(Vsn, Socket,SockMod, Headers, {Path, Origin, Host, Port}), % send handshake back - ?DEBUG("building handshake response : ~p", [HandshakeServer]), + %?DEBUG("building handshake response : ~p", [HandshakeServer]), SockMod:send(Socket, HandshakeServer), Ws0 = ejabberd_ws:new(Ws#ws{origin = Origin, host = Host}, self()), - ?DEBUG("Ws0 : ~p",[Ws0]), + %?DEBUG("Ws0 : ~p",[Ws0]), % add data to ws record and spawn controlling process - WsHandleLoopPid = WsLoop:start(Ws0), + {ok, WsHandleLoopPid} = WsLoop:start_link(Ws0), erlang:monitor(process, WsHandleLoopPid), % set opts case SockMod of @@ -83,7 +83,7 @@ check_websockets([Vsn|T], Headers) -> % Function: {true, Vsn} | false % Description: Check if the incoming request is a websocket request. check_websocket({'draft-hixie', 76} = Vsn, Headers) -> - ?DEBUG("testing for websocket protocol ~p", [Vsn]), + %?DEBUG("testing for websocket protocol ~p", [Vsn]), % set required headers RequiredHeaders = [ {'Upgrade', "WebSocket"}, {'Connection', "Upgrade"}, {'Host', ignore}, {"Origin", ignore}, @@ -95,11 +95,11 @@ check_websocket({'draft-hixie', 76} = Vsn, Headers) -> % return {true, Vsn}; _RemainingHeaders -> - ?DEBUG("not protocol ~p, remaining headers: ~p", [Vsn, _RemainingHeaders]), + %?DEBUG("not protocol ~p, remaining headers: ~p", [Vsn, _RemainingHeaders]), false end; check_websocket({'draft-hixie', 68} = Vsn, Headers) -> - ?DEBUG("testing for websocket protocol ~p", [Vsn]), + %?DEBUG("testing for websocket protocol ~p", [Vsn]), % set required headers RequiredHeaders = [ {'Upgrade', "WebSocket"}, {'Connection', "Upgrade"}, {'Host', ignore}, {"Origin", ignore} @@ -108,7 +108,7 @@ check_websocket({'draft-hixie', 68} = Vsn, Headers) -> case check_headers(Headers, RequiredHeaders) of true -> {true, Vsn}; _RemainingHeaders -> - ?DEBUG("not protocol ~p, remaining headers: ~p", [Vsn, _RemainingHeaders]), + %?DEBUG("not protocol ~p, remaining headers: ~p", [Vsn, _RemainingHeaders]), false end; check_websocket(_Vsn, _Headers) -> false. % not implemented @@ -121,7 +121,7 @@ check_headers(Headers, RequiredHeaders) -> case lists:keyfind(Tag, 1, Headers) of false -> true; % header not found, keep in list {Tag, HVal} -> - ?DEBUG("check: ~p", [{Tag, HVal,Val }]), + %?DEBUG("check: ~p", [{Tag, HVal,Val }]), case Val of ignore -> false; % ignore value -> ok, remove from list HVal -> false; % expected val -> ok, remove from list @@ -156,7 +156,7 @@ handshake({'draft-hixie', 76}, Sock,SocketMod, Headers, {Path, Origin, Host, Por ?ERROR_MSG("tcp error treating data: ~p", [_Other]), <<>> end, - ?DEBUG("got content in body of websocket request: ~p, ~p", [Body,string:join([Host, Path],"/")]), + %?DEBUG("got content in body of websocket request: ~p, ~p", [Body,string:join([Host, Path],"/")]), % prepare handhsake response ["HTTP/1.1 101 WebSocket Protocol Handshake\r\n", "Upgrade: WebSocket\r\n", @@ -193,18 +193,19 @@ build_challenge({'draft-hixie', 76}, {Key1, Key2, Key3}) -> ws_loop(Socket, Buffer, WsHandleLoopPid, SocketMode, WsAutoExit) -> - ?DEBUG("websocket loop", []), + %?DEBUG("websocket loop", []), receive {tcp, Socket, Data} -> handle_data(Buffer, binary_to_list(Data), Socket, WsHandleLoopPid, SocketMode, WsAutoExit); {tcp_closed, Socket} -> - ?DEBUG("tcp connection was closed, exit", []), + %?DEBUG("tcp connection was closed, exit", []), % close websocket and custom controlling loop websocket_close(Socket, WsHandleLoopPid, SocketMode, WsAutoExit); {'DOWN', Ref, process, WsHandleLoopPid, Reason} -> case Reason of normal -> - ?DEBUG("linked websocket controlling loop stopped.", []); + %?DEBUG("linked websocket controlling loop stopped.", []); + ok; _ -> ?ERROR_MSG("linked websocket controlling loop crashed with reason: ~p", [Reason]) end, @@ -213,11 +214,11 @@ ws_loop(Socket, Buffer, WsHandleLoopPid, SocketMode, WsAutoExit) -> % close websocket and custom controlling loop websocket_close(Socket, WsHandleLoopPid, SocketMode, WsAutoExit); {send, Data} -> - ?DEBUG("sending data to websocket: ~p", [Data]), + %?DEBUG("sending data to websocket: ~p", [Data]), SocketMode:send(Socket, [0, Data, 255]), ws_loop(Socket, Buffer, WsHandleLoopPid, SocketMode, WsAutoExit); shutdown -> - ?DEBUG("shutdown request received, closing websocket with pid ~p", [self()]), + %?DEBUG("shutdown request received, closing websocket with pid ~p", [self()]), % close websocket and custom controlling loop websocket_close(Socket, WsHandleLoopPid, SocketMode, WsAutoExit); _Ignored -> @@ -227,24 +228,24 @@ ws_loop(Socket, Buffer, WsHandleLoopPid, SocketMode, WsAutoExit) -> % Buffering and data handling handle_data(none, [0|T], Socket, WsHandleLoopPid, SocketMode, WsAutoExit) -> - ?DEBUG("handle_data 1", []), + %?DEBUG("handle_data 1", []), handle_data([], T, Socket, WsHandleLoopPid, SocketMode, WsAutoExit); handle_data(none, [], Socket, WsHandleLoopPid, SocketMode, WsAutoExit) -> - ?DEBUG("handle_data 2", []), + %?DEBUG("handle_data 2", []), ws_loop(Socket, none, WsHandleLoopPid, SocketMode, WsAutoExit); handle_data(L, [255|T], Socket, WsHandleLoopPid, SocketMode, WsAutoExit) -> - ?DEBUG("handle_data 3", []), + %?DEBUG("handle_data 3", []), WsHandleLoopPid ! {browser, lists:reverse(L)}, handle_data(none, T, Socket, WsHandleLoopPid, SocketMode, WsAutoExit); handle_data(L, [H|T], Socket, WsHandleLoopPid, SocketMode, WsAutoExit) -> - ?DEBUG("handle_data 4, Buffer = ~p", [L]), + %?DEBUG("handle_data 4, Buffer = ~p", [L]), handle_data([H|L], T, Socket, WsHandleLoopPid, SocketMode, WsAutoExit); handle_data([], L, Socket, WsHandleLoopPid, SocketMode, WsAutoExit) -> - ?DEBUG("handle_data 5", []), + %?DEBUG("handle_data 5", []), ws_loop(Socket, L, WsHandleLoopPid, SocketMode, WsAutoExit). % Close socket and custom handling loop dependency From 2624f3ba51c8df1ba13267a1d48b8c3f49aed71d Mon Sep 17 00:00:00 2001 From: Christophe Romain Date: Thu, 16 Sep 2010 14:31:08 +0200 Subject: [PATCH 50/85] added pubsub helper modules --- src/mod_pubsub/pubsub_clean.erl | 41 ++++++++++++ src/mod_pubsub/pubsub_debug.erl | 112 ++++++++++++++++++++++++++++++++ 2 files changed, 153 insertions(+) create mode 100644 src/mod_pubsub/pubsub_clean.erl create mode 100644 src/mod_pubsub/pubsub_debug.erl diff --git a/src/mod_pubsub/pubsub_clean.erl b/src/mod_pubsub/pubsub_clean.erl new file mode 100644 index 000000000..6e32ccb35 --- /dev/null +++ b/src/mod_pubsub/pubsub_clean.erl @@ -0,0 +1,41 @@ +-module(pubsub_clean). + +-define(TIMEOUT, 1000*600). % 1 minute + +-export([start/0, loop/0, subscribed/1, offline/1]). + +start() -> + Pid = spawn(?MODULE, loop, []), + register(pubsub_clean, Pid), + Pid. + +loop() -> + receive + purge -> purge() + after ?TIMEOUT -> purge() + end, + loop(). + +purge() -> + {Sessions, Subscriptions} = {mnesia:table_info(session,size),mnesia:table_info(pubsub_state,size)}, + if Subscriptions > Sessions + 500 -> + lists:foreach(fun(K) -> + [N]=mnesia:dirty_read({pubsub_node, K}), + I=element(3,N), + lists:foreach(fun(JID) -> + mnesia:dirty_delete({pubsub_state, {JID, I}}) + end, offline(subscribed(I))) + end, mnesia:dirty_all_keys(pubsub_node)); + true -> + ok + end. + +subscribed(NodeId) -> + lists:map(fun(S) -> + element(1,element(2,S)) + end, mnesia:dirty_match_object({pubsub_state, {'_',NodeId},'_',none,subscribed})). + +offline(Jids) -> + lists:filter(fun({U,S,""}) -> ejabberd_sm:get_user_resources(U,S) == []; + ({U,S,R}) -> not lists:member(R,ejabberd_sm:get_user_resources(U,S)) + end, Jids). diff --git a/src/mod_pubsub/pubsub_debug.erl b/src/mod_pubsub/pubsub_debug.erl new file mode 100644 index 000000000..2fe1a5b42 --- /dev/null +++ b/src/mod_pubsub/pubsub_debug.erl @@ -0,0 +1,112 @@ +-module(pubsub_debug). +-author('christophe.romain@process-one.net'). + +-include("pubsub.hrl"). + +-compile(export_all). + +nodeid(Host, Node) -> + case mnesia:dirty_read({pubsub_node, {Host, Node}}) of + [N] -> nodeid(N); + _ -> 0 + end. +nodeid(N) -> N#pubsub_node.id. +nodeids() -> [nodeid(Host, Node) || {Host, Node} <- mnesia:dirty_all_keys(pubsub_node)]. +nodeids_by_type(Type) -> [nodeid(N) || N <- mnesia:dirty_match_object(#pubsub_node{type=Type, _='_'})]. +nodeids_by_option(Key, Value) -> [nodeid(N) || N <- mnesia:dirty_match_object(#pubsub_node{_='_'}), lists:member({Key, Value}, N#pubsub_node.options)]. +nodeids_by_owner(JID) -> [nodeid(N) || N <- mnesia:dirty_match_object(#pubsub_node{_='_'}), lists:member(JID, N#pubsub_node.owners)]. +nodes_by_id(I) -> mnesia:dirty_match_object(#pubsub_node{id=I, _='_'}). + +state(JID, NodeId) -> + case mnesia:dirty_read({pubsub_state, {JID, NodeId}}) of + [S] -> S; + _ -> undefined + end. +states(NodeId) -> mnesia:dirty_match_object(#pubsub_state{stateid={'_', NodeId}, _='_'}). +stateid(S) -> element(1, S#pubsub_state.stateid). +stateids(NodeId) -> [stateid(S) || S <- states(NodeId)]. +states_by_jid(JID) -> mnesia:dirty_match_object(#pubsub_state{stateid={JID, '_'}, _='_'}). + +item(ItemId, NodeId) -> + case mnesia:dirty_read({pubsub_item, {ItemId, NodeId}}) of + [I] -> I; + _ -> undefined + end. +items(NodeId) -> mnesia:dirty_match_object(#pubsub_item{itemid={'_', NodeId}, _='_'}). +itemid(I) -> element(1, I#pubsub_item.itemid). +itemids(NodeId) -> [itemid(I) || I <- items(NodeId)]. +items_by_id(ItemId) -> mnesia:dirty_match_object(#pubsub_item{itemid={ItemId, '_'}, _='_'}). + +affiliated(NodeId) -> [stateid(S) || S <- states(NodeId), S#pubsub_state.affiliation=/=none]. +subscribed(NodeId) -> [stateid(S) || S <- states(NodeId), S#pubsub_state.subscriptions=/=[]]. +%subscribed(NodeId) -> [stateid(S) || S <- states(NodeId), S#pubsub_state.subscription=/=none]. %% old record +owners(NodeId) -> [stateid(S) || S <- mnesia:dirty_match_object(#pubsub_state{stateid={'_', NodeId}, affiliation=owner, _='_'})]. + +orphan_items(NodeId) -> + itemids(NodeId) -- lists:foldl(fun(S, A) -> A++S#pubsub_state.items end, [], mnesia:dirty_match_object(#pubsub_state{stateid={'_', NodeId}, _='_'})). +newer_items(NodeId, Seconds) -> + Now = calendar:universal_time(), + Oldest = calendar:seconds_to_daystime(Seconds), + [itemid(I) || I <- items(NodeId), calendar:time_difference(calendar:now_to_universal_time(element(1, I#pubsub_item.modification)), Now) < Oldest]. +older_items(NodeId, Seconds) -> + Now = calendar:universal_time(), + Oldest = calendar:seconds_to_daystime(Seconds), + [itemid(I) || I <- items(NodeId), calendar:time_difference(calendar:now_to_universal_time(element(1, I#pubsub_item.modification)), Now) > Oldest]. + +orphan_nodes() -> [I || I <- nodeids(), owners(I)==[]]. +duplicated_nodes() -> L = nodeids(), lists:usort(L -- lists:seq(1, lists:max(L))). +node_options(NodeId) -> + [N] = mnesia:dirty_match_object(#pubsub_node{id=NodeId, _='_'}), + N#pubsub_node.options. +update_node_options(Key, Value, NodeId) -> + [N] = mnesia:dirty_match_object(#pubsub_node{id=NodeId, _='_'}), + NewOptions = lists:keyreplace(Key, 1, N#pubsub_node.options, {Key, Value}), + mnesia:dirty_write(N#pubsub_node{options = NewOptions}). + +check() -> + mnesia:transaction(fun() -> + case mnesia:read({pubsub_index, node}) of + [Idx] -> + Free = Idx#pubsub_index.free, + Last = Idx#pubsub_index.last, + Allocated = lists:seq(1, Last) -- Free, + NodeIds = mnesia:foldl(fun(N,A) -> [nodeid(N)|A] end, [], pubsub_node), + StateIds = lists:usort(mnesia:foldl(fun(S,A) -> [element(2, S#pubsub_state.stateid)|A] end, [], pubsub_state)), + ItemIds = lists:usort(mnesia:foldl(fun(I,A) -> [element(2, I#pubsub_item.itemid)|A] end, [], pubsub_item)), + BadNodeIds = NodeIds -- Allocated, + BadStateIds = StateIds -- NodeIds, + BadItemIds = ItemIds -- NodeIds, + Lost = Allocated -- NodeIds, + [{bad_nodes, [N#pubsub_node.nodeid || N <- lists:flatten([mnesia:match_object(#pubsub_node{id=I, _='_'}) || I <- BadNodeIds])]}, + {bad_states, lists:foldl(fun(N,A) -> A++[{I,N} || I <- stateids(N)] end, [], BadStateIds)}, + {bad_items, lists:foldl(fun(N,A) -> A++[{I,N} || I <- itemids(N)] end, [], BadItemIds)}, + {lost_idx, Lost}, + {orphaned, [I || I <- NodeIds, owners(I)==[]]}, + {duplicated, lists:usort(NodeIds -- lists:seq(1, lists:max(NodeIds)))}]; + _ -> + no_index + end + end). + +rebuild_index() -> + mnesia:transaction(fun() -> + NodeIds = mnesia:foldl(fun(N,A) -> [nodeid(N)|A] end, [], pubsub_node), + Last = lists:max(NodeIds), + Free = lists:seq(1, Last) -- NodeIds, + mnesia:write(#pubsub_index{index = node, last = Last, free = Free}) + end). + +pep_subscriptions(LUser, LServer, LResource) -> + case ejabberd_sm:get_session_pid({LUser, LServer, LResource}) of + C2SPid when is_pid(C2SPid) -> + case catch ejabberd_c2s:get_subscribed(C2SPid) of + Contacts when is_list(Contacts) -> + lists:map(fun({U, S, _}) -> + io_lib:format("~s@~s", [U, S]) + end, Contacts); + _ -> + [] + end; + _ -> + [] + end. From 40625b29f2d089069407df1f3e421305eff6b849 Mon Sep 17 00:00:00 2001 From: Eric Cestari Date: Thu, 16 Sep 2010 14:37:27 +0200 Subject: [PATCH 51/85] ApplePush : previous merge missed timeout handler in c2s. --- src/ejabberd_c2s.erl | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/ejabberd_c2s.erl b/src/ejabberd_c2s.erl index ce68316e8..e67754cfc 100644 --- a/src/ejabberd_c2s.erl +++ b/src/ejabberd_c2s.erl @@ -1192,6 +1192,12 @@ handle_event({del_rosteritem, IJID}, StateName, StateData) -> NewStateData = roster_change(IJID, none, StateData), fsm_next_state(StateName, NewStateData); +handle_event({xmlstreamcdata, _}, StateName, StateData) -> + ?DEBUG("cdata ping", []), + NSD1 = change_reception(StateData, true), + NSD2 = start_keepalive_timer(NSD1), + fsm_next_state(StateName, NSD2); + handle_event(_Event, StateName, StateData) -> fsm_next_state(StateName, StateData). From df1ab9149fb978c8ba388f99207c5479cd504853 Mon Sep 17 00:00:00 2001 From: Christophe Romain Date: Thu, 16 Sep 2010 14:53:20 +0200 Subject: [PATCH 52/85] remove garbage configuration --- src/mod_pubsub/node_flat_odbc.erl | 3 +-- src/mod_pubsub/node_pep_odbc.erl | 1 - 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/mod_pubsub/node_flat_odbc.erl b/src/mod_pubsub/node_flat_odbc.erl index a255e9b0d..95998a554 100644 --- a/src/mod_pubsub/node_flat_odbc.erl +++ b/src/mod_pubsub/node_flat_odbc.erl @@ -76,8 +76,7 @@ terminate(Host, ServerHost) -> node_hometree_odbc:terminate(Host, ServerHost). options() -> - [{node_type, flat}, - {deliver_payloads, true}, + [{deliver_payloads, true}, {notify_config, false}, {notify_delete, false}, {notify_retract, true}, diff --git a/src/mod_pubsub/node_pep_odbc.erl b/src/mod_pubsub/node_pep_odbc.erl index 9f0071bbc..5d2fb0e1e 100644 --- a/src/mod_pubsub/node_pep_odbc.erl +++ b/src/mod_pubsub/node_pep_odbc.erl @@ -86,7 +86,6 @@ terminate(Host, ServerHost) -> options() -> [{odbc, true}, - {node_type, pep}, {deliver_payloads, true}, {notify_config, false}, {notify_delete, false}, From a45ecb70ff67a9fba4349e2fa4ad838a75232eb3 Mon Sep 17 00:00:00 2001 From: Eric Cestari Date: Thu, 16 Sep 2010 15:08:53 +0200 Subject: [PATCH 53/85] [TECH-1511] debug traces reorganized --- src/ejabberd_auth_internal.erl | 2 +- src/web/ejabberd_http.erl | 6 +----- src/web/ejabberd_http_ws.erl | 2 +- src/web/ejabberd_websocket.erl | 10 ++-------- 4 files changed, 5 insertions(+), 15 deletions(-) diff --git a/src/ejabberd_auth_internal.erl b/src/ejabberd_auth_internal.erl index add6fcd0e..9cd89b724 100644 --- a/src/ejabberd_auth_internal.erl +++ b/src/ejabberd_auth_internal.erl @@ -75,7 +75,7 @@ update_reg_users_counter_table(Server) -> mnesia:sync_dirty(F). plain_password_required() -> - true. + false. check_password(User, Server, Password) -> LUser = jlib:nodeprep(User), diff --git a/src/web/ejabberd_http.erl b/src/web/ejabberd_http.erl index 40bc5a559..9bfb3bd62 100644 --- a/src/web/ejabberd_http.erl +++ b/src/web/ejabberd_http.erl @@ -330,10 +330,6 @@ process(Handlers, #ws{} = Ws)-> (HandlerPathPrefix==Ws#ws.path)) of true -> ?DEBUG("~p matches ~p", [Ws#ws.path, HandlerPathPrefix]), - %% LocalPath is the path "local to the handler", i.e. if - %% the handler was registered to handle "/test/" and the - %% requested path is "/test/foo/bar", the local path is - %% ["foo", "bar"] LocalPath = lists:nthtail(length(HandlerPathPrefix), Ws#ws.path), ejabberd_hooks:run(ws_debug, [{LocalPath, Ws}]), ejabberd_websocket:connect(Ws#ws{local_path = LocalPath}, HandlerModule); @@ -410,6 +406,7 @@ process_request(#state{request_method = Method, headers = RequestHeaders }, process(WebSocketHandlers, Ws), + ?DEBUG("It is a websocket.",[]), none; false -> Request = #request{method = Method, @@ -422,7 +419,6 @@ process_request(#state{request_method = Method, tp = TP, headers = RequestHeaders, ip = IP}, - ?DEBUG("It is not a websocket.",[]), case process(RequestHandlers, Request) of El when element(1, El) == xmlelement -> make_xhtml_output(State, 200, [], El); diff --git a/src/web/ejabberd_http_ws.erl b/src/web/ejabberd_http_ws.erl index 93906229f..a4838c6e0 100644 --- a/src/web/ejabberd_http_ws.erl +++ b/src/web/ejabberd_http_ws.erl @@ -76,7 +76,7 @@ start(WS) -> supervisor:start_child(ejabberd_wsloop_sup, [WS]). start_link(WS) -> - gen_fsm:start_link(?MODULE, [WS],[{debug, [trace]}]). + gen_fsm:start_link(?MODULE, [WS],?FSMOPTS). send({http_ws, FsmRef, _IP}, Packet) -> gen_fsm:sync_send_all_state_event(FsmRef, {send, Packet}). diff --git a/src/web/ejabberd_websocket.erl b/src/web/ejabberd_websocket.erl index 61cd61daf..b579c057e 100644 --- a/src/web/ejabberd_websocket.erl +++ b/src/web/ejabberd_websocket.erl @@ -44,7 +44,6 @@ -include("ejabberd_http.hrl"). check(_Path, Headers)-> - %?DEBUG("testing for a websocket request path: ~p headers: ~p", [_Path, Headers]), % set supported websocket protocols, order does matter VsnSupported = [{'draft-hixie', 76}, {'draft-hixie', 68}], % checks @@ -198,7 +197,7 @@ ws_loop(Socket, Buffer, WsHandleLoopPid, SocketMode, WsAutoExit) -> {tcp, Socket, Data} -> handle_data(Buffer, binary_to_list(Data), Socket, WsHandleLoopPid, SocketMode, WsAutoExit); {tcp_closed, Socket} -> - %?DEBUG("tcp connection was closed, exit", []), + ?DEBUG("tcp connection was closed, exit", []), % close websocket and custom controlling loop websocket_close(Socket, WsHandleLoopPid, SocketMode, WsAutoExit); {'DOWN', Ref, process, WsHandleLoopPid, Reason} -> @@ -218,7 +217,7 @@ ws_loop(Socket, Buffer, WsHandleLoopPid, SocketMode, WsAutoExit) -> SocketMode:send(Socket, [0, Data, 255]), ws_loop(Socket, Buffer, WsHandleLoopPid, SocketMode, WsAutoExit); shutdown -> - %?DEBUG("shutdown request received, closing websocket with pid ~p", [self()]), + ?DEBUG("shutdown request received, closing websocket with pid ~p", [self()]), % close websocket and custom controlling loop websocket_close(Socket, WsHandleLoopPid, SocketMode, WsAutoExit); _Ignored -> @@ -228,24 +227,19 @@ ws_loop(Socket, Buffer, WsHandleLoopPid, SocketMode, WsAutoExit) -> % Buffering and data handling handle_data(none, [0|T], Socket, WsHandleLoopPid, SocketMode, WsAutoExit) -> - %?DEBUG("handle_data 1", []), handle_data([], T, Socket, WsHandleLoopPid, SocketMode, WsAutoExit); handle_data(none, [], Socket, WsHandleLoopPid, SocketMode, WsAutoExit) -> - %?DEBUG("handle_data 2", []), ws_loop(Socket, none, WsHandleLoopPid, SocketMode, WsAutoExit); handle_data(L, [255|T], Socket, WsHandleLoopPid, SocketMode, WsAutoExit) -> - %?DEBUG("handle_data 3", []), WsHandleLoopPid ! {browser, lists:reverse(L)}, handle_data(none, T, Socket, WsHandleLoopPid, SocketMode, WsAutoExit); handle_data(L, [H|T], Socket, WsHandleLoopPid, SocketMode, WsAutoExit) -> - %?DEBUG("handle_data 4, Buffer = ~p", [L]), handle_data([H|L], T, Socket, WsHandleLoopPid, SocketMode, WsAutoExit); handle_data([], L, Socket, WsHandleLoopPid, SocketMode, WsAutoExit) -> - %?DEBUG("handle_data 5", []), ws_loop(Socket, L, WsHandleLoopPid, SocketMode, WsAutoExit). % Close socket and custom handling loop dependency From 179a0cf255e59cdcbeb2562c756d070cb3522d03 Mon Sep 17 00:00:00 2001 From: Badlop Date: Fri, 17 Sep 2010 00:14:13 +0200 Subject: [PATCH 54/85] Remove some compiled files --- doc/dev.html | 413 --- doc/features.html | 132 - doc/guide.html | 4121 ----------------------------- src/configure | 6310 --------------------------------------------- 4 files changed, 10976 deletions(-) delete mode 100644 doc/dev.html delete mode 100644 doc/features.html delete mode 100644 doc/guide.html delete mode 100755 src/configure diff --git a/doc/dev.html b/doc/dev.html deleted file mode 100644 index b7fea526a..000000000 --- a/doc/dev.html +++ /dev/null @@ -1,413 +0,0 @@ - - - -Ejabberd 2.1.x Developers Guide - - - - - - - - -

    - -

    -

    Ejabberd 2.1.x Developers Guide

    Alexey Shchepin
    - mailto:alexey@sevcom.net
    - xmpp:aleksey@jabber.ru

    - -logo.png - - -
    I can thoroughly recommend ejabberd for ease of setup – -Kevin Smith, Current maintainer of the Psi project
    -

    Contents

    Introduction -

    ejabberd is a free and open source instant messaging server written in Erlang/OTP.

    ejabberd is cross-platform, distributed, fault-tolerant, and based on open standards to achieve real-time communication.

    ejabberd is designed to be a rock-solid and feature rich XMPP server.

    ejabberd is suitable for small deployments, whether they need to be scalable or not, as well as extremely big deployments.

    -

    1  Key Features

    - -

    ejabberd is: -

    • -Cross-platform: ejabberd runs under Microsoft Windows and Unix derived systems such as Linux, FreeBSD and NetBSD.
    • Distributed: You can run ejabberd on a cluster of machines and all of them will serve the same Jabber domain(s). When you need more capacity you can simply add a new cheap node to your cluster. Accordingly, you do not need to buy an expensive high-end machine to support tens of thousands concurrent users.
    • Fault-tolerant: You can deploy an ejabberd cluster so that all the information required for a properly working service will be replicated permanently on all nodes. This means that if one of the nodes crashes, the others will continue working without disruption. In addition, nodes also can be added or replaced ‘on the fly’.
    • Administrator Friendly: ejabberd is built on top of the Open Source Erlang. As a result you do not need to install an external database, an external web server, amongst others because everything is already included, and ready to run out of the box. Other administrator benefits include: -
      • -Comprehensive documentation. -
      • Straightforward installers for Linux, Mac OS X, and Windows.
      • Web Administration. -
      • Shared Roster Groups. -
      • Command line administration tool.
      • Can integrate with existing authentication mechanisms. -
      • Capability to send announce messages. -
    • Internationalized: ejabberd leads in internationalization. Hence it is very well suited in a globalized world. Related features are: -
      • -Translated to 25 languages.
      • Support for IDNA. -
    • Open Standards: ejabberd is the first Open Source Jabber server claiming to fully comply to the XMPP standard. -
    -

    2  Additional Features

    - -

    Moreover, ejabberd comes with a wide range of other state-of-the-art features: -

    • -Modular -
      • -Load only the modules you want. -
      • Extend ejabberd with your own custom modules. -
      -
    • Security -
      • -SASL and STARTTLS for c2s and s2s connections. -
      • STARTTLS and Dialback s2s connections. -
      • Web Admin accessible via HTTPS secure access. -
      -
    • Databases -
      • -Internal database for fast deployment (Mnesia). -
      • Native MySQL support. -
      • Native PostgreSQL support. -
      • ODBC data storage support. -
      • Microsoft SQL Server support.
      -
    • Authentication -
      • -Internal Authentication. -
      • PAM, LDAP and ODBC.
      • External Authentication script. -
      -
    • Others -
      • -Support for virtual hosting. -
      • Compressing XML streams with Stream Compression (XEP-0138). -
      • Statistics via Statistics Gathering (XEP-0039). -
      • IPv6 support both for c2s and s2s connections. -
      • Multi-User Chat module with support for clustering and HTML logging.
      • Users Directory based on users vCards. -
      • Publish-Subscribe component with support for Personal Eventing via Pubsub. -
      • Support for web clients: HTTP Polling and HTTP Binding (BOSH) services. -
      • IRC transport. -
      • Component support: interface with networks such as AIM, ICQ and MSN installing special tranports. -
      -
    -

    3  How it Works

    -

    A XMPP domain is served by one or more ejabberd nodes. These nodes can -be run on different machines that are connected via a network. They all must -have the ability to connect to port 4369 of all another nodes, and must have -the same magic cookie (see Erlang/OTP documentation, in other words the file -~ejabberd/.erlang.cookie must be the same on all nodes). This is -needed because all nodes exchange information about connected users, S2S -connections, registered services, etc…

    Each ejabberd node have following modules: -

    • -router; -
    • local router. -
    • session manager; -
    • S2S manager; -
    -

    3.1  Router

    This module is the main router of XMPP packets on each node. It routes -them based on their destinations domains. It has two tables: local and global -routes. First, domain of packet destination searched in local table, and if it -found, then the packet is routed to appropriate process. If no, then it -searches in global table, and is routed to the appropriate ejabberd node or -process. If it does not exists in either tables, then it sent to the S2S -manager.

    -

    3.2  Local Router

    This module routes packets which have a destination domain equal to this server -name. If destination JID has a non-empty user part, then it routed to the -session manager, else it is processed depending on it’s content.

    -

    3.3  Session Manager

    This module routes packets to local users. It searches for what user resource -packet must be sended via presence table. If this resource is connected to -this node, it is routed to C2S process, if it connected via another node, then -the packet is sent to session manager on that node.

    -

    3.4  S2S Manager

    This module routes packets to other XMPP servers. First, it checks if an -open S2S connection from the domain of the packet source to the domain of -packet destination already exists. If it is open on another node, then it -routes the packet to S2S manager on that node, if it is open on this node, then -it is routed to the process that serves this connection, and if a connection -does not exist, then it is opened and registered.

    -

    4  Authentication

    -

    4.0.1  External

    - -

    The external authentication script follows -the erlang port driver API.

    That script is supposed to do theses actions, in an infinite loop: -

    • -read from stdin: AABBBBBBBBB..... -
      • -A: 2 bytes of length data (a short in network byte order) -
      • B: a string of length found in A that contains operation in plain text -operation are as follows: -
        • -auth:User:Server:Password (check if a username/password pair is correct) -
        • isuser:User:Server (check if it’s a valid user) -
        • setpass:User:Server:Password (set user’s password) -
        • tryregister:User:Server:Password (try to register an account) -
        • removeuser:User:Server (remove this account) -
        • removeuser3:User:Server:Password (remove this account if the password is correct) -
        -
      -
    • write to stdout: AABB -
      • -A: the number 2 (coded as a short, which is bytes length of following result) -
      • B: the result code (coded as a short), should be 1 for success/valid, or 0 for failure/invalid -
      -

    Example python script -

    #!/usr/bin/python
    -
    -import sys
    -from struct import *
    -
    -def from_ejabberd():
    -    input_length = sys.stdin.read(2)
    -    (size,) = unpack('>h', input_length)
    -    return sys.stdin.read(size).split(':')
    -
    -def to_ejabberd(bool):
    -    answer = 0
    -    if bool:
    -        answer = 1
    -    token = pack('>hh', 2, answer)
    -    sys.stdout.write(token)
    -    sys.stdout.flush()
    -
    -def auth(username, server, password):
    -    return True
    -
    -def isuser(username, server):
    -    return True
    -
    -def setpass(username, server, password):
    -    return True
    -
    -while True:
    -    data = from_ejabberd()
    -    success = False
    -    if data[0] == "auth":
    -        success = auth(data[1], data[2], data[3])
    -    elif data[0] == "isuser":
    -        success = isuser(data[1], data[2])
    -    elif data[0] == "setpass":
    -        success = setpass(data[1], data[2], data[3])
    -    to_ejabberd(success)
    -
    -

    5  XML Representation

    -

    Each XML stanza is represented as the following tuple: -

    XMLElement = {xmlelement, Name, Attrs, [ElementOrCDATA]}
    -        Name = string()
    -        Attrs = [Attr]
    -        Attr = {Key, Val}
    -        Key = string()
    -        Val = string()
    -        ElementOrCDATA = XMLElement | CDATA
    -        CDATA = {xmlcdata, string()}
    -

    E. g. this stanza: -

    <message to='test@conference.example.org' type='groupchat'>
    -  <body>test</body>
    -</message>
    -

    is represented as the following structure: -

    {xmlelement, "message",
    -    [{"to", "test@conference.example.org"},
    -     {"type", "groupchat"}],
    -    [{xmlelement, "body",
    -         [],
    -         [{xmlcdata, "test"}]}]}}
    -
    -

    6  Module xml

    -

    -
    element_to_string(El) -> string() -
    El = XMLElement
    -
    Returns string representation of XML stanza El.
    crypt(S) -> string() -
    S = string()
    -
    Returns string which correspond to S with encoded XML special -characters.
    remove_cdata(ECList) -> EList -
    ECList = [ElementOrCDATA]
    -EList = [XMLElement]
    -
    EList is a list of all non-CDATA elements of ECList.
    get_path_s(El, Path) -> Res -
    El = XMLElement
    -Path = [PathItem]
    -PathItem = PathElem | PathAttr | PathCDATA
    -PathElem = {elem, Name}
    -PathAttr = {attr, Name}
    -PathCDATA = cdata
    -Name = string()
    -Res = string() | XMLElement
    -
    If Path is empty, then returns El. Else sequentially -consider elements of Path. Each element is one of: -
    -
    {elem, Name} Name is name of subelement of -El, if such element exists, then this element considered in -following steps, else returns empty string. -
    {attr, Name} If El have attribute Name, then -returns value of this attribute, else returns empty string. -
    cdata Returns CDATA of El. -
    TODO: -
             get_cdata/1, get_tag_cdata/1
    -         get_attr/2, get_attr_s/2
    -         get_tag_attr/2, get_tag_attr_s/2
    -         get_subtag/2
    -
    -

    7  Module xml_stream

    -

    -
    parse_element(Str) -> XMLElement | {error, Err} -
    Str = string()
    -Err = term()
    -
    Parses Str using XML parser, returns either parsed element or error -tuple. -
    -

    8  Modules

    -

    -

    8.1  Module gen_iq_handler

    -

    The module gen_iq_handler allows to easily write handlers for IQ packets -of particular XML namespaces that addressed to server or to users bare JIDs.

    In this module the following functions are defined: -

    -
    add_iq_handler(Component, Host, NS, Module, Function, Type) -
    Component = Module = Function = atom()
    -Host = NS = string()
    -Type = no_queue | one_queue | parallel
    -
    Registers function Module:Function as handler for IQ packets on -virtual host Host that contain child of namespace NS in -Component. Queueing discipline is Type. There are at least -two components defined: -
    -
    ejabberd_local Handles packets that addressed to server JID; -
    ejabberd_sm Handles packets that addressed to users bare JIDs. -
    -
    remove_iq_handler(Component, Host, NS) -
    Component = atom()
    -Host = NS = string()
    -
    Removes IQ handler on virtual host Host for namespace NS from -Component. -

    Handler function must have the following type: -

    -
    Module:Function(From, To, IQ) -
    From = To = jid()
    -
    -module(mod_cputime).
    -
    --behaviour(gen_mod).
    -
    --export([start/2,
    -         stop/1,
    -         process_local_iq/3]).
    -
    --include("ejabberd.hrl").
    --include("jlib.hrl").
    -
    --define(NS_CPUTIME, "ejabberd:cputime").
    -
    -start(Host, Opts) ->
    -    IQDisc = gen_mod:get_opt(iqdisc, Opts, one_queue),
    -    gen_iq_handler:add_iq_handler(ejabberd_local, Host, ?NS_CPUTIME,
    -                                  ?MODULE, process_local_iq, IQDisc).
    -
    -stop(Host) ->
    -    gen_iq_handler:remove_iq_handler(ejabberd_local, Host, ?NS_CPUTIME).
    -
    -process_local_iq(From, To, {iq, ID, Type, XMLNS, SubEl}) ->
    -    case Type of
    -        set ->
    -            {iq, ID, error, XMLNS,
    -             [SubEl, ?ERR_NOT_ALLOWED]};
    -        get ->
    -            CPUTime = element(1, erlang:statistics(runtime))/1000,
    -            SCPUTime = lists:flatten(io_lib:format("~.3f", CPUTime)),
    -            {iq, ID, result, XMLNS,
    -             [{xmlelement, "query",
    -               [{"xmlns", ?NS_CPUTIME}],
    -               [{xmlelement, "cputime", [], [{xmlcdata, SCPUTime}]}]}]}
    -    end.
    -
    -

    8.2  Services

    -

    -module(mod_echo).
    -
    --behaviour(gen_mod).
    -
    --export([start/2, init/1, stop/1]).
    -
    --include("ejabberd.hrl").
    --include("jlib.hrl").
    -
    -start(Host, Opts) ->
    -    MyHost = gen_mod:get_opt(host, Opts, "echo." ++ Host),
    -    register(gen_mod:get_module_proc(Host, ?PROCNAME),
    -             spawn(?MODULE, init, [MyHost])).
    -
    -init(Host) ->
    -    ejabberd_router:register_local_route(Host),
    -    loop(Host).
    -
    -loop(Host) ->
    -    receive
    -        {route, From, To, Packet} ->
    -            ejabberd_router:route(To, From, Packet),
    -            loop(Host);
    -        stop ->
    -            ejabberd_router:unregister_route(Host),
    -            ok;
    -        _ ->
    -            loop(Host)
    -    end.
    -
    -stop(Host) ->
    -    Proc = gen_mod:get_module_proc(Host, ?PROCNAME),
    -    Proc ! stop,
    -    {wait, Proc}.
    -
    - - - -
    This document was translated from LATEX by -HEVEA.
    - diff --git a/doc/features.html b/doc/features.html deleted file mode 100644 index 503ac0d3f..000000000 --- a/doc/features.html +++ /dev/null @@ -1,132 +0,0 @@ - - - -Ejabberd 2.1.x Feature Sheet - - - - - - - - -

    - -

    -

    Ejabberd 2.1.x Feature Sheet

    Sander Devrieze
    - mailto:s.devrieze@pandora.be
    - xmpp:sander@devrieze.dyndns.org

    - -logo.png - - -
    I can thoroughly recommend ejabberd for ease of setup – -Kevin Smith, Current maintainer of the Psi project

    Introduction -

    I just tried out ejabberd and was impressed both by ejabberd itself and the language it is written in, Erlang. — -Joeri

    ejabberd is a free and open source instant messaging server written in Erlang/OTP.

    ejabberd is cross-platform, distributed, fault-tolerant, and based on open standards to achieve real-time communication.

    ejabberd is designed to be a rock-solid and feature rich XMPP server.

    ejabberd is suitable for small deployments, whether they need to be scalable or not, as well as extremely big deployments.

    -

    Key Features

    - -

    Erlang seems to be tailor-made for writing stable, robust servers. — -Peter Saint-André, Executive Director of the Jabber Software Foundation

    ejabberd is: -

    • -Cross-platform: ejabberd runs under Microsoft Windows and Unix derived systems such as Linux, FreeBSD and NetBSD.
    • Distributed: You can run ejabberd on a cluster of machines and all of them will serve the same Jabber domain(s). When you need more capacity you can simply add a new cheap node to your cluster. Accordingly, you do not need to buy an expensive high-end machine to support tens of thousands concurrent users.
    • Fault-tolerant: You can deploy an ejabberd cluster so that all the information required for a properly working service will be replicated permanently on all nodes. This means that if one of the nodes crashes, the others will continue working without disruption. In addition, nodes also can be added or replaced ‘on the fly’.
    • Administrator Friendly: ejabberd is built on top of the Open Source Erlang. As a result you do not need to install an external database, an external web server, amongst others because everything is already included, and ready to run out of the box. Other administrator benefits include: -
      • -Comprehensive documentation. -
      • Straightforward installers for Linux, Mac OS X, and Windows.
      • Web Administration. -
      • Shared Roster Groups. -
      • Command line administration tool.
      • Can integrate with existing authentication mechanisms. -
      • Capability to send announce messages. -
    • Internationalized: ejabberd leads in internationalization. Hence it is very well suited in a globalized world. Related features are: -
      • -Translated to 25 languages.
      • Support for IDNA. -
    • Open Standards: ejabberd is the first Open Source Jabber server claiming to fully comply to the XMPP standard. -
    -

    Additional Features

    - -

    ejabberd is making inroads to solving the "buggy incomplete server" problem — -Justin Karneges, Founder of the Psi and the Delta projects

    Moreover, ejabberd comes with a wide range of other state-of-the-art features: -

    • -Modular -
      • -Load only the modules you want. -
      • Extend ejabberd with your own custom modules. -
      -
    • Security -
      • -SASL and STARTTLS for c2s and s2s connections. -
      • STARTTLS and Dialback s2s connections. -
      • Web Admin accessible via HTTPS secure access. -
      -
    • Databases -
      • -Internal database for fast deployment (Mnesia). -
      • Native MySQL support. -
      • Native PostgreSQL support. -
      • ODBC data storage support. -
      • Microsoft SQL Server support.
      -
    • Authentication -
      • -Internal Authentication. -
      • PAM, LDAP and ODBC.
      • External Authentication script. -
      -
    • Others -
      • -Support for virtual hosting. -
      • Compressing XML streams with Stream Compression (XEP-0138). -
      • Statistics via Statistics Gathering (XEP-0039). -
      • IPv6 support both for c2s and s2s connections. -
      • Multi-User Chat module with support for clustering and HTML logging.
      • Users Directory based on users vCards. -
      • Publish-Subscribe component with support for Personal Eventing via Pubsub. -
      • Support for web clients: HTTP Polling and HTTP Binding (BOSH) services. -
      • IRC transport. -
      • Component support: interface with networks such as AIM, ICQ and MSN installing special tranports. -
      -
    - - - -
    This document was translated from LATEX by -HEVEA.
    - diff --git a/doc/guide.html b/doc/guide.html deleted file mode 100644 index 50cdca74a..000000000 --- a/doc/guide.html +++ /dev/null @@ -1,4121 +0,0 @@ - - - - - - - - ejabberd 2.1.x - - Installation and Operation Guide - - - - - - - - - - - - - - -

    - -

    -

    -

    -
    - - - - -
    ejabberd 2.1.x
     
    Installation and Operation Guide

    -
    - -
    - -

    -

    -

    Contents

    -

    Chapter 1  Introduction

    -

    ejabberd is a free and open source instant messaging server written in Erlang/OTP.

    ejabberd is cross-platform, distributed, fault-tolerant, and based on open standards to achieve real-time communication.

    ejabberd is designed to be a rock-solid and feature rich XMPP server.

    ejabberd is suitable for small deployments, whether they need to be scalable or not, as well as extremely big deployments.

    -

    1.1  Key Features

    - -

    ejabberd is: -

    • -Cross-platform: ejabberd runs under Microsoft Windows and Unix derived systems such as Linux, FreeBSD and NetBSD.
    • Distributed: You can run ejabberd on a cluster of machines and all of them will serve the same Jabber domain(s). When you need more capacity you can simply add a new cheap node to your cluster. Accordingly, you do not need to buy an expensive high-end machine to support tens of thousands concurrent users.
    • Fault-tolerant: You can deploy an ejabberd cluster so that all the information required for a properly working service will be replicated permanently on all nodes. This means that if one of the nodes crashes, the others will continue working without disruption. In addition, nodes also can be added or replaced ‘on the fly’.
    • Administrator Friendly: ejabberd is built on top of the Open Source Erlang. As a result you do not need to install an external database, an external web server, amongst others because everything is already included, and ready to run out of the box. Other administrator benefits include: -
      • -Comprehensive documentation. -
      • Straightforward installers for Linux, Mac OS X, and Windows.
      • Web Administration. -
      • Shared Roster Groups. -
      • Command line administration tool.
      • Can integrate with existing authentication mechanisms. -
      • Capability to send announce messages. -
    • Internationalized: ejabberd leads in internationalization. Hence it is very well suited in a globalized world. Related features are: -
      • -Translated to 25 languages.
      • Support for IDNA. -
    • Open Standards: ejabberd is the first Open Source Jabber server claiming to fully comply to the XMPP standard. -
    -

    1.2  Additional Features

    - -

    Moreover, ejabberd comes with a wide range of other state-of-the-art features: -

    • -Modular -
      • -Load only the modules you want. -
      • Extend ejabberd with your own custom modules. -
      -
    • Security -
      • -SASL and STARTTLS for c2s and s2s connections. -
      • STARTTLS and Dialback s2s connections. -
      • Web Admin accessible via HTTPS secure access. -
      -
    • Databases -
      • -Internal database for fast deployment (Mnesia). -
      • Native MySQL support. -
      • Native PostgreSQL support. -
      • ODBC data storage support. -
      • Microsoft SQL Server support.
      -
    • Authentication -
      • -Internal Authentication. -
      • PAM, LDAP and ODBC.
      • External Authentication script. -
      -
    • Others -
      • -Support for virtual hosting. -
      • Compressing XML streams with Stream Compression (XEP-0138). -
      • Statistics via Statistics Gathering (XEP-0039). -
      • IPv6 support both for c2s and s2s connections. -
      • Multi-User Chat module with support for clustering and HTML logging.
      • Users Directory based on users vCards. -
      • Publish-Subscribe component with support for Personal Eventing via Pubsub. -
      • Support for web clients: HTTP Polling and HTTP Binding (BOSH) services. -
      • IRC transport. -
      • Component support: interface with networks such as AIM, ICQ and MSN installing special tranports. -
      -

    -

    Chapter 2  Installing ejabberd

    -

    2.1  Installing ejabberd with Binary Installer

    Probably the easiest way to install an ejabberd instant messaging server -is using the binary installer published by ProcessOne. -The binary installers of released ejabberd versions -are available in the ProcessOne ejabberd downloads page: -http://www.process-one.net/en/ejabberd/downloads

    The installer will deploy and configure a full featured ejabberd -server and does not require any extra dependencies.

    In *nix systems, remember to set executable the binary installer before starting it. For example: -

    chmod +x ejabberd-2.0.0_1-linux-x86-installer.bin
    -./ejabberd-2.0.0_1-linux-x86-installer.bin
    -

    ejabberd can be started manually at any time, -or automatically by the operating system at system boot time.

    To start and stop ejabberd manually, -use the desktop shortcuts created by the installer. -If the machine doesn’t have a graphical system, use the scripts ’start’ -and ’stop’ in the ’bin’ directory where ejabberd is installed.

    The Windows installer also adds ejabberd as a system service, -and a shortcut to a debug console for experienced administrators. -If you want ejabberd to be started automatically at boot time, -go to the Windows service settings and set ejabberd to be automatically started. -Note that the Windows service is a feature still in development, -and for example it doesn’t read the file ejabberdctl.cfg.

    On a *nix system, if you want ejabberd to be started as daemon at boot time, -copy ejabberd.init from the ’bin’ directory to something like /etc/init.d/ejabberd -(depending on your distribution). -Create a system user called ejabberd; -it will be used by the script to start the server. -Then you can call /etc/inid.d/ejabberd start as root to start the server.

    If ejabberd doesn’t start correctly in Windows, -try to start it using the shortcut in desktop or start menu. -If the window shows error 14001, the solution is to install: -"Microsoft Visual C++ 2005 SP1 Redistributable Package". -You can download it from -www.microsoft.com. -Then uninstall ejabberd and install it again.

    If ejabberd doesn’t start correctly and a crash dump is generated, -there was a severe problem. -You can try starting ejabberd with -the script bin/live.bat in Windows, -or with the command bin/ejabberdctl live in other Operating Systems. -This way you see the error message provided by Erlang -and can identify what is exactly the problem.

    The ejabberdctl administration script is included in the bin directory. -Please refer to the section 4.1 for details about ejabberdctl, -and configurable options to fine tune the Erlang runtime system.

    -

    2.2  Installing ejabberd with Operating System Specific Packages

    Some Operating Systems provide a specific ejabberd package adapted to -the system architecture and libraries. -It usually also checks dependencies -and performs basic configuration tasks like creating the initial -administrator account. Some examples are Debian and Gentoo. Consult the -resources provided by your Operating System for more information.

    Usually those packages create a script like /etc/init.d/ejabberd -to start and stop ejabberd as a service at boot time.

    -

    2.3  Installing ejabberd with CEAN

    CEAN -(Comprehensive Erlang Archive Network) is a repository that hosts binary -packages from many Erlang programs, including ejabberd and all its dependencies. -The binaries are available for many different system architectures, so this is an -alternative to the binary installer and Operating System’s ejabberd packages.

    You will have to create your own ejabberd start -script depending of how you handle your CEAN installation. -The default ejabberdctl script is located -into ejabberd’s priv directory and can be used as an example.

    -

    2.4  Installing ejabberd from Source Code

    -

    The canonical form for distribution of ejabberd stable releases is the source code package. -Compiling ejabberd from source code is quite easy in *nix systems, -as long as your system have all the dependencies.

    -

    2.4.1  Requirements

    -

    To compile ejabberd on a ‘Unix-like’ operating system, you need: -

    • -GNU Make -
    • GCC -
    • Libexpat 1.95 or higher -
    • Erlang/OTP R10B-9 or higher. The recommended versions are R12B-5 and R13B04. -
    • OpenSSL 0.9.8 or higher, for STARTTLS, SASL and SSL encryption. -
    • Zlib 1.2.3 or higher, for Stream Compression support (XEP-0138). Optional. -
    • Erlang mysql library. Optional. For MySQL authentication or storage. See section 3.2.1. -
    • Erlang pgsql library. Optional. For PostgreSQL authentication or storage. See section 3.2.3. -
    • PAM library. Optional. For Pluggable Authentication Modules (PAM). See section 3.1.4. -
    • GNU Iconv 1.8 or higher, for the IRC Transport (mod_irc). Optional. Not needed on systems with GNU Libc. See section 3.3.8. -
    • ImageMagick’s Convert program. Optional. For CAPTCHA challenges. See section 3.1.8. -
    • exmpp 0.9.2 or higher. Optional. For import/export user data with XEP-0227 XML files. -

    -

    2.4.2  Download Source Code

    -

    Released versions of ejabberd are available in the ProcessOne ejabberd downloads page: -http://www.process-one.net/en/ejabberd/downloads

    -Alternatively, the latest development source code can be retrieved from the Git repository using the commands: -

    git clone git://git.process-one.net/ejabberd/mainline.git ejabberd
    -cd ejabberd
    -git checkout -b 2.1.x origin/2.1.x
    -

    -

    2.4.3  Compile

    -

    To compile ejabberd execute the commands: -

    ./configure
    -make
    -

    The build configuration script allows several options. -To get the full list run the command: -

    ./configure --help
    -

    Some options that you may be interested in modifying: -

    - --prefix=/
    - Specify the path prefix where the files will be copied when running - the make install command.

    --enable-user[=USER]
    - Allow this normal system user to execute the ejabberdctl script - (see section 4.1), - read the configuration files, - read and write in the spool directory, - read and write in the log directory. - The account user and group must exist in the machine - before running make install. - This account doesn’t need an explicit HOME directory, because - /var/lib/ejabberd/ will be used by default.

    --enable-pam
    - Enable the PAM authentication method (see section 3.1.4).

    --enable-odbc or --enable-mssql
    - Required if you want to use an external database. - See section 3.2 for more information.

    --enable-full-xml
    - Enable the use of XML based optimisations. - It will for example use CDATA to escape characters in the XMPP stream. - Use this option only if you are sure your XMPP clients include a fully compliant XML parser.

    --disable-transient-supervisors
    - Disable the use of Erlang/OTP supervision for transient processes.

    --enable-nif
    -Replaces some critical Erlang functions with equivalents written in C to improve performance. -This feature requires Erlang/OTP R13B04 or higher. -

    -

    2.4.4  Install

    -

    To install ejabberd in the destination directories, run the command: -

    make install
    -

    Note that you probably need administrative privileges in the system -to install ejabberd.

    The files and directories created are, by default: -

    - /etc/ejabberd/
    Configuration directory: -
    - ejabberd.cfg
    ejabberd configuration file -
    ejabberdctl.cfg
    Configuration file of the administration script -
    inetrc
    Network DNS configuration file -
    -
    /lib/ejabberd/
    -
    - ebin/
    Erlang binary files (*.beam) -
    include/
    Erlang header files (*.hrl) -
    priv/
    Additional files required at runtime -
    - bin/
    Executable programs -
    lib/
    Binary system libraries (*.so) -
    msgs/
    Translation files (*.msgs) -
    -
    -
    /sbin/ejabberdctl
    Administration script (see section 4.1) -
    /share/doc/ejabberd/
    Documentation of ejabberd -
    /var/lib/ejabberd/
    Spool directory: -
    - .erlang.cookie
    Erlang cookie file (see section 5.3) -
    acl.DCD, ...
    Mnesia database spool files (*.DCD, *.DCL, *.DAT) -
    -
    /var/log/ejabberd/
    Log directory (see section 7.1): -
    - ejabberd.log
    ejabberd service log -
    erlang.log
    Erlang/OTP system log -
    -

    -

    2.4.5  Start

    -

    You can use the ejabberdctl command line administration script to start and stop ejabberd. -If you provided the configure option --enable-user=USER (see 2.4.3), -you can execute ejabberdctl with either that system account or root.

    Usage example: -

    ejabberdctl start
    -
    -ejabberdctl status
    -The node ejabberd@localhost is started with status: started
    -ejabberd is running in that node
    -
    -ejabberdctl stop
    -

    If ejabberd doesn’t start correctly and a crash dump is generated, -there was a severe problem. -You can try starting ejabberd with -the command ejabberdctl live -to see the error message provided by Erlang -and can identify what is exactly the problem.

    Please refer to the section 4.1 for details about ejabberdctl, -and configurable options to fine tune the Erlang runtime system.

    If you want ejabberd to be started as daemon at boot time, -copy ejabberd.init to something like /etc/init.d/ejabberd -(depending on your distribution). -Create a system user called ejabberd; -it will be used by the script to start the server. -Then you can call /etc/inid.d/ejabberd start as root to start the server.

    -

    2.4.6  Specific Notes for BSD

    -

    The command to compile ejabberd in BSD systems is: -

    gmake
    -

    -

    2.4.7  Specific Notes for Sun Solaris

    -

    You need to have GNU install, -but it isn’t included in Solaris. -It can be easily installed if your Solaris system -is set up for blastwave.org -package repository. -Make sure /opt/csw/bin is in your PATH and run: -

    pkg-get -i fileutils
    -

    If that program is called ginstall, -modify the ejabberd Makefile script to suit your system, -for example: -

    cat Makefile | sed s/install/ginstall/ > Makefile.gi
    -

    And finally install ejabberd with: -

    gmake -f Makefile.gi ginstall
    -

    -

    2.4.8  Specific Notes for Microsoft Windows

    -

    -

    Requirements

    To compile ejabberd on a Microsoft Windows system, you need: -

    -

    Compilation

    We assume that we will try to put as much library as possible into C:\sdk\ to make it easier to track what is install for ejabberd.

    1. -Install Erlang emulator (for example, into C:\sdk\erl5.5.5). -
    2. Install Expat library into C:\sdk\Expat-2.0.0 -directory.

      Copy file C:\sdk\Expat-2.0.0\Libs\libexpat.dll -to your Windows system directory (for example, C:\WINNT or -C:\WINNT\System32) -

    3. Build and install the Iconv library into the directory -C:\sdk\GnuWin32.

      Copy file C:\sdk\GnuWin32\bin\lib*.dll to your -Windows system directory (more installation instructions can be found in the -file README.woe32 in the iconv distribution).

      Note: instead of copying libexpat.dll and iconv.dll to the Windows -directory, you can add the directories -C:\sdk\Expat-2.0.0\Libs and -C:\sdk\GnuWin32\bin to the PATH environment -variable. -

    4. Install OpenSSL in C:\sdk\OpenSSL and add C:\sdk\OpenSSL\lib\VC to your path or copy the binaries to your system directory. -
    5. Install ZLib in C:\sdk\gnuWin32. Copy -C:\sdk\GnuWin32\bin\zlib1.dll to your system directory. If you change your path it should already be set after libiconv install. -
    6. Make sure the you can access Erlang binaries from your path. For example: set PATH=%PATH%;"C:\sdk\erl5.6.5\bin" -
    7. Depending on how you end up actually installing the library you might need to check and tweak the paths in the file configure.erl. -
    8. While in the directory ejabberd\src run: -
      configure.bat
      -nmake -f Makefile.win32
      -
    9. Edit the file ejabberd\src\ejabberd.cfg and run -
      werl -s ejabberd -name ejabberd
      -

    -

    2.5  Create a XMPP Account for Administration

    You need a XMPP account and grant him administrative privileges -to enter the ejabberd Web Admin: -

    1. -Register a XMPP account on your ejabberd server, for example admin1@example.org. -There are two ways to register a XMPP account: -
      1. -Using ejabberdctl (see section 4.1): -
        ejabberdctl register admin1 example.org FgT5bk3
        -
      2. Using a XMPP client and In-Band Registration (see section 3.3.18). -
      -
    2. Edit the ejabberd configuration file to give administration rights to the XMPP account you created: -
      {acl, admins, {user, "admin1", "example.org"}}.
      -{access, configure, [{allow, admins}]}.
      -
      You can grant administrative privileges to many XMPP accounts, -and also to accounts in other XMPP servers. -
    3. Restart ejabberd to load the new configuration. -
    4. Open the Web Admin (http://server:port/admin/) in your -favourite browser. Make sure to enter the full JID as username (in this -example: admin1@example.org. The reason that you also need to enter the -suffix, is because ejabberd’s virtual hosting support. -

    -

    2.6  Upgrading ejabberd

    To upgrade an ejabberd installation to a new version, -simply uninstall the old version, and then install the new one. -Of course, it is important that the configuration file -and Mnesia database spool directory are not removed.

    ejabberd automatically updates the Mnesia table definitions at startup when needed. -If you also use an external database for storage of some modules, -check if the release notes of the new ejabberd version -indicates you need to also update those tables.

    -

    Chapter 3  Configuring ejabberd

    -

    -

    3.1  Basic Configuration

    The configuration file will be loaded the first time you start ejabberd. The -content from this file will be parsed and stored in the internal ejabberd database. Subsequently the -configuration will be loaded from the database and any commands in the -configuration file are appended to the entries in the database.

    Note that ejabberd never edits the configuration file. -So, the configuration changes done using the Web Admin -are stored in the database, but are not reflected in the configuration file. -If you want those changes to be use after ejabberd restart, you can either -edit the configuration file, or remove all its content.

    The configuration file contains a sequence of Erlang terms. Lines beginning with a -‘%’ sign are ignored. Each term is a tuple of which the first element is -the name of an option, and any further elements are that option’s values. If the -configuration file do not contain for instance the ‘hosts’ option, the old -host name(s) stored in the database will be used.

    You can override the old values stored in the database by adding next lines to -the beginning of the configuration file: -

    override_global.
    -override_local.
    -override_acls.
    -

    With these lines the old global options (shared between all ejabberd nodes in a -cluster), local options (which are specific for this particular ejabberd node) -and ACLs will be removed before new ones are added.

    -

    3.1.1  Host Names

    -

    The option hosts defines a list containing one or more domains that -ejabberd will serve.

    The syntax is: -

    {hosts, [HostName, ...]}.

    Examples: -

    • -Serving one domain: -
      {hosts, ["example.org"]}.
      -
    • Serving three domains: -
      {hosts, ["example.net", "example.com", "jabber.somesite.org"]}.
      -

    -

    3.1.2  Virtual Hosting

    -

    Options can be defined separately for every virtual host using the -host_config option.

    The syntax is: -

    {host_config, HostName, [Option, ...]}

    Examples: -

    • -Domain example.net is using the internal authentication method while -domain example.com is using the LDAP server running on the -domain localhost to perform authentication: -
      {host_config, "example.net", [{auth_method,   internal}]}.
      -
      -{host_config, "example.com", [{auth_method,   ldap},
      -                              {ldap_servers,  ["localhost"]},
      -                              {ldap_uids,     [{"uid"}]},
      -                              {ldap_rootdn,   "dc=localdomain"},
      -                              {ldap_rootdn,   "dc=example,dc=com"},
      -                              {ldap_password, ""}]}.
      -
    • Domain example.net is using ODBC to perform authentication -while domain example.com is using the LDAP servers running on the domains -localhost and otherhost: -
      {host_config, "example.net", [{auth_method, odbc},
      -                              {odbc_server, "DSN=ejabberd;UID=ejabberd;PWD=ejabberd"}]}.
      -
      -{host_config, "example.com", [{auth_method,   ldap},
      -                              {ldap_servers,  ["localhost", "otherhost"]},
      -                              {ldap_uids,     [{"uid"}]},
      -                              {ldap_rootdn,   "dc=localdomain"},
      -                              {ldap_rootdn,   "dc=example,dc=com"},
      -                              {ldap_password, ""}]}.
      -

    To define specific ejabberd modules in a virtual host, -you can define the global modules option with the common modules, -and later add specific modules to certain virtual hosts. -To accomplish that, instead of defining each option in host_config with the general syntax -

    {OptionName, OptionValue}

    -use this syntax: -

    {{add, OptionName}, OptionValue}

    In this example three virtual hosts have some similar modules, but there are also -other different modules for some specific virtual hosts: -

    %% This ejabberd server has three vhosts:
    -{hosts, ["one.example.org", "two.example.org", "three.example.org"]}.
    -
    -%% Configuration of modules that are common to all vhosts
    -{modules,
    - [
    -  {mod_roster,     []},
    -  {mod_configure,  []},
    -  {mod_disco,      []},
    -  {mod_private,    []},
    -  {mod_time,       []},
    -  {mod_last,       []},
    -  {mod_version,    []}
    - ]}.
    -
    -%% Add some modules to vhost one:
    -{host_config, "one.example.org",
    - [{{add, modules}, [
    -                    {mod_echo,       [{host, "echo-service.one.example.org"}]}
    -                    {mod_http_bind,  []},
    -                    {mod_logxml,     []}
    -                   ]
    -  }
    - ]}.
    -
    -%% Add a module just to vhost two:
    -{host_config, "two.example.org",
    - [{{add, modules}, [
    -                    {mod_echo,       [{host, "mirror.two.example.org"}]}
    -                   ]
    -  }
    - ]}.
    -

    -

    3.1.3  Listening Ports

    -

    The option listen defines for which ports, addresses and network protocols ejabberd -will listen and what services will be run on them. Each element of the list is a -tuple with the following elements: -

    • -Port number. Optionally also the IP address and/or a transport protocol. -
    • Listening module that serves this port. -
    • Options for the TCP socket and for the listening module. -

    The option syntax is: -

    {listen, [Listener, ...]}.

    To define a listener there are several syntax. -

    {PortNumber, Module, [Option, ...]}
    {{PortNumber, IPaddress}, Module, [Option, ...]}
    {{PortNumber, TransportProtocol}, Module, [Option, ...]}
    {{PortNumber, IPaddress, TransportProtocol}, Module, [Option, ...]}

    -

    Port Number, IP Address and Transport Protocol

    The port number defines which port to listen for incoming connections. -It can be a Jabber/XMPP standard port -(see section 5.1) or any other valid port number.

    The IP address can be represented with a string -or an Erlang tuple with decimal or hexadecimal numbers. -The socket will listen only in that network interface. -It is possible to specify a generic address, -so ejabberd will listen in all addresses. -Depending in the type of the IP address, IPv4 or IPv6 will be used. -When not specified the IP address, it will listen on all IPv4 network addresses.

    Some example values for IP address: -

    • -"0.0.0.0" to listen in all IPv4 network interfaces. This is the default value when no IP is specified. -
    • "::" to listen in all IPv6 network interfaces -
    • "10.11.12.13" is the IPv4 address 10.11.12.13 -
    • "::FFFF:127.0.0.1" is the IPv6 address ::FFFF:127.0.0.1/128 -
    • {10, 11, 12, 13} is the IPv4 address 10.11.12.13 -
    • {0, 0, 0, 0, 0, 65535, 32512, 1} is the IPv6 address ::FFFF:127.0.0.1/128 -
    • {16#fdca, 16#8ab6, 16#a243, 16#75ef, 0, 0, 0, 1} is the IPv6 address FDCA:8AB6:A243:75EF::1/128 -

    The transport protocol can be tcp or udp. -Default is tcp.

    -

    Listening Module

    -The available modules, their purpose and the options allowed by each one are: -

    -ejabberd_c2s
    -Handles c2s connections.
    - Options: access, certfile, max_fsm_queue, -max_stanza_size, shaper, -starttls, starttls_required, tls, -zlib -
    ejabberd_s2s_in
    -Handles incoming s2s connections.
    - Options: max_stanza_size, shaper -
    ejabberd_service
    -Interacts with an external component -(as defined in the Jabber Component Protocol (XEP-0114).
    - Options: access, hosts, max_fsm_queue, -service_check_from, shaper -
    ejabberd_stun
    -Handles STUN Binding requests as defined in -RFC 5389.
    - Options: certfile -
    ejabberd_http
    -Handles incoming HTTP connections.
    - Options: captcha, certfile, http_bind, http_poll, -request_handlers, tls, web_admin
    -

    -

    Options

    This is a detailed description of each option allowed by the listening modules: -

    -{access, AccessName}
    This option defines -access to the port. The default value is all. -
    {backlog, Value}
    The backlog value -defines the maximum length that the queue of pending connections may -grow to. This should be increased if the server is going to handle -lots of new incoming connections as they may be dropped if there is -no space in the queue (and ejabberd was not able to accept them -immediately). Default value is 5. -
    captcha
    -Simple web page that allows a user to fill a CAPTCHA challenge (see section 3.1.8). -
    {certfile, Path}
    Full path to a file containing the default SSL certificate. -To define a certificate file specific for a given domain, use the global option domain_certfile. -
    {hosts, [Hostname, ...], [HostOption, ...]}
    -The external Jabber component that connects to this ejabberd_service -can serve one or more hostnames. -As HostOption you can define options for the component; -currently the only allowed option is the password required to the component -when attempt to connect to ejabberd: {password, Secret}. -Note that you cannot define in a single ejabberd_service components of -different services: add an ejabberd_service for each service, -as seen in an example below. -
    http_bind
    -This option enables HTTP Binding (XEP-0124 and XEP-0206) support. HTTP Bind -enables access via HTTP requests to ejabberd from behind firewalls which -do not allow outgoing sockets on port 5222.

    Remember that you must also install and enable the module mod_http_bind.

    If HTTP Bind is enabled, it will be available at -http://server:port/http-bind/. Be aware that support for HTTP Bind -is also needed in the XMPP client. Remark also that HTTP Bind can be -interesting to host a web-based XMPP client such as -JWChat -(check the tutorials to install JWChat with ejabberd and an -embedded local web server -or Apache). -

    http_poll
    -This option enables HTTP Polling (XEP-0025) support. HTTP Polling -enables access via HTTP requests to ejabberd from behind firewalls which -do not allow outgoing sockets on port 5222.

    If HTTP Polling is enabled, it will be available at -http://server:port/http-poll/. Be aware that support for HTTP Polling -is also needed in the XMPP client. Remark also that HTTP Polling can be -interesting to host a web-based XMPP client such as -JWChat.

    The maximum period of time to keep a client session active without -an incoming POST request can be configured with the global option -http_poll_timeout. The default value is five minutes. -The option can be defined in ejabberd.cfg, expressing the time -in seconds: {http_poll_timeout, 300}. -

    {max_fsm_queue, Size}
    -This option specifies the maximum number of elements in the queue of the FSM -(Finite State Machine). -Roughly speaking, each message in such queues represents one XML -stanza queued to be sent into its relevant outgoing stream. If queue size -reaches the limit (because, for example, the receiver of stanzas is too slow), -the FSM and the corresponding connection (if any) will be terminated -and error message will be logged. -The reasonable value for this option depends on your hardware configuration. -However, there is no much sense to set the size above 1000 elements. -This option can be specified for ejabberd_service and -ejabberd_c2s listeners, -or also globally for ejabberd_s2s_out. -If the option is not specified for ejabberd_service or -ejabberd_c2s listeners, -the globally configured value is used. -The allowed values are integers and ’undefined’. -Default value: ’undefined’. -
    {max_stanza_size, Size}
    -This option specifies an -approximate maximum size in bytes of XML stanzas. Approximate, -because it is calculated with the precision of one block of read -data. For example {max_stanza_size, 65536}. The default -value is infinity. Recommended values are 65536 for c2s -connections and 131072 for s2s connections. s2s max stanza size -must always much higher than c2s limit. Change this value with -extreme care as it can cause unwanted disconnect if set too low. -
    {request_handlers, [ {Path, Module}, ...]}
    To define one or several handlers that will serve HTTP requests. -The Path is a list of strings; so the URIs that start with that Path will be served by Module. -For example, if you want mod_foo to serve the URIs that start with /a/b/, -and you also want mod_http_bind to serve the URIs /http-bind/, -use this option: {request_handlers, [{["a", "b"], mod_foo}, {["http-bind"], mod_http_bind}]} -
    {service_check_from, true|false}
    - -This option can be used with ejabberd_service only. -XEP-0114 requires that the domain must match the hostname of the component. -If this option is set to false, ejabberd will allow the component -to send stanzas with any arbitrary domain in the ’from’ attribute. -Only use this option if you are completely sure about it. -The default value is true, to be compliant with XEP-0114. -
    {shaper, none|ShaperName}
    This option defines a -shaper for the port (see section 3.1.6). The default value -is none. -
    starttls
    This option -specifies that STARTTLS encryption is available on connections to the port. -You should also set the certfile option. -You can define a certificate file for a specific domain using the global option domain_certfile. -
    starttls_required
    This option -specifies that STARTTLS encryption is required on connections to the port. -No unencrypted connections will be allowed. -You should also set the certfile option. -You can define a certificate file for a specific domain using the global option domain_certfile. -
    tls
    This option specifies that traffic on -the port will be encrypted using SSL immediately after connecting. -This was the traditional encryption method in the early Jabber software, -commonly on port 5223 for client-to-server communications. -But this method is nowadays deprecated and not recommended. -The preferable encryption method is STARTTLS on port 5222, as defined -RFC 3920: XMPP Core, -which can be enabled in ejabberd with the option starttls. -If this option is set, you should also set the certfile option. -The option tls can also be used in ejabberd_http to support HTTPS. -
    web_admin
    This option -enables the Web Admin for ejabberd administration which is available -at http://server:port/admin/. Login and password are the username and -password of one of the registered users who are granted access by the -‘configure’ access rule. -
    zlib
    This -option specifies that Zlib stream compression (as defined in XEP-0138) -is available on connections to the port. -

    There are some additional global options that can be specified in the ejabberd configuration file (outside listen): -

    -{s2s_use_starttls, true|false}
    -This option defines whether to -use STARTTLS for s2s connections. -
    {s2s_certfile, Path}
    Full path to a -file containing a SSL certificate. -
    {domain_certfile, Domain, Path}
    -Full path to the file containing the SSL certificate for a specific domain. -
    {outgoing_s2s_options, Methods, Timeout}
    -Specify which address families to try, in what order, and connect timeout in milliseconds. -By default it first tries connecting with IPv4, if that fails it tries using IPv6, -with a timeout of 10000 milliseconds. -
    {s2s_dns_options, [ {Property, Value}, ...]}
    -Define properties to use for DNS resolving. -Allowed Properties are: timeout in seconds which default value is 10 -and retries which default value is 2. -
    {s2s_default_policy, allow|deny}
    -The default policy for incoming and outgoing s2s connections to other XMPP servers. -The default value is allow. -
    {{s2s_host, Host}, allow|deny}
    -Defines if incoming and outgoing s2s connections with a specific remote host are allowed or denied. -This allows to restrict ejabberd to only establish s2s connections -with a small list of trusted servers, or to block some specific servers. -
    {s2s_max_retry_delay, Seconds}
    -The maximum allowed delay for retry to connect after a failed connection attempt. -Specified in seconds. The default value is 300 seconds (5 minutes). -
    {max_fsm_queue, Size}
    -This option specifies the maximum number of elements in the queue of the FSM -(Finite State Machine). -Roughly speaking, each message in such queues represents one XML -stanza queued to be sent into its relevant outgoing stream. If queue size -reaches the limit (because, for example, the receiver of stanzas is too slow), -the FSM and the corresponding connection (if any) will be terminated -and error message will be logged. -The reasonable value for this option depends on your hardware configuration. -However, there is no much sense to set the size above 1000 elements. -This option can be specified for ejabberd_service and -ejabberd_c2s listeners, -or also globally for ejabberd_s2s_out. -If the option is not specified for ejabberd_service or -ejabberd_c2s listeners, -the globally configured value is used. -The allowed values are integers and ’undefined’. -Default value: ’undefined’. -
    {route_subdomains, local|s2s}
    -Defines if ejabberd must route stanzas directed to subdomains locally (compliant with -RFC 3920: XMPP Core), -or to foreign server using S2S (compliant with -RFC 3920 bis). -

    -

    Examples

    For example, the following simple configuration defines: -

    • -There are three domains. The default certificate file is server.pem. -However, the c2s and s2s connections to the domain example.com use the file example_com.pem. -
    • Port 5222 listens for c2s connections with STARTTLS, -and also allows plain connections for old clients. -
    • Port 5223 listens for c2s connections with the old SSL. -
    • Port 5269 listens for s2s connections with STARTTLS. The socket is set for IPv6 instead of IPv4. -
    • Port 3478 listens for STUN requests over UDP. -
    • Port 5280 listens for HTTP requests, and serves the HTTP Poll service. -
    • Port 5281 listens for HTTP requests, and serves the Web Admin using HTTPS as explained in -section 4.3. The socket only listens connections to the IP address 127.0.0.1. -
    {hosts, ["example.com", "example.org", "example.net"]}.
    -{listen,
    - [
    -  {5222, ejabberd_c2s, [
    -                        {access, c2s},
    -                        {shaper, c2s_shaper},
    -                        starttls, {certfile, "/etc/ejabberd/server.pem"},
    -                        {max_stanza_size, 65536}
    -                       ]},
    -  {5223, ejabberd_c2s, [
    -                        {access, c2s},
    -                        {shaper, c2s_shaper},
    -                        tls, {certfile, "/etc/ejabberd/server.pem"},
    -                        {max_stanza_size, 65536}
    -                       ]},
    -  {{5269, "::"}, ejabberd_s2s_in, [
    -                                   {shaper, s2s_shaper},
    -                                   {max_stanza_size, 131072}
    -                                  ]},
    -  {{3478, udp}, ejabberd_stun, []},
    -  {5280, ejabberd_http, [
    -                         http_poll
    -                        ]},
    -  {{5281, "127.0.0.1"}, ejabberd_http, [
    -                                        web_admin,
    -                                        tls, {certfile, "/etc/ejabberd/server.pem"},
    -                                       ]}
    - ]
    -}.
    -{s2s_use_starttls, true}.
    -{s2s_certfile, "/etc/ejabberd/server.pem"}.
    -{domain_certfile, "example.com", "/etc/ejabberd/example_com.pem"}.
    -

    In this example, the following configuration defines that: -

    • -c2s connections are listened for on port 5222 (all IPv4 addresses) and -on port 5223 (SSL, IP 192.168.0.1 and fdca:8ab6:a243:75ef::1) and denied -for the user called ‘bad’. -
    • s2s connections are listened for on port 5269 (all IPv4 addresses) -with STARTTLS for secured traffic enabled. -Incoming and outgoing connections of remote XMPP servers are denied, -only two servers can connect: "jabber.example.org" and "example.com". -
    • Port 5280 is serving the Web Admin and the HTTP Polling service -in all the IPv4 addresses. Note -that it is also possible to serve them on different ports. The second -example in section 4.3 shows how exactly this can be done. -
    • All users except for the administrators have a traffic of limit -1,000 Bytes/second -
    • The -AIM transport -aim.example.org is connected to port 5233 on localhost IP addresses -(127.0.0.1 and ::1) with password ‘aimsecret’. -
    • The ICQ transport JIT (icq.example.org and -sms.example.org) is connected to port 5234 with password -‘jitsecret’. -
    • The -MSN transport -msn.example.org is connected to port 5235 with password -‘msnsecret’. -
    • The -Yahoo! transport -yahoo.example.org is connected to port 5236 with password -‘yahoosecret’. -
    • The Gadu-Gadu transport gg.example.org is -connected to port 5237 with password ‘ggsecret’. -
    • The -Jabber Mail Component -jmc.example.org is connected to port 5238 with password -‘jmcsecret’. -
    • The service custom has enabled the special option to avoiding checking the from attribute in the packets send by this component. The component can send packets in behalf of any users from the server, or even on behalf of any server. -
    {acl, blocked, {user, "bad"}}.
    -{access, c2s, [{deny, blocked},
    -               {allow, all}]}.
    -{shaper, normal, {maxrate, 1000}}.
    -{access, c2s_shaper, [{none, admin},
    -                      {normal, all}]}.
    -{listen,
    - [{5222, ejabberd_c2s, [
    -                        {access, c2s},
    -                        {shaper, c2s_shaper}
    -                       ]},
    -  {{5223, {192, 168, 0, 1}}, ejabberd_c2s, [
    -                                            {access, c2s},
    -                                            ssl, {certfile, "/path/to/ssl.pem"}
    -                                           ]},
    -  {{5223, {16#fdca, 16#8ab6, 16#a243, 16#75ef, 0, 0, 0, 1}},
    -   ejabberd_c2s, [
    -                  {access, c2s},
    -                  ssl, {certfile, "/path/to/ssl.pem"}
    -                 ]},
    -  {5269, ejabberd_s2s_in, []},
    -  {{5280, {0, 0, 0, 0}}, ejabberd_http, [
    -                                         http_poll,
    -                                         web_admin
    -                                        ]},
    -  {{5233, {127, 0, 0, 1}}, ejabberd_service, [
    -                                              {hosts, ["aim.example.org"],
    -                                                 [{password, "aimsecret"}]}
    -                                             ]},
    -  {{5233, "::1"}, ejabberd_service, [
    -                                     {hosts, ["aim.example.org"],
    -                                        [{password, "aimsecret"}]}
    -                                    ]},
    -  {5234, ejabberd_service, [{hosts, ["icq.example.org", "sms.example.org"],
    -                             [{password, "jitsecret"}]}]},
    -  {5235, ejabberd_service, [{hosts, ["msn.example.org"],
    -                             [{password, "msnsecret"}]}]},
    -  {5236, ejabberd_service, [{hosts, ["yahoo.example.org"],
    -                             [{password, "yahoosecret"}]}]},
    -  {5237, ejabberd_service, [{hosts, ["gg.example.org"],
    -                             [{password, "ggsecret"}]}]},
    -  {5238, ejabberd_service, [{hosts, ["jmc.example.org"],
    -                             [{password, "jmcsecret"}]}]},
    -  {5239, ejabberd_service, [{hosts, ["custom.example.org"],
    -                             [{password, "customsecret"}]},
    -                            {service_check_from, false}]}
    - ]
    -}.
    -{s2s_use_starttls, true}.
    -{s2s_certfile, "/path/to/ssl.pem"}.
    -{s2s_default_policy, deny}.
    -{{s2s_host,"jabber.example.org"}, allow}.
    -{{s2s_host,"example.com"}, allow}.
    -

    Note, that for services based in jabberd14 or WPJabber -you have to make the transports log and do XDB by themselves: -

      <!--
    -     You have to add elogger and rlogger entries here when using ejabberd.
    -     In this case the transport will do the logging.
    -  -->
    -
    -  <log id='logger'>
    -    <host/>
    -    <logtype/>
    -    <format>%d: [%t] (%h): %s</format>
    -    <file>/var/log/jabber/service.log</file>
    -  </log>
    -
    -  <!--
    -     Some XMPP server implementations do not provide
    -     XDB services (for example, jabberd2 and ejabberd).
    -     xdb_file.so is loaded in to handle all XDB requests.
    -  -->
    -
    -  <xdb id="xdb">
    -    <host/>
    -    <load>
    -      <!-- this is a lib of wpjabber or jabberd14 -->
    -      <xdb_file>/usr/lib/jabber/xdb_file.so</xdb_file>
    -      </load>
    -    <xdb_file xmlns="jabber:config:xdb_file">
    -      <spool><jabberd:cmdline flag='s'>/var/spool/jabber</jabberd:cmdline></spool>
    -    </xdb_file>
    -  </xdb>
    -

    -

    3.1.4  Authentication

    -

    The option auth_method defines the authentication methods that are used -for user authentication. The syntax is: -

    {auth_method, [Method, ...]}.

    The following authentication methods are supported by ejabberd: -

    • -internal (default) — See section 3.1.4. -
    • external — See section 3.1.4. -
    • ldap — See section 3.2.5. -
    • odbc — See section 3.2.1, 3.2.3, -3.2.2 and 3.2.4. -
    • anonymous — See section 3.1.4. -
    • pam — See section 3.1.4. -

    Account creation is only supported by internal, external and odbc methods.

    -

    Internal

    -

    ejabberd uses its internal Mnesia database as the default authentication method. -The value internal will enable the internal authentication method.

    Examples: -

    • -To use internal authentication on example.org and LDAP -authentication on example.net: -
      {host_config, "example.org", [{auth_method, [internal]}]}.
      -{host_config, "example.net", [{auth_method, [ldap]}]}.
      -
    • To use internal authentication on all virtual hosts: -
      {auth_method, internal}.
      -

    -

    External Script

    -

    In this authentication method, when ejabberd starts, -it start a script, and calls it to perform authentication tasks.

    The server administrator can write the external authentication script -in any language. -The details on the interface between ejabberd and the script are described -in the ejabberd Developers Guide. -There are also several example authentication scripts.

    These are the specific options: -

    -{extauth_program, PathToScript}
    -Indicate in this option the full path to the external authentication script. -The script must be executable by ejabberd.
    {extauth_instances, Integer}
    -Indicate how many instances of the script to run simultaneously to serve authentication in the virtual host. -The default value is the minimum number: 1.
    {extauth_cache, false|CacheTimeInteger}
    -The value false disables the caching feature, this is the default. -The integer 0 (zero) enables caching for statistics, but doesn’t use that cached information to authenticate users. -If another integer value is set, caching is enabled both for statistics and for authentication: -the CacheTimeInteger indicates the number of seconds that ejabberd can reuse -the authentication information since the user last disconnected, -to verify again the user authentication without querying again the extauth script. -Note: caching should not be enabled in a host if internal auth is also enabled. -If caching is enabled, mod_last or mod_last_odbc must be enabled also in that vhost. -

    This example sets external authentication, the extauth script, enables caching for 10 minutes, -and starts three instances of the script for each virtual host defined in ejabberd: -

    {auth_method, [external]}.
    -{extauth_program, "/etc/ejabberd/JabberAuth.class.php"}.
    -{extauth_cache, 600}.
    -{extauth_instances, 3}. 
    -

    -

    SASL Anonymous and Anonymous Login

    -

    The value anonymous will enable the internal authentication method.

    The anonymous authentication method can be configured with the following -options. Remember that you can use the host_config option to set virtual -host specific options (see section 3.1.2). Note that there also -is a detailed tutorial regarding SASL -Anonymous and anonymous login configuration.

    -{allow_multiple_connections, false|true}
    This option is only used -when the anonymous mode is -enabled. Setting it to true means that the same username can be taken -multiple times in anonymous login mode if different resource are used to -connect. This option is only useful in very special occasions. The default -value is false. -
    {anonymous_protocol, sasl_anon | login_anon | both}
    -sasl_anon means -that the SASL Anonymous method will be used. login_anon means that the -anonymous login method will be used. both means that SASL Anonymous and -login anonymous are both enabled. -

    Those options are defined for each virtual host with the host_config -parameter (see section 3.1.2).

    Examples: -

    • -To enable anonymous login on all virtual hosts: -
      {auth_method, [anonymous]}.
      -{anonymous_protocol, login_anon}.
      -
    • Similar as previous example, but limited to public.example.org: -
      {host_config, "public.example.org", [{auth_method, [anonymous]},
      -                                     {anonymous_protocol, login_anon}]}.
      -
    • To enable anonymous login and internal authentication on a virtual host: -
      {host_config, "public.example.org", [{auth_method, [internal,anonymous]},
      -                                     {anonymous_protocol, login_anon}]}.
      -
    • To enable SASL Anonymous on a virtual host: -
      {host_config, "public.example.org", [{auth_method, [anonymous]},
      -                                     {anonymous_protocol, sasl_anon}]}.
      -
    • To enable SASL Anonymous and anonymous login on a virtual host: -
      {host_config, "public.example.org", [{auth_method, [anonymous]},
      -                                     {anonymous_protocol, both}]}.
      -
    • To enable SASL Anonymous, anonymous login, and internal authentication on -a virtual host: -
      {host_config, "public.example.org", [{auth_method, [internal,anonymous]},
      -                                     {anonymous_protocol, both}]}.
      -

    -

    PAM Authentication

    -

    ejabberd supports authentication via Pluggable Authentication Modules (PAM). -PAM is currently supported in AIX, FreeBSD, HP-UX, Linux, Mac OS X, NetBSD and Solaris. -PAM authentication is disabled by default, so you have to configure and compile -ejabberd with PAM support enabled: -

    ./configure --enable-pam && make install
    -

    Options: -

    -{pam_service, Name}
    This option defines the PAM service name. -Default is "ejabberd". Refer to the PAM documentation of your operation system -for more information. -
    {pam_userinfotype, username|jid}
    -This option defines what type of information about the user ejabberd -provides to the PAM service: only the username, or the user JID. -Default is username. -

    Example: -

    {auth_method, [pam]}.
    -{pam_service, "ejabberd"}.
    -

    Though it is quite easy to set up PAM support in ejabberd, PAM itself introduces some -security issues:

    • -To perform PAM authentication ejabberd uses external C-program called -epam. By default, it is located in /var/lib/ejabberd/priv/bin/ -directory. You have to set it root on execution in the case when your PAM module -requires root privileges (pam_unix.so for example). Also you have to grant access -for ejabberd to this file and remove all other permissions from it. -Execute with root privileges: -
      chown root:ejabberd /var/lib/ejabberd/priv/bin/epam
      -chmod 4750 /var/lib/ejabberd/priv/bin/epam
      -
    • Make sure you have the latest version of PAM installed on your system. -Some old versions of PAM modules cause memory leaks. If you are not able to use the latest -version, you can kill(1) epam process periodically to reduce its memory -consumption: ejabberd will restart this process immediately. -
    • epam program tries to turn off delays on authentication failures. -However, some PAM modules ignore this behavior and rely on their own configuration options. -You can create a configuration file ejabberd.pam. -This example shows how to turn off delays in pam_unix.so module: -
      #%PAM-1.0
      -auth        sufficient  pam_unix.so likeauth nullok nodelay
      -account     sufficient  pam_unix.so
      -
      That is not a ready to use configuration file: you must use it -as a hint when building your own PAM configuration instead. Note that if you want to disable -delays on authentication failures in the PAM configuration file, you have to restrict access -to this file, so a malicious user can’t use your configuration to perform brute-force -attacks. -
    • You may want to allow login access only for certain users. pam_listfile.so -module provides such functionality. -
    • If you use pam_winbind to authorise against a Windows Active Directory, -then /etc/nssswitch.conf must be configured to use winbind as well. -

    -

    3.1.5  Access Rules

    -

    -

    ACL Definition

    -

    Access control in ejabberd is performed via Access Control Lists (ACLs). The -declarations of ACLs in the configuration file have the following syntax: -

    {acl, ACLName, ACLValue}.

    ACLValue can be one of the following: -

    -all
    Matches all JIDs. Example: -
    {acl, all, all}.
    -
    {user, Username}
    Matches the user with the name -Username at the first virtual host. Example: -
    {acl, admin, {user, "yozhik"}}.
    -
    {user, Username, Server}
    Matches the user with the JID -Username@Server and any resource. Example: -
    {acl, admin, {user, "yozhik", "example.org"}}.
    -
    {server, Server}
    Matches any JID from server -Server. Example: -
    {acl, exampleorg, {server, "example.org"}}.
    -
    {resource, Resource}
    Matches any JID with a resource -Resource. Example: -
    {acl, mucklres, {resource, "muckl"}}.
    -
    {shared_group, Groupname}
    Matches any member of a Shared Roster Group with name Groupname in the virtual host. Example: -
    {acl, techgroupmembers, {shared_group, "techteam"}}.
    -
    {shared_group, Groupname, Server}
    Matches any member of a Shared Roster Group with name Groupname in the virtual host Server. Example: -
    {acl, techgroupmembers, {shared_group, "techteam", "example.org"}}.
    -
    {user_regexp, Regexp}
    Matches any local user with a name that -matches Regexp on local virtual hosts. Example: -
    {acl, tests, {user_regexp, "^test[0-9]*$"}}.
    -
    {user_regexp, UserRegexp, Server}
    Matches any user with a name -that matches Regexp at server Server. Example: -
    {acl, tests, {user_Userregexp, "^test", "example.org"}}.
    -
    {server_regexp, Regexp}
    Matches any JID from the server that -matches Regexp. Example: -
    {acl, icq, {server_regexp, "^icq\\."}}.
    -
    {resource_regexp, Regexp}
    Matches any JID with a resource that -matches Regexp. Example: -
    {acl, icq, {resource_regexp, "^laptop\\."}}.
    -
    {node_regexp, UserRegexp, ServerRegexp}
    Matches any user -with a name that matches UserRegexp at any server that matches -ServerRegexp. Example: -
    {acl, yohzik, {node_regexp, "^yohzik$", "^example.(com|org)$"}}.
    -
    {user_glob, Glob}
    -
    {user_glob, Glob, Server}
    -
    {server_glob, Glob}
    -
    {resource_glob, Glob}
    -
    {node_glob, UserGlob, ServerGlob}
    This is the same as -above. However, it uses shell glob patterns instead of regexp. These patterns -can have the following special characters: -
    -*
    matches any string including the null string. -
    ?
    matches any single character. -
    [...]
    matches any of the enclosed characters. Character -ranges are specified by a pair of characters separated by a ‘-’. -If the first character after ‘[’ is a ‘!’, any -character not enclosed is matched. -
    -

    The following ACLName are pre-defined: -

    -all
    Matches any JID. -
    none
    Matches no JID. -

    -

    Access Rights

    -

    An entry allowing or denying access to different services. -The syntax is: -

    {access, AccessName, [ {allow|deny, ACLName}, ...]}.

    When a JID is checked to have access to Accessname, the server -sequentially checks if that JID matches any of the ACLs that are named in the -second elements of the tuples in the list. If it matches, the first element of -the first matched tuple is returned, otherwise the value ‘deny’ is -returned.

    If you define specific Access rights in a virtual host, -remember that the globally defined Access rights have precedence over those. -This means that, in case of conflict, the Access granted or denied in the global server is used -and the Access of a virtual host doesn’t have effect.

    Example: -

    {access, configure, [{allow, admin}]}.
    -{access, something, [{deny, badmans},
    -                     {allow, all}]}.
    -

    The following AccessName are pre-defined: -

    -all
    Always returns the value ‘allow’. -
    none
    Always returns the value ‘deny’. -

    -

    Limiting Opened Sessions with ACL

    -

    The special access max_user_sessions specifies the maximum -number of sessions (authenticated connections) per user. If a user -tries to open more sessions by using different resources, the first -opened session will be disconnected. The error session replaced -will be sent to the disconnected session. The value for this option -can be either a number, or infinity. The default value is -infinity.

    The syntax is: -

    {access, max_user_sessions, [ {MaxNumber, ACLName}, ...]}.

    This example limits the number of sessions per user to 5 for all users, and to 10 for admins: -

    {access, max_user_sessions, [{10, admin}, {5, all}]}.
    -

    -

    Several connections to a remote XMPP server with ACL

    -

    The special access max_s2s_connections specifies how many -simultaneous S2S connections can be established to a specific remote XMPP server. -The default value is 1. -There’s also available the access max_s2s_connections_per_node.

    The syntax is: -

    {access, max_s2s_connections, [ {MaxNumber, ACLName}, ...]}.

    Examples: -

    • -Allow up to 3 connections with each remote server: -
      {access, max_s2s_connections, [{3, all}]}.
      -

    -

    3.1.6  Shapers

    -

    Shapers enable you to limit connection traffic. -The syntax is: -

    {shaper, ShaperName, Kind}.

    -Currently only one kind of shaper called maxrate is available. It has the -following syntax: -

    {maxrate, Rate}

    -where Rate stands for the maximum allowed incoming rate in bytes per -second. -When a connection exceeds this limit, ejabberd stops reading from the socket -until the average rate is again below the allowed maximum.

    Examples: -

    • -To define a shaper named ‘normal’ with traffic speed limited to -1,000 bytes/second: -
      {shaper, normal, {maxrate, 1000}}.
      -
    • To define a shaper named ‘fast’ with traffic speed limited to -50,000 bytes/second: -
      {shaper, fast, {maxrate, 50000}}.
      -

    -

    3.1.7  Default Language

    -

    The option language defines the default language of server strings that -can be seen by XMPP clients. If a XMPP client does not support -xml:lang, the specified language is used.

    The option syntax is: -

    {language, Language}.

    The default value is en. -In order to take effect there must be a translation file -Language.msg in ejabberd’s msgs directory.

    For example, to set Russian as default language: -

    {language, "ru"}.
    -

    Appendix A provides more details about internationalization and localization.

    -

    3.1.8  CAPTCHA

    -

    Some ejabberd modules can be configured to require a CAPTCHA challenge on certain actions. -If the client does not support CAPTCHA Forms (XEP-0158), -a web link is provided so the user can fill the challenge in a web browser.

    An example script is provided that generates the image -using ImageMagick’s Convert program.

    The configurable options are: -

    -{captcha_cmd, Path}
    -Full path to a script that generates the image. -The default value is an empty string: "" -
    {captcha_host, Host}
    -Host part of the URL sent to the user. -You can include the port number. -The URL sent to the user is formed by: http://Host/captcha/ -The default value is the first hostname configured. -

    Additionally, an ejabberd_http listener must be enabled with the captcha option. -See section 3.1.3.

    Example configuration: -

    {hosts, ["example.org"]}.
    -
    -{captcha_cmd, "/lib/ejabberd/priv/bin/captcha.sh"}.
    -{captcha_host, "example.org:5280"}.
    -
    -{listen,
    - [
    -  ...
    -  {5280, ejabberd_http, [
    -                         captcha,
    -                         ...
    -                        ]
    -  }
    -
    -]}.
    -

    -

    3.1.9  STUN

    -

    ejabberd is able to act as a stand-alone STUN server -(RFC 5389). Currently only Binding usage -is supported. In that role ejabberd helps clients with Jingle ICE (XEP-0176) support to discover their external addresses and ports.

    You should configure ejabberd_stun listening module as described in 3.1.3 section. -If certfile option is defined, ejabberd multiplexes TCP and -TLS over TCP connections on the same port. Obviously, certfile option -is defined for tcp only. Note however that TCP or TLS over TCP -support is not required for Binding usage and is reserved for -TURN -functionality. Feel free to configure udp transport only.

    Example configuration: -

    {listen,
    - [
    -  ...
    -  {{3478, udp}, ejabberd_stun, []},
    -  {3478, ejabberd_stun, []},
    -  {5349, ejabberd_stun, [{certfile, "/etc/ejabberd/server.pem"}]},
    -  ...
    - ]
    -}.
    -

    You also need to configure DNS SRV records properly so clients can easily discover a -STUN server serving your XMPP domain. Refer to section -DNS Discovery of a Server -of RFC 5389 for details.

    Example DNS SRV configuration: -

    _stun._udp   IN SRV  0 0 3478 stun.example.com.
    -_stun._tcp   IN SRV  0 0 3478 stun.example.com.
    -_stuns._tcp  IN SRV  0 0 5349 stun.example.com.
    -

    -

    3.1.10  Include Additional Configuration Files

    -

    The option include_config_file in a configuration file instructs ejabberd to include other configuration files immediately.

    The basic syntax is: -

    {include_config_file, Filename}.

    -It is possible to specify suboptions using the full syntax: -

    {include_config_file, Filename, [Suboption, ...]}.

    The filename can be indicated either as an absolute path, -or relative to the main ejabberd configuration file. -It isn’t possible to use wildcards. -The file must exist and be readable.

    The allowed suboptions are: -

    -{disallow, [Optionname, ...]}
    Disallows the usage of those options in the included configuration file. -The options that match this criteria are not accepted. -The default value is an empty list: [] -
    {allow_only, [Optionname, ...]}
    Allows only the usage of those options in the included configuration file. -The options that do not match this criteria are not accepted. -The default value is: all -

    This is a basic example: -

    {include_config_file, "/etc/ejabberd/additional.cfg"}.
    -

    In this example, the included file is not allowed to contain a listen option. -If such an option is present, the option will not be accepted. -The file is in a subdirectory from where the main configuration file is. -

    {include_config_file, "./example.org/additional_not_listen.cfg", [{disallow, [listen]}]}.
    -

    In this example, ejabberd.cfg defines some ACL and Access rules, -and later includes another file with additional rules: -

    {acl, admin, {user, "admin", "localhost"}}.
    -{access, announce, [{allow, admin}]}.
    -{include_config_file, "/etc/ejabberd/acl_and_access.cfg", [{allow_only, [acl, access]}]}.
    -

    and content of the file acl_and_access.cfg can be, for example: -

    {acl, admin, {user, "bob", "localhost"}}.
    -{acl, admin, {user, "jan", "localhost"}}.
    -

    -

    3.1.11  Option Macros in Configuration File

    -

    In the ejabberd configuration file, -it is possible to define a macro for a value -and later use this macro when defining an option.

    A macro is defined with this syntax: -

    {define_macro, ’MACRO’, Value}.

    -The MACRO must be surrounded by single quotation marks, -and all letters in uppercase; check the examples bellow. -The value can be any valid arbitrary Erlang term.

    The first definition of a macro is preserved, -and additional definitions of the same macro are forgotten.

    Macros are processed after -additional configuration files have been included, -so it is possible to use macros that -are defined in configuration files included before the usage.

    It isn’t possible to use a macro in the definition -of another macro.

    There are two ways to use a macro: -

    ’MACRO’
    -You can put this instead of a value in an ejabberd option, -and will be replaced with the value previously defined. -If the macro is not defined previously, -the program will crash and report an error.
    {use_macro, ’MACRO’, Defaultvalue}
    -Use a macro even if it may not be defined. -If the macro is not defined previously, -the provided defaultvalue is used. -This usage behaves as if it were defined and used this way: -
    {define_macro, 'MACRO', Defaultvalue}.
    -'MACRO'
    -

    This example shows the basic usage of a macro: -

    {define_macro, 'LOG_LEVEL_NUMBER', 5}.
    -{loglevel, 'LOG_LEVEL_NUMBER'}.
    -

    The resulting option interpreted by ejabberd is: {loglevel, 5}.

    This example shows that values can be any arbitrary Erlang term: -

    {define_macro, 'USERBOB', {user, "bob", "localhost"}}.
    -{acl, admin, 'USERBOB'}.
    -

    The resulting option interpreted by ejabberd is: {acl, admin, {user, "bob", "localhost"}}.

    This complex example: -

    {define_macro, 'NUMBER_PORT_C2S', 5222}.
    -{define_macro, 'PORT_S2S_IN', {5269, ejabberd_s2s_in, []}}.
    -{listen,
    - [
    -  {'NUMBER_PORT_C2S', ejabberd_c2s, []},
    -  'PORT_S2S_IN',
    -  {{use_macro, 'NUMBER_PORT_HTTP', 5280}, ejabberd_http, []}
    - ]
    -}.
    -

    produces this result after being interpreted: -

    {listen,
    - [
    -  {5222, ejabberd_c2s, []},
    -  {5269, ejabberd_s2s_in, []},
    -  {5280, ejabberd_http, []}
    - ]
    -}.
    -

    -

    3.2  Database and LDAP Configuration

    - -

    ejabberd uses its internal Mnesia database by default. However, it is -possible to use a relational database or an LDAP server to store persistent, -long-living data. ejabberd is very flexible: you can configure different -authentication methods for different virtual hosts, you can configure different -authentication mechanisms for the same virtual host (fallback), you can set -different storage systems for modules, and so forth.

    The following databases are supported by ejabberd: -

    The following LDAP servers are tested with ejabberd: -

    • -Active Directory -(see section 3.2.5) -
    • OpenLDAP -
    • Normally any LDAP compatible server should work; inform us about your -success with a not-listed server so that we can list it here. -

    Important note about virtual hosting: -if you define several domains in ejabberd.cfg (see section 3.1.1), -you probably want that each virtual host uses a different configuration of database, authentication and storage, -so that usernames do not conflict and mix between different virtual hosts. -For that purpose, the options described in the next sections -must be set inside a host_config for each vhost (see section 3.1.2). -For example: -

    {host_config, "public.example.org", [
    -  {odbc_server, {pgsql, "localhost", "database-public-example-org", "ejabberd", "password"}},
    -  {auth_method, [odbc]}
    -]}.
    -

    -

    3.2.1  MySQL

    -

    Although this section will describe ejabberd’s configuration when you want to -use the native MySQL driver, it does not describe MySQL’s installation and -database creation. Check the MySQL documentation and the tutorial Using ejabberd with MySQL native driver for information regarding these topics. -Note that the tutorial contains information about ejabberd’s configuration -which is duplicate to this section.

    Moreover, the file mysql.sql in the directory src/odbc might be interesting for -you. This file contains the ejabberd schema for MySQL. At the end of the file -you can find information to update your database schema.

    -

    Driver Compilation

    -

    You can skip this step if you installed ejabberd using a binary installer or -if the binary packages of ejabberd you are using include support for MySQL.

    1. -First, install the Erlang -MySQL library. Make sure the compiled files are in your Erlang path; you can -put them for example in the same directory as your ejabberd .beam files. -
    2. Then, configure and install ejabberd with ODBC support enabled (this is -also needed for native MySQL support!). This can be done, by using next -commands: -
      ./configure --enable-odbc && make install
      -

    -

    Database Connection

    -

    The actual database access is defined in the option odbc_server. Its -value is used to define if we want to use ODBC, or one of the two native -interface available, PostgreSQL or MySQL.

    To use the native MySQL interface, you can pass a tuple of the following form as -parameter: -

    {mysql, "Server", "Database", "Username", "Password"}

    mysql is a keyword that should be kept as is. For example: -

    {odbc_server, {mysql, "localhost", "test", "root", "password"}}.

    Optionally, it is possible to define the MySQL port to use. This -option is only useful, in very rare cases, when you are not running -MySQL with the default port setting. The mysql parameter -can thus take the following form: -

    {mysql, "Server", Port, "Database", "Username", "Password"}

    The Port value should be an integer, without quotes. For example: -

    {odbc_server, {mysql, "localhost", Port, "test", "root", "password"}}.

    By default ejabberd opens 10 connections to the database for each virtual host. -Use this option to modify the value: -

    {odbc_pool_size, 10}.
    -

    You can configure an interval to make a dummy SQL request -to keep alive the connections to the database. -The default value is ’undefined’, so no keepalive requests are made. -Specify in seconds: for example 28800 means 8 hours. -

    {odbc_keepalive_interval, undefined}.
    -

    If the connection to the database fails, ejabberd waits 30 seconds before retrying. -You can modify this interval with this option: -

    {odbc_start_interval, 30}.
    -

    -

    Authentication

    -

    The option value name may be misleading, as the auth_method name is used -for access to a relational database through ODBC, as well as through the native -MySQL interface. Anyway, the first configuration step is to define the odbc -auth_method. For example: -

    {auth_method, [odbc]}.
    -

    -

    Storage

    -

    MySQL also can be used to store information into from several ejabberd -modules. See section 3.3.1 to see which modules have a version -with the ‘_odbc’. This suffix indicates that the module can be used with -relational databases like MySQL. To enable storage to your database, just make -sure that your database is running well (see previous sections), and replace the -suffix-less or ldap module variant with the odbc module variant. Keep in mind -that you cannot have several variants of the same module loaded!

    -

    3.2.2  Microsoft SQL Server

    -

    Although this section will describe ejabberd’s configuration when you want to -use Microsoft SQL Server, it does not describe Microsoft SQL Server’s -installation and database creation. Check the MySQL documentation and the -tutorial Using ejabberd with MySQL native driver for information regarding these topics. -Note that the tutorial contains information about ejabberd’s configuration -which is duplicate to this section.

    Moreover, the file mssql.sql in the directory src/odbc might be interesting for -you. This file contains the ejabberd schema for Microsoft SQL Server. At the end -of the file you can find information to update your database schema.

    -

    Driver Compilation

    -

    You can skip this step if you installed ejabberd using a binary installer or -if the binary packages of ejabberd you are using include support for ODBC.

    If you want to use Microsoft SQL Server with ODBC, you need to configure, -compile and install ejabberd with support for ODBC and Microsoft SQL Server -enabled. This can be done, by using next commands: -

    ./configure --enable-odbc --enable-mssql && make install
    -

    -

    Database Connection

    -

    The configuration of Database Connection for a Microsoft SQL Server -is the same as the configuration for -ODBC compatible servers (see section 3.2.4).

    -

    Authentication

    -

    The configuration of Authentication for a Microsoft SQL Server -is the same as the configuration for -ODBC compatible servers (see section 3.2.4).

    -

    Storage

    -

    Microsoft SQL Server also can be used to store information into from several -ejabberd modules. See section 3.3.1 to see which modules have -a version with the ‘_odbc’. This suffix indicates that the module can be used -with relational databases like Microsoft SQL Server. To enable storage to your -database, just make sure that your database is running well (see previous -sections), and replace the suffix-less or ldap module variant with the odbc -module variant. Keep in mind that you cannot have several variants of the same -module loaded!

    -

    3.2.3  PostgreSQL

    -

    Although this section will describe ejabberd’s configuration when you want to -use the native PostgreSQL driver, it does not describe PostgreSQL’s installation -and database creation. Check the PostgreSQL documentation and the tutorial Using ejabberd with MySQL native driver for information regarding these topics. -Note that the tutorial contains information about ejabberd’s configuration -which is duplicate to this section.

    Also the file pg.sql in the directory src/odbc might be interesting for you. -This file contains the ejabberd schema for PostgreSQL. At the end of the file -you can find information to update your database schema.

    -

    Driver Compilation

    -

    You can skip this step if you installed ejabberd using a binary installer or -if the binary packages of ejabberd you are using include support for -PostgreSQL.

    1. -First, install the Erlang pgsql library from -ejabberd-modules SVN repository. -Make sure the compiled -files are in your Erlang path; you can put them for example in the same -directory as your ejabberd .beam files. -
    2. Then, configure, compile and install ejabberd with ODBC support enabled -(this is also needed for native PostgreSQL support!). This can be done, by -using next commands: -
      ./configure --enable-odbc && make install
      -

    -

    Database Connection

    -

    The actual database access is defined in the option odbc_server. Its -value is used to define if we want to use ODBC, or one of the two native -interface available, PostgreSQL or MySQL.

    To use the native PostgreSQL interface, you can pass a tuple of the following -form as parameter: -

    {pgsql, "Server", "Database", "Username", "Password"}

    pgsql is a keyword that should be kept as is. For example: -

    {odbc_server, {pgsql, "localhost", "database", "ejabberd", "password"}}.

    Optionally, it is possible to define the PostgreSQL port to use. This -option is only useful, in very rare cases, when you are not running -PostgreSQL with the default port setting. The pgsql parameter -can thus take the following form: -

    {pgsql, "Server", Port, "Database", "Username", "Password"}

    The Port value should be an integer, without quotes. For example: -

    {odbc_server, {pgsql, "localhost", 5432, "database", "ejabberd", "password"}}.

    By default ejabberd opens 10 connections to the database for each virtual host. -Use this option to modify the value: -

    {odbc_pool_size, 10}.
    -

    You can configure an interval to make a dummy SQL request -to keep alive the connections to the database. -The default value is ’undefined’, so no keepalive requests are made. -Specify in seconds: for example 28800 means 8 hours. -

    {odbc_keepalive_interval, undefined}.
    -

    -

    Authentication

    -

    The option value name may be misleading, as the auth_method name is used -for access to a relational database through ODBC, as well as through the native -PostgreSQL interface. Anyway, the first configuration step is to define the odbc -auth_method. For example: -

    {auth_method, [odbc]}.
    -

    -

    Storage

    -

    PostgreSQL also can be used to store information into from several ejabberd -modules. See section 3.3.1 to see which modules have a version -with the ‘_odbc’. This suffix indicates that the module can be used with -relational databases like PostgreSQL. To enable storage to your database, just -make sure that your database is running well (see previous sections), and -replace the suffix-less or ldap module variant with the odbc module variant. -Keep in mind that you cannot have several variants of the same module loaded!

    -

    3.2.4  ODBC Compatible

    -

    Although this section will describe ejabberd’s configuration when you want to -use the ODBC driver, it does not describe the installation and database creation -of your database. Check the documentation of your database. The tutorial Using ejabberd with MySQL native driver also can help you. Note that the tutorial -contains information about ejabberd’s configuration which is duplicate to -this section.

    -

    Driver Compilation

    You can skip this step if you installed ejabberd using a binary installer or -if the binary packages of ejabberd you are using include support for -ODBC.

    1. -First, install the Erlang -MySQL library. Make sure the compiled files are in your Erlang path; you can -put them for example in the same directory as your ejabberd .beam files. -
    2. Then, configure, compile and install ejabberd with ODBC support -enabled. This can be done, by using next commands: -
      ./configure --enable-odbc && make install
      -

    -

    Database Connection

    -

    The actual database access is defined in the option odbc_server. Its -value is used to defined if we want to use ODBC, or one of the two native -interface available, PostgreSQL or MySQL.

    To use a relational database through ODBC, you can pass the ODBC connection -string as odbc_server parameter. For example: -

    {odbc_server, "DSN=database;UID=ejabberd;PWD=password"}.
    -

    By default ejabberd opens 10 connections to the database for each virtual host. -Use this option to modify the value: -

    {odbc_pool_size, 10}.
    -

    You can configure an interval to make a dummy SQL request -to keep alive the connections to the database. -The default value is ’undefined’, so no keepalive requests are made. -Specify in seconds: for example 28800 means 8 hours. -

    {odbc_keepalive_interval, undefined}.
    -

    -

    Authentication

    -

    The first configuration step is to define the odbc auth_method. For -example: -

    {auth_method, [odbc]}.
    -

    -

    Storage

    -

    An ODBC compatible database also can be used to store information into from -several ejabberd modules. See section 3.3.1 to see which -modules have a version with the ‘_odbc’. This suffix indicates that the module -can be used with ODBC compatible relational databases. To enable storage to your -database, just make sure that your database is running well (see previous -sections), and replace the suffix-less or ldap module variant with the odbc -module variant. Keep in mind that you cannot have several variants of the same -module loaded!

    -

    3.2.5  LDAP

    -

    ejabberd has built-in LDAP support. You can authenticate users against LDAP -server and use LDAP directory as vCard storage. Shared rosters are not supported -yet.

    Usually ejabberd treats LDAP as a read-only storage: -it is possible to consult data, but not possible to -create accounts or edit vCard that is stored in LDAP. -However, it is possible to change passwords if mod_register module is enabled -and LDAP server supports -RFC 3062.

    -

    Connection

    Two connections are established to the LDAP server per vhost, -one for authentication and other for regular calls.

    Parameters: -

    -{ldap_servers, [Servers, ...]}
    List of IP addresses or DNS names of your -LDAP servers. This option is required. -
    {ldap_encrypt, none|tls}
    Type of connection encryption to the LDAP server. -Allowed values are: none, tls. -The value tls enables encryption by using LDAP over SSL. -Note that STARTTLS encryption is not supported. -The default value is: none. -
    {ldap_tls_verify, false|soft|hard}
    -This option specifies whether to verify LDAP server certificate or not when TLS is enabled. -When hard is enabled ejabberd doesn’t proceed if a certificate is invalid. -When soft is enabled ejabberd proceeds even if check fails. -The default is false which means no checks are performed. -
    {ldap_port, Number}
    Port to connect to your LDAP server. -The default port is 389 if encryption is disabled; and 636 if encryption is enabled. -If you configure a value, it is stored in ejabberd’s database. -Then, if you remove that value from the configuration file, -the value previously stored in the database will be used instead of the default port. -
    {ldap_rootdn, RootDN}
    Bind DN. The default value -is "" which means ‘anonymous connection’. -
    {ldap_password, Password}
    Bind password. The default -value is "". -

    Example: -

    {auth_method, ldap}.
    -{ldap_servers, ["ldap.example.org"]}.
    -{ldap_port, 389}.
    -{ldap_rootdn, "cn=Manager,dc=domain,dc=org"}.
    -{ldap_password, "secret"}.
    -

    -

    Authentication

    You can authenticate users against an LDAP directory. -Note that current LDAP implementation does not support SASL authentication.

    Available options are:

    -{ldap_base, Base}
    LDAP base directory which stores -users accounts. This option is required. -
    {ldap_uids, [ {ldap_uidattr} | {ldap_uidattr, ldap_uidattr_format}, ...]}
    -LDAP attribute which holds a list of attributes to use as alternatives for getting the JID. -The default attributes are [{"uid", "%u"}]. -The attributes are of the form: -[{ldap_uidattr}] or [{ldap_uidattr, ldap_uidattr_format}]. -You can use as many comma separated attributes as needed. -The values for ldap_uidattr and -ldap_uidattr_format are described as follow: -
    -ldap_uidattr
    LDAP attribute which holds -the user’s part of a JID. The default value is "uid". -
    ldap_uidattr_format
    Format of -the ldap_uidattr variable. The format must contain one and -only one pattern variable "%u" which will be replaced by the -user’s part of a JID. For example, "%u@example.org". The default -value is "%u". -
    -
    {ldap_filter, Filter}
    -RFC 4515 LDAP filter. The -default Filter value is: undefined. Example: -"(&(objectClass=shadowAccount)(memberOf=Jabber Users))". Please, do -not forget to close brackets and do not use superfluous whitespaces. Also you -must not use ldap_uidattr attribute in filter because this -attribute will be substituted in LDAP filter automatically. -
    {ldap_dn_filter, { Filter, FilterAttrs }}
    -This filter is applied on the results returned by the main filter. This filter -performs additional LDAP lookup to make the complete result. This is useful -when you are unable to define all filter rules in ldap_filter. You -can define "%u", "%d", "%s" and "%D" pattern -variables in Filter: "%u" is replaced by a user’s part of a JID, -"%d" is replaced by the corresponding domain (virtual host), -all "%s" variables are consecutively replaced by values of FilterAttrs -attributes and "%D" is replaced by Distinguished Name. By default -ldap_dn_filter is undefined. -Example: -
    {ldap_dn_filter, {"(&(name=%s)(owner=%D)(user=%u@%d))", ["sn"]}}.
    -
    Since this filter makes additional LDAP lookups, use it only in the -last resort: try to define all filter rules in ldap_filter if possible. -
    {ldap_local_filter, Filter}
    -If you can’t use ldap_filter due to performance reasons -(the LDAP server has many users registered), -you can use this local filter. -The local filter checks an attribute in ejabberd, -not in LDAP, so this limits the load on the LDAP directory. -The default filter is: undefined. -Example values: -
    {ldap_local_filter, {notequal, {"accountStatus",["disabled"]}}}.
    -{ldap_local_filter, {equal, {"accountStatus",["enabled"]}}}.
    -{ldap_local_filter, undefined}.
    -

    -

    Examples

    -
    Common example

    Let’s say ldap.example.org is the name of our LDAP server. We have -users with their passwords in "ou=Users,dc=example,dc=org" directory. -Also we have addressbook, which contains users emails and their additional -infos in "ou=AddressBook,dc=example,dc=org" directory. -The connection to the LDAP server is encrypted using TLS, -and using the custom port 6123. -Corresponding authentication section should looks like this:

    %% Authentication method
    -{auth_method, ldap}.
    -%% DNS name of our LDAP server
    -{ldap_servers, ["ldap.example.org"]}.
    -%% Bind to LDAP server as "cn=Manager,dc=example,dc=org" with password "secret"
    -{ldap_rootdn, "cn=Manager,dc=example,dc=org"}.
    -{ldap_password, "secret"}.
    -{ldap_encrypt, tls}.
    -{ldap_port, 6123}.
    -%% Define the user's base
    -{ldap_base, "ou=Users,dc=example,dc=org"}.
    -%% We want to authorize users from 'shadowAccount' object class only
    -{ldap_filter, "(objectClass=shadowAccount)"}.
    -

    Now we want to use users LDAP-info as their vCards. We have four attributes -defined in our LDAP schema: "mail" — email address, "givenName" -— first name, "sn" — second name, "birthDay" — birthday. -Also we want users to search each other. Let’s see how we can set it up:

    {modules,
    - [
    -  ...
    -  {mod_vcard_ldap,
    -   [
    -    %% We use the same server and port, but want to bind anonymously because
    -    %% our LDAP server accepts anonymous requests to
    -    %% "ou=AddressBook,dc=example,dc=org" subtree.
    -    {ldap_rootdn, ""},
    -    {ldap_password, ""},
    -    %% define the addressbook's base
    -    {ldap_base, "ou=AddressBook,dc=example,dc=org"},
    -    %% uidattr: user's part of JID is located in the "mail" attribute
    -    %% uidattr_format: common format for our emails
    -    {ldap_uids, [{"mail", "%u@mail.example.org"}]},
    -    %% We have to define empty filter here, because entries in addressbook does not
    -    %% belong to shadowAccount object class
    -    {ldap_filter, ""},
    -    %% Now we want to define vCard pattern
    -    {ldap_vcard_map,
    -     [{"NICKNAME", "%u", []}, % just use user's part of JID as his nickname
    -      {"GIVEN", "%s", ["givenName"]},
    -      {"FAMILY", "%s", ["sn"]},
    -      {"FN", "%s, %s", ["sn", "givenName"]}, % example: "Smith, John"
    -      {"EMAIL", "%s", ["mail"]},
    -      {"BDAY", "%s", ["birthDay"]}]},
    -    %% Search form
    -    {ldap_search_fields,
    -     [{"User", "%u"},
    -      {"Name", "givenName"},
    -      {"Family Name", "sn"},
    -      {"Email", "mail"},
    -      {"Birthday", "birthDay"}]},
    -    %% vCard fields to be reported
    -    %% Note that JID is always returned with search results
    -    {ldap_search_reported,
    -     [{"Full Name", "FN"},
    -      {"Nickname", "NICKNAME"},
    -      {"Birthday", "BDAY"}]}
    -  ]},
    -  ...
    - ]}.
    -

    Note that mod_vcard_ldap module checks for the existence of the user before -searching in his information in LDAP.

    -
    Active Directory

    -

    Active Directory is just an LDAP-server with predefined attributes. A sample -configuration is shown below:

    {auth_method, ldap}.
    -{ldap_servers, ["office.org"]}.    % List of LDAP servers
    -{ldap_base, "DC=office,DC=org"}. % Search base of LDAP directory
    -{ldap_rootdn, "CN=Administrator,CN=Users,DC=office,DC=org"}. % LDAP manager
    -{ldap_password, "*******"}. % Password to LDAP manager
    -{ldap_uids, [{"sAMAccountName"}]}.
    -{ldap_filter, "(memberOf=*)"}.
    -
    -{modules,
    - [
    -  ...
    -  {mod_vcard_ldap,
    -   [{ldap_vcard_map,
    -     [{"NICKNAME", "%u", []},
    -      {"GIVEN", "%s", ["givenName"]},
    -      {"MIDDLE", "%s", ["initials"]},
    -      {"FAMILY", "%s", ["sn"]},
    -      {"FN", "%s", ["displayName"]},
    -      {"EMAIL", "%s", ["mail"]},
    -      {"ORGNAME", "%s", ["company"]},
    -      {"ORGUNIT", "%s", ["department"]},
    -      {"CTRY", "%s", ["c"]},
    -      {"LOCALITY", "%s", ["l"]},
    -      {"STREET", "%s", ["streetAddress"]},
    -      {"REGION", "%s", ["st"]},
    -      {"PCODE", "%s", ["postalCode"]},
    -      {"TITLE", "%s", ["title"]},
    -      {"URL", "%s", ["wWWHomePage"]},
    -      {"DESC", "%s", ["description"]},
    -      {"TEL", "%s", ["telephoneNumber"]}]},
    -    {ldap_search_fields,
    -     [{"User", "%u"},
    -      {"Name", "givenName"},
    -      {"Family Name", "sn"},
    -      {"Email", "mail"},
    -      {"Company", "company"},
    -      {"Department", "department"},
    -      {"Role", "title"},
    -      {"Description", "description"},
    -      {"Phone", "telephoneNumber"}]},
    -    {ldap_search_reported,
    -     [{"Full Name", "FN"},
    -      {"Nickname", "NICKNAME"},
    -      {"Email", "EMAIL"}]}
    -  ]},
    -  ...
    - ]}.
    -

    -

    3.3  Modules Configuration

    -

    The option modules defines the list of modules that will be loaded after -ejabberd’s startup. Each entry in the list is a tuple in which the first -element is the name of a module and the second is a list of options for that -module.

    The syntax is: -

    {modules, [ {ModuleName, ModuleOptions}, ...]}.

    Examples: -

    • -In this example only the module mod_echo is loaded and no module -options are specified between the square brackets: -
      {modules,
      - [
      -  {mod_echo,      []}
      - ]}.
      -
    • In the second example the modules mod_echo, mod_time, and -mod_version are loaded without options. Remark that, besides the last entry, -all entries end with a comma: -
      {modules,
      - [
      -  {mod_echo,      []},
      -  {mod_time,      []},
      -  {mod_version,   []}
      - ]}.
      -

    -

    3.3.1  Modules Overview

    -

    The following table lists all modules included in ejabberd.


    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    ModuleFeatureDependencies
    mod_adhocAd-Hoc Commands (XEP-0050) 
    mod_announceManage announcementsrecommends mod_adhoc
    mod_capsEntity Capabilities (XEP-0115) 
    mod_configureServer configuration using Ad-Hocmod_adhoc
    mod_discoService Discovery (XEP-0030) 
    mod_echoEchoes XMPP stanzas 
    mod_http_bindXMPP over Bosh service (HTTP Binding) 
    mod_http_fileserverSmall HTTP file server 
    mod_ircIRC transport 
    mod_lastLast Activity (XEP-0012) 
    mod_last_odbcLast Activity (XEP-0012)supported DB (*)
    mod_mucMulti-User Chat (XEP-0045) 
    mod_muc_logMulti-User Chat room loggingmod_muc
    mod_offlineOffline message storage (XEP-0160) 
    mod_offline_odbcOffline message storage (XEP-0160)supported DB (*)
    mod_pingXMPP Ping and periodic keepalives (XEP-0199) 
    mod_privacyBlocking Communication (XMPP IM) 
    mod_privacy_odbcBlocking Communication (XMPP IM)supported DB (*)
    mod_privatePrivate XML Storage (XEP-0049) 
    mod_private_odbcPrivate XML Storage (XEP-0049)supported DB (*)
    mod_proxy65SOCKS5 Bytestreams (XEP-0065) 
    mod_pubsubPub-Sub (XEP-0060), PEP (XEP-0163)mod_caps
    mod_pubsub_odbcPub-Sub (XEP-0060), PEP (XEP-0163)supported DB (*) and mod_caps
    mod_registerIn-Band Registration (XEP-0077) 
    mod_rosterRoster management (XMPP IM) 
    mod_roster_odbcRoster management (XMPP IM)supported DB (*)
    mod_service_logCopy user messages to logger service 
    mod_shared_rosterShared roster managementmod_roster or
      mod_roster_odbc
    mod_sicServer IP Check (XEP-0279) 
    mod_statsStatistics Gathering (XEP-0039) 
    mod_timeEntity Time (XEP-0202) 
    mod_vcardvcard-temp (XEP-0054) 
    mod_vcard_ldapvcard-temp (XEP-0054)LDAP server
    mod_vcard_odbcvcard-temp (XEP-0054)supported DB (*)
    mod_vcard_xupdatevCard-Based Avatars (XEP-0153)mod_vcard or mod_vcard_odbc
    mod_versionSoftware Version (XEP-0092) 
    -

    • -(*) This module requires a supported database. For a list of supported databases, see section 3.2. -

    You can see which database backend each module needs by looking at the suffix: -

    • -No suffix, this means that the modules uses Erlang’s built-in database -Mnesia as backend. -
    • ‘_odbc’, this means that the module needs a supported database -(see 3.2) as backend. -
    • ‘_ldap’, this means that the module needs an LDAP server as backend. -

    If you want to, -it is possible to use a relational database to store the tables created by some ejabberd modules. -You can do this by changing the module name to a name with an -_odbc suffix in ejabberd config file. You can use a relational -database for the following data:

    • -Last connection date and time: Use mod_last_odbc instead of -mod_last. -
    • Offline messages: Use mod_offline_odbc instead of -mod_offline. -
    • Rosters: Use mod_roster_odbc instead of mod_roster. -
    • Users’ VCARD: Use mod_vcard_odbc instead of mod_vcard. -
    • Private XML storage: Use mod_private_odbc instead of mod_private. -
    • User rules for blocking communications: Use mod_privacy_odbc instead of mod_privacy. -
    • Pub-Sub nodes, items and subscriptions: Use mod_pubsub_odbc instead of mod_pubsub. -

    You can find more -contributed modules on the -ejabberd website. Please remember that these contributions might not work or -that they can contain severe bugs and security leaks. Therefore, use them at -your own risk!

    -

    3.3.2  Common Options

    The following options are used by many modules. Therefore, they are described in -this separate section.

    -

    iqdisc

    -

    Many modules define handlers for processing IQ queries of different namespaces -to this server or to a user (e. g. to example.org or to -user@example.org). This option defines processing discipline for -these queries.

    The syntax is: -

    {iqdisc, Value}

    Possible Value are: -

    -no_queue
    All queries of a namespace with this processing discipline are -processed immediately. This also means that no other packets can be processed -until this one has been completely processed. Hence this discipline is not -recommended if the processing of a query can take a relatively long time. -
    one_queue
    In this case a separate queue is created for the processing -of IQ queries of a namespace with this discipline. In addition, the processing -of this queue is done in parallel with that of other packets. This discipline -is most recommended. -
    {queues, N}
    N separate queues are created to process the -queries. The queries are thus process in parallel, but in a -controlled way. -
    parallel
    For every packet with this discipline a separate Erlang process -is spawned. Consequently, all these packets are processed in parallel. -Although spawning of Erlang process has a relatively low cost, this can break -the server’s normal work, because the Erlang emulator has a limit on the -number of processes (32000 by default). -

    Example: -

    {modules,
    - [
    -  ...
    -  {mod_time, [{iqdisc, no_queue}]},
    -  ...
    - ]}.
    -

    -

    host

    -

    This option defines the Jabber ID of a service provided by an ejabberd module.

    The syntax is: -

    {host, HostName}

    If you include the keyword "@HOST@" in the HostName, -it is replaced at start time with the real virtual host string.

    This example configures -the echo module to provide its echoing service -in the Jabber ID mirror.example.org: -

    {modules,
    - [
    -  ...
    -  {mod_echo, [{host, "mirror.example.org"}]},
    -  ...
    - ]}.
    -

    However, if there are several virtual hosts and this module is enabled in all of them, -the "@HOST@" keyword must be used: -

    {modules,
    - [
    -  ...
    -  {mod_echo, [{host, "mirror.@HOST@"}]},
    -  ...
    - ]}.
    -

    -

    3.3.3  mod_announce

    -

    This module enables configured users to broadcast announcements and to set -the message of the day (MOTD). -Configured users can perform these actions with a -XMPP client either using Ad-hoc commands -or sending messages to specific JIDs.

    The Ad-hoc commands are listed in the Server Discovery. -For this feature to work, mod_adhoc must be enabled.

    The specific JIDs where messages can be sent are listed bellow. -The first JID in each entry will apply only to the specified virtual host -example.org, while the JID between brackets will apply to all virtual -hosts in ejabberd. -

    -example.org/announce/all (example.org/announce/all-hosts/all)
    The -message is sent to all registered users. If the user is online and connected -to several resources, only the resource with the highest priority will receive -the message. If the registered user is not connected, the message will be -stored offline in assumption that offline storage -(see section 3.3.12) is enabled. -
    example.org/announce/online (example.org/announce/all-hosts/online)
    The -message is sent to all connected users. If the user is online and connected -to several resources, all resources will receive the message. -
    example.org/announce/motd (example.org/announce/all-hosts/motd)
    The -message is set as the message of the day (MOTD) and is sent to users when they -login. In addition the message is sent to all connected users (similar to -announce/online). -
    example.org/announce/motd/update (example.org/announce/all-hosts/motd/update)
    -The message is set as message of the day (MOTD) and is sent to users when they -login. The message is not sent to any currently connected user. -
    example.org/announce/motd/delete (example.org/announce/all-hosts/motd/delete)
    -Any message sent to this JID removes the existing message of the day (MOTD). -

    Options: -

    -{access, AccessName}
    This option specifies who is allowed to -send announcements and to set the message of the day (by default, nobody is -able to send such messages). -

    Examples: -

    • -Only administrators can send announcements: -
      {access, announce, [{allow, admins}]}.
      -
      -{modules,
      - [
      -  ...
      -  {mod_adhoc, []},
      -  {mod_announce, [{access, announce}]},
      -  ...
      - ]}.
      -
    • Administrators as well as the direction can send announcements: -
      {acl, direction, {user, "big_boss", "example.org"}}.
      -{acl, direction, {user, "assistant", "example.org"}}.
      -{acl, admins, {user, "admin", "example.org"}}.
      -
      -{access, announce, [{allow, admins},
      -                    {allow, direction}]}.
      -
      -{modules,
      - [
      -  ...
      -  {mod_adhoc, []},
      -  {mod_announce, [{access, announce}]},
      -  ...
      - ]}.
      -

    Note that mod_announce can be resource intensive on large -deployments as it can broadcast lot of messages. This module should be -disabled for instances of ejabberd with hundreds of thousands users.

    -

    3.3.4  mod_disco

    - - - - -

    This module adds support for Service Discovery (XEP-0030). With -this module enabled, services on your server can be discovered by -XMPP clients. Note that ejabberd has no modules with support -for the superseded Jabber Browsing (XEP-0011) and Agent Information -(XEP-0094). Accordingly, XMPP clients need to have support for -the newer Service Discovery protocol if you want them be able to discover -the services you offer.

    Options: -

    -{iqdisc, Discipline}
    This specifies -the processing discipline for Service Discovery (http://jabber.org/protocol/disco#items and -http://jabber.org/protocol/disco#info) IQ queries (see section 3.3.2). -
    {extra_domains, [Domain, ...]}
    With this option, -you can specify a list of extra domains that are added to the Service Discovery item list. -
    {server_info, [ {Modules, Field, [Value, ...]}, ... ]}
    -Specify additional information about the server, -as described in Contact Addresses for XMPP Services (XEP-0157). -Modules can be the keyword ‘all’, -in which case the information is reported in all the services; -or a list of ejabberd modules, -in which case the information is only specified for the services provided by those modules. -Any arbitrary Field and Value can be specified, not only contact addresses. -

    Examples: -

    • -To serve a link to the Jabber User Directory on jabber.org: -
      {modules,
      - [
      -  ...
      -  {mod_disco, [{extra_domains, ["users.jabber.org"]}]},
      -  ...
      - ]}.
      -
    • To serve a link to the transports on another server: -
      {modules,
      - [
      -  ...
      -  {mod_disco, [{extra_domains, ["icq.example.com",
      -                                "msn.example.com"]}]},
      -  ...
      - ]}.
      -
    • To serve a link to a few friendly servers: -
      {modules,
      - [
      -  ...
      -  {mod_disco, [{extra_domains, ["example.org",
      -                                "example.com"]}]},
      -  ...
      - ]}.
      -
    • With this configuration, all services show abuse addresses, -feedback address on the main server, -and admin addresses for both the main server and the vJUD service: -
      {modules,
      - [
      -  ...
      -  {mod_disco, [{server_info, [
      -      {all,
      -       "abuse-addresses",
      -       ["mailto:abuse@shakespeare.lit"]},
      -      {[mod_muc],
      -       "Web chatroom logs",
      -       ["http://www.example.org/muc-logs"]},
      -      {[mod_disco],
      -       "feedback-addresses",
      -       ["http://shakespeare.lit/feedback.php", "mailto:feedback@shakespeare.lit", "xmpp:feedback@shakespeare.lit"]},
      -      {[mod_disco, mod_vcard],
      -       "admin-addresses",
      -       ["mailto:xmpp@shakespeare.lit", "xmpp:admins@shakespeare.lit"]}
      -  ]}]},
      -  ...
      - ]}.
      -

    -

    3.3.5  mod_echo

    -

    This module simply echoes any XMPP -packet back to the sender. This mirror can be of interest for -ejabberd and XMPP client debugging.

    Options: -

    - -{host, HostName}
    This option defines the Jabber ID of the -service. If the host option is not specified, the Jabber ID will be the -hostname of the virtual host with the prefix ‘echo.’. The keyword "@HOST@" -is replaced at start time with the real virtual host name. - -

    Example: Mirror, mirror, on the wall, who is the most beautiful -of them all? -

    {modules,
    - [
    -  ...
    -  {mod_echo, [{host, "mirror.example.org"}]},
    -  ...
    - ]}.
    -

    -

    3.3.6  mod_http_bind

    -

    This module implements XMPP over Bosh (formerly known as HTTP Binding) -as defined in XEP-0124 and XEP-0206. -It extends ejabberd’s built in HTTP service with a configurable -resource at which this service will be hosted.

    To use HTTP-Binding, enable the module: -

    {modules,
    - [
    -  ...
    -  {mod_http_bind, []},
    -  ...
    -]}.
    -

    and add http_bind in the HTTP service. For example: -

    {listen, 
    - [
    -  ...
    -  {5280, ejabberd_http, [
    -                         http_bind,
    -                         http_poll,
    -                         web_admin
    -                        ]
    -  },
    -  ...
    -]}.
    -

    With this configuration, the module will serve the requests sent to -http://example.org:5280/http-bind/ -Remember that this page is not designed to be used by web browsers, -it is used by XMPP clients that support XMPP over Bosh.

    If you want to set the service in a different URI path or use a different module, -you can configure it manually using the option request_handlers. -For example: -

    {listen, 
    - [
    -  ...
    -  {5280, ejabberd_http, [
    -                         {request_handlers, [{["http-bind"], mod_http_bind}]},
    -                         http_poll,
    -                         web_admin
    -                        ]
    -  },
    -  ...
    -]}.
    -

    Options: -

    -{max_inactivity, Seconds}
    -Define the maximum inactivity period in seconds. -Default value is 30 seconds. -For example, to set 50 seconds: -
    {modules,
    - [
    -  ...
    -  {mod_http_bind, [ {max_inactivity, 50} ]},
    -  ...
    -]}.
    -

    -

    3.3.7  mod_http_fileserver

    -

    This simple module serves files from the local disk over HTTP.

    Options: -

    -{docroot, Path}
    -Directory to serve the files. -
    {accesslog, Path}
    -File to log accesses using an Apache-like format. -No log will be recorded if this option is not specified. -
    {directory_indices, [Index, ...]}
    -Indicate one or more directory index files, similarly to Apache’s -DirectoryIndex variable. When a web request hits a directory -instead of a regular file, those directory indices are looked in -order, and the first one found is returned. -
    {custom_headers, [ {Name, Value}, ...]}
    -Indicate custom HTTP headers to be included in all responses. -Default value is: [] -
    {content_types, [ {Name, Type}, ...]}
    -Specify mappings of extension to content type. -There are several content types already defined, -with this option you can add new definitions, modify or delete existing ones. -To delete an existing definition, simply define it with a value: ‘undefined’. -
    {default_content_type, Type}
    -Specify the content type to use for unknown extensions. -Default value is ‘application/octet-stream’. -

    This example configuration will serve the files from -the local directory /var/www -in the address http://example.org:5280/pub/archive/. -In this example a new content type ogg is defined, -png is redefined, and jpg definition is deleted. -To use this module you must enable it: -

    {modules,
    - [
    -  ...
    -  {mod_http_fileserver, [
    -                         {docroot, "/var/www"}, 
    -                         {accesslog, "/var/log/ejabberd/access.log"},
    -                         {directory_indices, ["index.html", "main.htm"]},
    -                         {custom_headers, [{"X-Powered-By", "Erlang/OTP"},
    -                                           {"X-Fry", "It's a widely-believed fact!"}
    -                                          ]},
    -                         {content_types, [{".ogg", "audio/ogg"},
    -                                          {".png", "image/png"},
    -                                          {".jpg", undefined}
    -                                         ]},
    -                         {default_content_type, "text/html"}
    -                        ]
    -  },
    -  ...
    -]}.
    -

    And define it as a handler in the HTTP service: -

    {listen, 
    - [
    -  ...
    -  {5280, ejabberd_http, [
    -                         ...
    -                         {request_handlers, [
    -                                             ...
    -                                             {["pub", "archive"], mod_http_fileserver},
    -                                             ...
    -                                            ]
    -                         },
    -                         ...
    -                        ]
    -  },
    -  ...
    -]}.
    -

    -

    3.3.8  mod_irc

    -

    This module is an IRC transport that can be used to join channels on IRC -servers.

    End user information: - -

    • -A XMPP client with ‘groupchat 1.0’ support or Multi-User -Chat support (XEP-0045) is necessary to join IRC channels. -
    • An IRC channel can be joined in nearly the same way as joining a -XMPP Multi-User Chat room. The difference is that the room name will -be ‘channel%irc.example.org’ in case irc.example.org is -the IRC server hosting ‘channel’. And of course the host should point -to the IRC transport instead of the Multi-User Chat service. -
    • You can register your nickame by sending ‘IDENTIFY password’ to
      - nickserver!irc.example.org@irc.jabberserver.org. -
    • Entering your password is possible by sending ‘LOGIN nick password’
      - to nickserver!irc.example.org@irc.jabberserver.org. -
    • The IRC transport provides Ad-Hoc Commands (XEP-0050) -to join a channel, and to set custom IRC username and encoding. -
    • When using a popular XMPP server, it can occur that no -connection can be achieved with some IRC servers because they limit the -number of conections from one IP. -

    Options: -

    - -{host, HostName}
    This option defines the Jabber ID of the -service. If the host option is not specified, the Jabber ID will be the -hostname of the virtual host with the prefix ‘irc.’. The keyword "@HOST@" -is replaced at start time with the real virtual host name. - -
    {access, AccessName}
    This option can be used to specify who -may use the IRC transport (default value: all). -
    {default_encoding, Encoding}
    Set the default IRC encoding. -Default value: "koi8-r" -

    Examples: -

    • -In the first example, the IRC transport is available on (all) your -virtual host(s) with the prefix ‘irc.’. Furthermore, anyone is -able to use the transport. The default encoding is set to "iso8859-15". -
      {modules,
      - [
      -  ...
      -  {mod_irc, [{access, all}, {default_encoding, "iso8859-15"}]},
      -  ...
      - ]}.
      -
    • In next example the IRC transport is available with JIDs with prefix irc-t.net. -Moreover, the transport is only accessible to two users -of example.org, and any user of example.com: -
      {acl, paying_customers, {user, "customer1", "example.org"}}.
      -{acl, paying_customers, {user, "customer2", "example.org"}}.
      -{acl, paying_customers, {server, "example.com"}}.
      -
      -{access, irc_users, [{allow, paying_customers}, {deny, all}]}.
      -
      -{modules,
      - [
      -  ...
      -  {mod_irc, [{access, irc_users},
      -             {host, "irc.example.net"}]},
      -  ...
      - ]}.
      -

    -

    3.3.9  mod_last

    -

    This module adds support for Last Activity (XEP-0012). It can be used to -discover when a disconnected user last accessed the server, to know when a -connected user was last active on the server, or to query the uptime of the -ejabberd server.

    Options: -

    -{iqdisc, Discipline}
    This specifies -the processing discipline for Last activity (jabber:iq:last) IQ queries (see section 3.3.2). -

    -

    3.3.10  mod_muc

    -

    This module provides a Multi-User Chat (XEP-0045) service. -Users can discover existing rooms, join or create them. -Occupants of a room can chat in public or have private chats.

    Some of the features of Multi-User Chat: -

    • -Sending public and private messages to room occupants. -
    • Inviting other users to a room. -
    • Setting a room subject. -
    • Creating password protected rooms. -
    • Kicking and banning occupants. -

    The MUC service allows any Jabber ID to register a nickname, -so nobody else can use that nickname in any room in the MUC service. -To register a nickname, open the Service Discovery in your -XMPP client and register in the MUC service.

    This module supports clustering and load -balancing. One module can be started per cluster node. Rooms are -distributed at creation time on all available MUC module -instances. The multi-user chat module is clustered but the rooms -themselves are not clustered nor fault-tolerant: if the node managing a -set of rooms goes down, the rooms disappear and they will be recreated -on an available node on first connection attempt.

    Module options: -

    - -{host, HostName}
    This option defines the Jabber ID of the -service. If the host option is not specified, the Jabber ID will be the -hostname of the virtual host with the prefix ‘conference.’. The keyword "@HOST@" -is replaced at start time with the real virtual host name. - -
    {access, AccessName}
    You can specify who is allowed to use -the Multi-User Chat service. By default everyone is allowed to use it. -
    {access_create, AccessName}
    To configure who is -allowed to create new rooms at the Multi-User Chat service, this option can be used. -By default any account in the local ejabberd server is allowed to create rooms. -
    {access_persistent, AccessName}
    To configure who is -allowed to modify the ’persistent’ room option. -By default any account in the local ejabberd server is allowed to modify that option. -
    {access_admin, AccessName}
    This option specifies -who is allowed to administrate the Multi-User Chat service. The default -value is none, which means that only the room creator can -administer his room. -The administrators can send a normal message to the service JID, -and it will be shown in all active rooms as a service message. -The administrators can send a groupchat message to the JID of an active room, -and the message will be shown in the room as a service message. -
    {history_size, Size}
    A small history of -the current discussion is sent to users when they enter the -room. With this option you can define the number of history messages -to keep and send to users joining the room. The value is an -integer. Setting the value to 0 disables the history feature -and, as a result, nothing is kept in memory. The default value is -20. This value is global and thus affects all rooms on the -service. -
    {max_users, Number}
    This option defines at -the service level, the maximum number of users allowed per -room. It can be lowered in each room configuration but cannot be -increased in individual room configuration. The default value is -200. -
    {max_users_admin_threshold, Number}
    - This option defines the -number of service admins or room owners allowed to enter the room when -the maximum number of allowed occupants was reached. The default limit -is 5. -
    {max_user_conferences, Number}
    - This option defines the maximum -number of rooms that any given user can join. The default value -is 10. This option is used to prevent possible abuses. Note that -this is a soft limit: some users can sometimes join more conferences -in cluster configurations. -
    {max_room_id, Number}
    -This option defines the maximum number of characters that Room ID -can have when creating a new room. -The default value is to not limit: infinite. -
    {max_room_name, Number}
    -This option defines the maximum number of characters that Room Name -can have when configuring the room. -The default value is to not limit: infinite. -
    {max_room_desc, Number}
    -This option defines the maximum number of characters that Room Description -can have when configuring the room. -The default value is to not limit: infinite. -
    {min_message_interval, Number}
    -This option defines the minimum interval between two messages send -by an occupant in seconds. This option is global and valid for all -rooms. A decimal value can be used. When this option is not defined, -message rate is not limited. This feature can be used to protect a -MUC service from occupant abuses and limit number of messages that will -be broadcasted by the service. A good value for this minimum message -interval is 0.4 second. If an occupant tries to send messages faster, an -error is send back explaining that the message has been discarded -and describing the reason why the message is not acceptable. -
    {min_presence_interval, Number}
    - This option defines the -minimum of time between presence changes coming from a given occupant in -seconds. This option is global and valid for all rooms. A -decimal value can be used. When this option is not defined, no -restriction is applied. This option can be used to protect a MUC -service for occupants abuses. If an occupant tries -to change its presence more often than the specified interval, the -presence is cached by ejabberd and only the last presence is -broadcasted to all occupants in the room after expiration of the -interval delay. Intermediate presence packets are silently -discarded. A good value for this option is 4 seconds. -
    {default_room_options, [ {OptionName, OptionValue}, ...]}
    -This module option allows to define the desired default room options. -Note that the creator of a room can modify the options of his room -at any time using a XMPP client with MUC capability. -The available room options and the default values are: -
    -{allow_change_subj, true|false}
    Allow occupants to change the subject. -
    {allow_private_messages, true|false}
    Occupants can send private messages to other occupants. -
    {allow_query_users, true|false}
    Occupants can send IQ queries to other occupants. -
    {allow_user_invites, false|true}
    Allow occupants to send invitations. -
    {allow_visitor_nickchange, true|false}
    Allow visitors to -change nickname. -
    {allow_visitor_status, true|false}
    Allow visitors to send -status text in presence updates. If disallowed, the status -text is stripped before broadcasting the presence update to all -the room occupants. -
    {anonymous, true|false}
    The room is anonymous: -occupants don’t see the real JIDs of other occupants. -Note that the room moderators can always see the real JIDs of the occupants. -
    {captcha_protected, false}
    -When a user tries to join a room where he has no affiliation (not owner, admin or member), -the room requires him to fill a CAPTCHA challenge (see section 3.1.8) -in order to accept her join in the room. -
    {logging, false|true}
    The public messages are logged using mod_muc_log. -
    {max_users, 200}
    Maximum number of occupants in the room. -
    {members_by_default, true|false}
    The occupants that enter the room are participants by default, so they have ’voice’. -
    {members_only, false|true}
    Only members of the room can enter. -
    {moderated, true|false}
    Only occupants with ’voice’ can send public messages. -
    {password, "roompass123"}
    Password of the room. You may want to enable the next option too. -
    {password_protected, false|true}
    The password is required to enter the room. -
    {persistent, false|true}
    The room persists even if the last participant leaves. -
    {public, true|false}
    The room is public in the list of the MUC service, so it can be discovered. -
    {public_list, true|false}
    The list of participants is public, without requiring to enter the room. -
    {title, "Room Title"}
    A human-readable title of the room. -
    -All of those room options can be set to true or false, -except password and title which are strings, -and max_users that is integer. -

    Examples: -

    • -In the first example everyone is allowed to use the Multi-User Chat -service. Everyone will also be able to create new rooms but only the user -admin@example.org is allowed to administrate any room. In this -example he is also a global administrator. When admin@example.org -sends a message such as ‘Tomorrow, the XMPP server will be moved -to new hardware. This will involve service breakdowns around 23:00 UMT. -We apologise for this inconvenience.’ to conference.example.org, -it will be displayed in all active rooms. In this example the history -feature is disabled. -
      {acl, admin, {user, "admin", "example.org"}}.
      -
      -{access, muc_admin, [{allow, admin}]}.
      -
      -{modules,
      - [
      -  ...
      -  {mod_muc, [{access, all},
      -             {access_create, all},
      -             {access_admin, muc_admin},
      -             {history_size, 0}]},
      -  ...
      - ]}.
      -
    • In the second example the Multi-User Chat service is only accessible by -paying customers registered on our domains and on other servers. Of course -the administrator is also allowed to access rooms. In addition, he is the -only authority able to create and administer rooms. When -admin@example.org sends a message such as ‘Tomorrow, the Jabber -server will be moved to new hardware. This will involve service breakdowns -around 23:00 UMT. We apologise for this inconvenience.’ to -conference.example.org, it will be displayed in all active rooms. No -history_size option is used, this means that the feature is enabled -and the default value of 20 history messages will be send to the users. -
      {acl, paying_customers, {user, "customer1", "example.net"}}.
      -{acl, paying_customers, {user, "customer2", "example.com"}}.
      -{acl, paying_customers, {user, "customer3", "example.org"}}.
      -{acl, admin, {user, "admin", "example.org"}}.
      -
      -{access, muc_admin, [{allow, admin},
      -                      {deny, all}]}.
      -{access, muc_access, [{allow, paying_customers},
      -                      {allow, admin},
      -                      {deny, all}]}.
      -
      -{modules,
      - [
      -  ...
      -  {mod_muc, [{access, muc_access},
      -             {access_create, muc_admin},
      -             {access_admin, muc_admin}]},
      -  ...
      - ]}.
      -
    • In the following example, MUC anti abuse options are used. An -occupant cannot send more than one message every 0.4 seconds and cannot -change its presence more than once every 4 seconds. -The length of Room IDs and Room Names are limited to 20 characters, -and Room Description to 300 characters. No ACLs are -defined, but some user restriction could be added as well:
      {modules,
      - [
      -  ...
      -  {mod_muc, [{min_message_interval, 0.4},
      -             {min_presence_interval, 4},
      -             {max_room_id, 20},
      -             {max_room_name, 20},
      -             {max_room_desc, 300}]},
      -  ...
      - ]}.
      -
    • This example shows how to use default_room_options to make sure -the newly created rooms have by default those options. -
      {modules,
      - [
      -  ...
      -  {mod_muc, [{access, muc_access},
      -             {access_create, muc_admin},
      -             {default_room_options,
      -              [
      -               {allow_change_subj, false},
      -               {allow_query_users, true},
      -               {allow_private_messages, true},
      -               {members_by_default, false},
      -               {title, "New chatroom"},
      -               {anonymous, false}
      -              ]},
      -             {access_admin, muc_admin}]},
      -  ...
      - ]}.
      -

    -

    3.3.11  mod_muc_log

    -

    This module enables optional logging of Multi-User Chat (MUC) public conversations to -HTML. Once you enable this module, users can join a room using a MUC capable -XMPP client, and if they have enough privileges, they can request the -configuration form in which they can set the option to enable room logging.

    Features: -

    • -Room details are added on top of each page: room title, JID, -author, subject and configuration. -
    • -The room JID in the generated HTML is a link to join the room (using -XMPP URI). -
    • Subject and room configuration changes are tracked and displayed. -
    • Joins, leaves, nick changes, kicks, bans and ‘/me’ are tracked and -displayed, including the reason if available. -
    • Generated HTML files are XHTML 1.0 Transitional and CSS compliant. -
    • Timestamps are self-referencing links. -
    • Links on top for quicker navigation: Previous day, Next day, Up. -
    • CSS is used for style definition, and a custom CSS file can be used. -
    • URLs on messages and subjects are converted to hyperlinks. -
    • Timezone used on timestamps is shown on the log files. -
    • A custom link can be added on top of each page. -

    Options: -

    -{access_log, AccessName}
    -This option restricts which occupants are allowed to enable or disable room -logging. The default value is muc_admin. Note for this default setting -you need to have an access rule for muc_admin in order to take effect. -
    {cssfile, false|URL}
    -With this option you can set whether the HTML files should have a custom CSS -file or if they need to use the embedded CSS file. Allowed values are -false and an URL to a CSS file. With the first value, HTML files will -include the embedded CSS code. With the latter, you can specify the URL of the -custom CSS file (for example: "http://example.com/my.css"). The default value -is false. -
    {dirname, room_jid|room_name}
    -Allows to configure the name of the room directory. -Allowed values are room_jid and room_name. -With the first value, the room directory name will be the full room JID. -With the latter, the room directory name will be only the room name, -not including the MUC service name. -The default value is room_jid. -
    {dirtype, subdirs|plain}
    -The type of the created directories can be specified with this option. Allowed -values are subdirs and plain. With the first value, -subdirectories are created for each year and month. With the latter, the -names of the log files contain the full date, and there are no subdirectories. -The default value is subdirs. -
    {file_format, html|plaintext}
    -Define the format of the log files: -html stores in HTML format, -plaintext stores in plain text. -The default value is html. -
    {outdir, Path}
    -This option sets the full path to the directory in which the HTML files should -be stored. Make sure the ejabberd daemon user has write access on that -directory. The default value is "www/muc". -
    {spam_prevention true|false}
    -To prevent spam, the spam_prevention option adds a special attribute -to links that prevent their indexation by search engines. The default value -is true, which mean that nofollow attributes will be added to user -submitted links. -
    {timezone, local|universal}
    -The time zone for the logs is configurable with this option. Allowed values -are local and universal. With the first value, the local time, -as reported to Erlang by the operating system, will be used. With the latter, -GMT/UTC time will be used. The default value is local. -
    {top_link, {URL, Text}}
    -With this option you can customize the link on the top right corner of each -log file. The default value is {"/", "Home"}. -

    Examples: -

    • -In the first example any room owner can enable logging, and a -custom CSS file will be used (http://example.com/my.css). The names -of the log files will contain the full date, and there will be no -subdirectories. The log files will be stored in /var/www/muclogs, and the -time zone will be GMT/UTC. Finally, the top link will be -<a href="http://www.jabber.ru/">Jabber.ru</a>. -
      {access, muc, [{allow, all}]}.
      -
      -{modules,
      - [
      -  ...
      -  {mod_muc_log, [
      -                 {access_log, muc},
      -                 {cssfile, "http://example.com/my.css"},
      -                 {dirtype, plain},
      -                 {dirname, room_jid},
      -                 {outdir, "/var/www/muclogs"},
      -                 {timezone, universal},
      -                 {spam_prevention, true},
      -                 {top_link, {"http://www.jabber.ru/", "Jabber.ru"}}
      -                ]},
      -  ...
      - ]}.
      -
    • In the second example only admin1@example.org and -admin2@example.net can enable logging, and the embedded CSS file will be -used. The names of the log files will only contain the day (number), -and there will be subdirectories for each year and month. The log files will -be stored in /var/www/muclogs, and the local time will be used. Finally, the -top link will be the default <a href="/">Home</a>. -
      {acl, admins, {user, "admin1", "example.org"}}.
      -{acl, admins, {user, "admin2", "example.net"}}.
      -
      -{access, muc_log, [{allow, admins},
      -                   {deny, all}]}.
      -
      -{modules,
      - [
      -  ...
      -  {mod_muc_log, [
      -                 {access_log, muc_log},
      -                 {cssfile, false},
      -                 {dirtype, subdirs},
      -                 {outdir, "/var/www/muclogs"},
      -                 {timezone, local}
      -                ]},
      -  ...
      - ]}.
      -

    -

    3.3.12  mod_offline

    -

    This module implements offline message storage (XEP-0160). -This means that all messages -sent to an offline user will be stored on the server until that user comes -online again. Thus it is very similar to how email works. Note that -ejabberdctl has a command to delete expired messages -(see section 4.1).

    -{access_max_user_messages, AccessName}
    -This option defines which access rule will be enforced to limit -the maximum number of offline messages that a user can have (quota). -When a user has too many offline messages, any new messages that he receive are discarded, -and a resource-constraint error is returned to the sender. -The default value is max_user_offline_messages. -Then you can define an access rule with a syntax similar to -max_user_sessions (see 3.1.5). -

    This example allows power users to have as much as 5000 offline messages, -administrators up to 2000, -and all the other users up to 100. -

    {acl, admin, {user, "admin1", "localhost"}}.
    -{acl, admin, {user, "admin2", "example.org"}}.
    -{acl, poweruser, {user, "bob", "example.org"}}.
    -{acl, poweruser, {user, "jane", "example.org"}}.
    -
    -{access, max_user_offline_messages, [ {5000, poweruser}, {2000, admin}, {100, all} ]}.
    -
    -{modules,
    - [
    -  ...
    -  {mod_offline,  [ {access_max_user_messages, max_user_offline_messages} ]},
    -  ...
    - ]}.
    -

    -

    3.3.13  mod_ping

    -

    This module implements support for XMPP Ping (XEP-0199) and periodic keepalives. -When this module is enabled ejabberd responds correctly to -ping requests, as defined in the protocol.

    Configuration options: -

    -{send_pings, true|false}
    -If this option is set to true, the server sends pings to connected clients -that are not active in a given interval ping_interval. -This is useful to keep client connections alive or checking availability. -By default this option is disabled. -
    {ping_interval, Seconds}
    -How often to send pings to connected clients, if the previous option is enabled. -If a client connection does not send or receive any stanza in this interval, -a ping request is sent to the client. -The default value is 60 seconds. -
    {timeout_action, none|kill}
    -What to do when a client does not answer to a server ping request in less than 32 seconds. -The default is to do nothing. -

    This example enables Ping responses, configures the module to send pings -to client connections that are inactive for 4 minutes, -and if a client does not answer to the ping in less than 32 seconds, its connection is closed: -

    {modules,
    - [
    -  ...
    -  {mod_ping,  [{send_pings, true}, {ping_interval, 240}, {timeout_action, kill}]},
    -  ...
    - ]}.
    -

    -

    3.3.14  mod_privacy

    -

    This module implements Blocking Communication (also known as Privacy Rules) -as defined in section 10 from XMPP IM. If end users have support for it in -their XMPP client, they will be able to: -

    -
    • -Retrieving one’s privacy lists. -
    • Adding, removing, and editing one’s privacy lists. -
    • Setting, changing, or declining active lists. -
    • Setting, changing, or declining the default list (i.e., the list that -is active by default). -
    • Allowing or blocking messages based on JID, group, or subscription type -(or globally). -
    • Allowing or blocking inbound presence notifications based on JID, group, -or subscription type (or globally). -
    • Allowing or blocking outbound presence notifications based on JID, group, -or subscription type (or globally). -
    • Allowing or blocking IQ stanzas based on JID, group, or subscription type -(or globally). -
    • Allowing or blocking all communications based on JID, group, or -subscription type (or globally). -
    -(from http://xmpp.org/rfcs/rfc3921.html#privacy) -

    Options: -

    -{iqdisc, Discipline}
    This specifies -the processing discipline for Blocking Communication (jabber:iq:privacy) IQ queries (see section 3.3.2). -

    -

    3.3.15  mod_private

    -

    This module adds support for Private XML Storage (XEP-0049): -

    -Using this method, XMPP entities can store private data on the server and -retrieve it whenever necessary. The data stored might be anything, as long as -it is valid XML. One typical usage for this namespace is the server-side storage -of client-specific preferences; another is Bookmark Storage (XEP-0048). -

    Options: -

    -{iqdisc, Discipline}
    This specifies -the processing discipline for Private XML Storage (jabber:iq:private) IQ queries (see section 3.3.2). -

    -

    3.3.16  mod_proxy65

    -

    This module implements SOCKS5 Bytestreams (XEP-0065). -It allows ejabberd to act as a file transfer proxy between two -XMPP clients.

    Options: -

    - -{host, HostName}
    This option defines the Jabber ID of the -service. If the host option is not specified, the Jabber ID will be the -hostname of the virtual host with the prefix ‘proxy.’. The keyword "@HOST@" -is replaced at start time with the real virtual host name. - -
    {name, Text}
    Defines Service Discovery name of the service. -Default is "SOCKS5 Bytestreams". -
    {ip, IPTuple}
    This option specifies which network interface -to listen for. Default is an IP address of the service’s DNS name, or, -if fails, {127,0,0,1}. -
    {port, Number}
    This option defines port to listen for -incoming connections. Default is 7777. -
    {hostname, HostName}
    Defines a hostname advertised -by the service when establishing a session with clients. This is useful when -you run the service behind a NAT. The default is the value of ip option. -Examples: "proxy.mydomain.org", "200.150.100.50". Note that -not all clients understand domain names in stream negotiation, -so you should think twice before setting domain name in this option. -
    {auth_type, anonymous|plain}
    SOCKS5 authentication type. -Possible values are anonymous and plain. Default is -anonymous. -
    {access, AccessName}
    Defines ACL for file transfer initiators. -Default is all. -
    {max_connections, Number}
    Maximum number of -active connections per file transfer initiator. No limit by default. -
    {shaper, none|ShaperName}
    This option defines shaper for -the file transfer peers. Shaper with the maximum bandwidth will be selected. -Default is none. -

    Examples: -

    • -The simpliest configuration of the module: -
      {modules,
      - [
      -  ...
      -  {mod_proxy65, []},
      -  ...
      - ]}.
      -
    • More complicated configuration. -
      {acl, proxy_users, {server, "example.org"}}.
      -{access, proxy65_access, [{allow, proxy_users}, {deny, all}]}.
      -
      -{acl, admin, {user, "admin", "example.org"}}.
      -{shaper, proxyrate, {maxrate, 10240}}. %% 10 Kbytes/sec
      -{access, proxy65_shaper, [{none, admin}, {proxyrate, proxy_users}]}.
      -
      -{modules,
      - [
      -  ...
      -  {mod_proxy65, [{host, "proxy1.example.org"},
      -                 {name, "File Transfer Proxy"},
      -                 {ip, {200,150,100,1}},
      -                 {port, 7778},
      -                 {max_connections, 5},
      -                 {access, proxy65_access},
      -                 {shaper, proxy65_shaper}]},
      -  ...
      - ]}.
      -

    -

    3.3.17  mod_pubsub

    -

    This module offers a Publish-Subscribe Service (XEP-0060). -The functionality in mod_pubsub can be extended using plugins. -The plugin that implements PEP (Personal Eventing via Pubsub) (XEP-0163) -is enabled in the default ejabberd configuration file, -and it requires mod_caps.

    Options: -

    - -{host, HostName}
    This option defines the Jabber ID of the -service. If the host option is not specified, the Jabber ID will be the -hostname of the virtual host with the prefix ‘pubsub.’. The keyword "@HOST@" -is replaced at start time with the real virtual host name. - -If you use mod_pubsub_odbc, please ensure the prefix contains only one dot, -for example ‘pubsub.’, or ‘publish.’,. -
    {access_createnode, AccessName}
    -This option restricts which users are allowed to create pubsub nodes using -ACL and ACCESS. -By default any account in the local ejabberd server is allowed to create pubsub nodes. -
    {max_items_node, MaxItems}
    -Define the maximum number of items that can be stored in a node. -Default value is 10. -
    {plugins, [ Plugin, ...]}
    -To specify which pubsub node plugins to use. -The first one in the list is used by default. -If this option is not defined, the default plugins list is: ["flat"]. -PubSub clients can define which plugin to use when creating a node: -add type=’plugin-name’ attribute to the create stanza element. -
    {nodetree, Nodetree}
    -To specify which nodetree to use. -If not defined, the default pubsub nodetree is used: "tree". -Only one nodetree can be used per host, and is shared by all node plugins.

    The "virtual" nodetree does not store nodes on database. -This saves resources on systems with tons of nodes. -If using the "virtual" nodetree, -you can only enable those node plugins: -["flat","pep"] or ["flat"]; -any other plugins configuration will not work. -Also, all nodes will have the defaut configuration, -and this can not be changed. -Using "virtual" nodetree requires to start from a clean database, -it will not work if you used the default "tree" nodetree before.

    The "dag" nodetree provides experimental support for PubSub Collection Nodes (XEP-0248). -In that case you should also add "dag" node plugin as default, for example: -{plugins, ["dag","flat","hometree","pep"]} -

    {ignore_pep_from_offline, false|true}
    -To specify whether or not we should get last published PEP items -from users in our roster which are offline when we connect. Value is true or false. -If not defined, pubsub assumes true so we only get last items of online contacts. -
    {last_item_cache, false|true}
    -To specify whether or not pubsub should cache last items. Value is true -or false. If not defined, pubsub do not cache last items. On systems with not so many nodes, -caching last items speeds up pubsub and allows to raise user connection rate. The cost is memory -usage, as every item is stored in memory. -
    {pep_mapping, [ {Key, Value}, ...]}
    -This allow to define a Key-Value list to choose defined node plugins on given PEP namespace. -The following example will use node_tune instead of node_pep for every PEP node with tune namespace: -
      {mod_pubsub, [{pep_mapping, [{"http://jabber.org/protocol/tune", "tune"}]}]}
    -

    Example of configuration that uses flat nodes as default, and allows use of flat, nodetree and pep nodes: -

    {modules,
    - [
    -  ...
    -  {mod_pubsub, [
    -                {access_createnode, pubsub_createnode},
    -                {plugins, ["flat", "hometree", "pep"]}
    -               ]},
    -  ...
    - ]}.
    -

    Using ODBC database requires use of dedicated plugins. The following example shows previous configuration -with ODBC usage: -

    {modules,
    - [
    -  ...
    -  {mod_pubsub_odbc, [
    -                {access_createnode, pubsub_createnode},
    -                {plugins, ["flat_odbc", "hometree_odbc", "pep_odbc"]}
    -               ]},
    -  ...
    - ]}.
    -

    -

    3.3.18  mod_register

    -

    This module adds support for In-Band Registration (XEP-0077). This protocol -enables end users to use a XMPP client to: -

    • -Register a new account on the server. -
    • Change the password from an existing account on the server. -
    • Delete an existing account on the server. -

    Options: -

    -{access, AccessName}
    This option can be configured to specify -rules to restrict registration. If a rule returns ‘deny’ on the requested -user name, registration for that user name is denied. (there are no -restrictions by default). -
    {access_from, AccessName}
    By default, ejabberd -doesn’t allow to register new accounts from s2s or existing c2s sessions. You can -change it by defining access rule in this option. Use with care: allowing registration -from s2s leads to uncontrolled massive accounts creation by rogue users. -
    {welcome_message, Message}
    Set a welcome message that -is sent to each newly registered account. The first string is the subject, and -the second string is the message body. -In the body you can set a newline with the characters: \n -
    {registration_watchers, [ JID, ...]}
    This option defines a -list of JIDs which will be notified each time a new account is registered. -
    {iqdisc, Discipline}
    This specifies -the processing discipline for In-Band Registration (jabber:iq:register) IQ queries (see section 3.3.2). -

    This module reads also another option defined globally for the server: -{registration_timeout, Timeout}. -This option limits the frequency of registration from a given IP or username. -So, a user that tries to register a new account from the same IP address or JID during -this number of seconds after his previous registration -will receive an error resource-constraint with the explanation: -“Users are not allowed to register accounts so quickly”. -The timeout is expressed in seconds, and it must be an integer. -To disable this limitation, -instead of an integer put a word like: infinity. -Default value: 600 seconds.

    Examples: -

    • -Next example prohibits the registration of too short account names: -
      {acl, shortname, {user_glob, "?"}}.
      -{acl, shortname, {user_glob, "??"}}.
      -%% The same using regexp:
      -%%{acl, shortname, {user_regexp, "^..?$"}}.
      -
      -{access, register, [{deny, shortname},
      -                    {allow, all}]}.
      -
      -{modules,
      - [
      -  ...
      -  {mod_register, [{access, register}]},
      -  ...
      - ]}.
      -
    • This configuration prohibits usage of In-Band Registration -to create or delete accounts, -but allows existing accounts to change the password: -
      {access, register, [{deny, all}]}.
      -
      -{modules,
      - [
      -  ...
      -  {mod_register, [{access, register}]},
      -  ...
      - ]}.
      -
    • This configuration disables all In-Band Registration -functionality: create, delete accounts and change password: -
      {modules,
      - [
      -  ...
      -  %% {mod_register, [{access, register}]},
      -  ...
      - ]}.
      -
    • Define the welcome message and two registration watchers. -Also define a registration timeout of one hour: -
      {registration_timeout, 3600}.
      -{modules,
      - [
      -  ...
      -  {mod_register,
      -   [
      -    {welcome_message, {"Welcome!", "Hi.\nWelcome to this Jabber server.\n Check http://www.jabber.org\n\nBye"}},
      -    {registration_watchers, ["admin1@example.org", "boss@example.net"]}
      -   ]},
      -  ...
      - ]}.
      -

    -

    3.3.19  mod_roster

    -

    This module implements roster management as defined in -RFC 3921: XMPP IM. -It also supports Roster Versioning (XEP-0237).

    Options: -

    -{iqdisc, Discipline}
    This specifies -the processing discipline for Roster Management (jabber:iq:roster) IQ queries (see section 3.3.2). -
    {versioning, false|true}
    Enables -Roster Versioning. -This option is disabled by default. -
    {store_current_id, false|true}
    -If this option is enabled, the current version number is stored on the database. -If disabled, the version number is calculated on the fly each time. -Enabling this option reduces the load for both ejabberd and the database. -This option does not affect the client in any way. -This option is only useful if Roster Versioning is enabled. -This option is disabled by default. -Important: if you use mod_shared_roster, you must disable this option. -

    This example configuration enables Roster Versioning with storage of current id: -

    {modules,
    - [
    -  ...
    -  {mod_roster, [{versioning, true}, {store_current_id, true}]},
    -  ...
    - ]}.
    -

    -

    3.3.20  mod_service_log

    -

    This module adds support for logging end user packets via a XMPP message -auditing service such as -Bandersnatch. All user -packets are encapsulated in a <route/> element and sent to the specified -service(s).

    Options: -

    -{loggers, [Names, ...]}
    With this option a (list of) service(s) -that will receive the packets can be specified. -

    Examples: -

    • -To log all end user packets to the Bandersnatch service running on -bandersnatch.example.com: -
      {modules,
      - [
      -  ...
      -  {mod_service_log, [{loggers, ["bandersnatch.example.com"]}]},
      -  ...
      - ]}.
      -
    • To log all end user packets to the Bandersnatch service running on -bandersnatch.example.com and the backup service on -bandersnatch.example.org: -
      {modules,
      - [
      -  ...
      -  {mod_service_log, [{loggers, ["bandersnatch.example.com",
      -                                "bandersnatch.example.org"]}]},
      -  ...
      - ]}.
      -

    -

    3.3.21  mod_shared_roster

    -

    This module enables you to create shared roster groups. This means that you can -create groups of people that can see members from (other) groups in their -rosters. The big advantages of this feature are that end users do not need to -manually add all users to their rosters, and that they cannot permanently delete -users from the shared roster groups. -A shared roster group can have members from any XMPP server, -but the presence will only be available from and to members -of the same virtual host where the group is created.

    Shared roster groups can be edited only via the Web Admin. Each group -has a unique identification and the following parameters: -

    -Name
    The name of the group, which will be displayed in the roster. -
    Description
    The description of the group. This parameter does not affect -anything. -
    Members
    A list of full JIDs of group members, entered one per line in -the Web Admin. -To put as members all the registered users in the virtual hosts, -you can use the special directive: @all@. -Note that this directive is designed for a small server with just a few hundred users. -
    Displayed groups
    A list of groups that will be in the rosters of this -group’s members. -

    Examples: -

    • -Take the case of a computer club that wants all its members seeing each -other in their rosters. To achieve this, they need to create a shared roster -group similar to next table: -

      - - - - - -
      IdentificationGroup ‘club_members
      NameClub Members
      DescriptionMembers from the computer club
      Members - - -
      member1@example.org
      member2@example.org
      member3@example.org
      Displayed groupsclub_members
      -

      -
    • In another case we have a company which has three divisions: Management, -Marketing and Sales. All group members should see all other members in their -rosters. Additionally, all managers should have all marketing and sales people -in their roster. Simultaneously, all marketeers and the whole sales team -should see all managers. This scenario can be achieved by creating shared -roster groups as shown in the following table: -

      - - - - - -
      Identification Group ‘management Group ‘marketing Group ‘sales
      NameManagementMarketingSales
      Description 
      Members - - - -
      manager1@example.org
      manager2@example.org
      manager3@example.org
      manager4@example.org
      -
      - - - -
      marketeer1@example.org
      marketeer2@example.org
      marketeer3@example.org
      marketeer4@example.org
      -
      - - - -
      saleswoman1@example.org
      salesman1@example.org
      saleswoman2@example.org
      salesman2@example.org
      Displayed groups - - -
      management
      marketing
      sales
      -
      - -
      management
      marketing
      -
      - -
      management
      sales
      -

      -

    -

    3.3.22  mod_sic

    -

    This module adds support for Server IP Check (XEP-0279). This protocol -enables a client to discover its external IP address.

    Options: -

    -{iqdisc, Discipline}
    This specifies -the processing discipline for urn:xmpp:sic:0 IQ queries (see section 3.3.2). -

    -

    3.3.23  mod_stats

    -

    This module adds support for Statistics Gathering (XEP-0039). This protocol -allows you to retrieve next statistics from your ejabberd deployment: -

    • -Total number of registered users on the current virtual host (users/total). -
    • Total number of registered users on all virtual hosts (users/all-hosts/total). -
    • Total number of online users on the current virtual host (users/online). -
    • Total number of online users on all virtual hosts (users/all-hosts/online). -

    Options: -

    -{iqdisc, Discipline}
    This specifies -the processing discipline for Statistics Gathering (http://jabber.org/protocol/stats) IQ queries (see section 3.3.2). -

    As there are only a small amount of clients (for example -Tkabber) and software libraries with -support for this XEP, a few examples are given of the XML you need to send -in order to get the statistics. Here they are: -

    • -You can request the number of online users on the current virtual host -(example.org) by sending: -
      <iq to='example.org' type='get'>
      -  <query xmlns='http://jabber.org/protocol/stats'>
      -    <stat name='users/online'/>
      -  </query>
      -</iq>
      -
    • You can request the total number of registered users on all virtual hosts -by sending: -
      <iq to='example.org' type='get'>
      -  <query xmlns='http://jabber.org/protocol/stats'>
      -    <stat name='users/all-hosts/total'/>
      -  </query>
      -</iq>
      -

    -

    3.3.24  mod_time

    -

    This module features support for Entity Time (XEP-0202). By using this XEP, -you are able to discover the time at another entity’s location.

    Options: -

    -{iqdisc, Discipline}
    This specifies -the processing discipline for Entity Time (jabber:iq:time) IQ queries (see section 3.3.2). -

    -

    3.3.25  mod_vcard

    -

    This module allows end users to store and retrieve their vCard, and to retrieve -other users vCards, as defined in vcard-temp (XEP-0054). The module also -implements an uncomplicated Jabber User Directory based on the vCards of -these users. Moreover, it enables the server to send its vCard when queried.

    Options: -

    - -{host, HostName}
    This option defines the Jabber ID of the -service. If the host option is not specified, the Jabber ID will be the -hostname of the virtual host with the prefix ‘vjud.’. The keyword "@HOST@" -is replaced at start time with the real virtual host name. - -
    {iqdisc, Discipline}
    This specifies -the processing discipline for vcard-temp IQ queries (see section 3.3.2). -
    {search, true|false}
    This option specifies whether the search -functionality is enabled or not -If disabled, the option host will be ignored and the -Jabber User Directory service will not appear in the Service Discovery item -list. The default value is true. -
    {matches, infinity|Number}
    With this option, the number of reported -search results can be limited. If the option’s value is set to infinity, -all search results are reported. The default value is 30. -
    {allow_return_all, false|true}
    This option enables -you to specify if search operations with empty input fields should return all -users who added some information to their vCard. The default value is -false. -
    {search_all_hosts, true|false}
    If this option is set -to true, search operations will apply to all virtual hosts. Otherwise -only the current host will be searched. The default value is true. -This option is available in mod_vcard, but not available in mod_vcard_odbc. -

    Examples: -

    • -In this first situation, search results are limited to twenty items, -every user who added information to their vCard will be listed when people -do an empty search, and only users from the current host will be returned: -
      {modules,
      - [
      -  ...
      -  {mod_vcard, [{search, true},
      -               {matches, 20},
      -               {allow_return_all, true},
      -               {search_all_hosts, false}]},
      -  ...
      - ]}.
      -
    • The second situation differs in a way that search results are not limited, -and that all virtual hosts will be searched instead of only the current one: -
      {modules,
      - [
      -  ...
      -  {mod_vcard, [{search, true},
      -               {matches, infinity},
      -               {allow_return_all, true}]},
      -  ...
      - ]}.
      -

    -

    3.3.26  mod_vcard_ldap

    -

    ejabberd can map LDAP attributes to vCard fields. This behaviour is -implemented in the mod_vcard_ldap module. This module does not depend on the -authentication method (see 3.2.5).

    Usually ejabberd treats LDAP as a read-only storage: -it is possible to consult data, but not possible to -create accounts or edit vCard that is stored in LDAP. -However, it is possible to change passwords if mod_register module is enabled -and LDAP server supports -RFC 3062.

    The mod_vcard_ldap module has -its own optional parameters. The first group of parameters has the same -meaning as the top-level LDAP parameters to set the authentication method: -ldap_servers, ldap_port, ldap_rootdn, -ldap_password, ldap_base, ldap_uids, and -ldap_filter. See section 3.2.5 for detailed information -about these options. If one of these options is not set, ejabberd will look -for the top-level option with the same name.

    The second group of parameters -consists of the following mod_vcard_ldap-specific options:

    - -{host, HostName}
    This option defines the Jabber ID of the -service. If the host option is not specified, the Jabber ID will be the -hostname of the virtual host with the prefix ‘vjud.’. The keyword "@HOST@" -is replaced at start time with the real virtual host name. - -
    {iqdisc, Discipline}
    This specifies -the processing discipline for vcard-temp IQ queries (see section 3.3.2). -
    {search, true|false}
    This option specifies whether the search -functionality is enabled (value: true) or disabled (value: -false). If disabled, the option host will be ignored and the -Jabber User Directory service will not appear in the Service Discovery item -list. The default value is true. -
    {matches, infinity|Number}
    With this option, the number of reported -search results can be limited. If the option’s value is set to infinity, -all search results are reported. The default value is 30. -
    {ldap_vcard_map, [ {Name, Pattern, LDAPattributes}, ...]}
    -With this option you can set the table that maps LDAP attributes to vCard fields. - -Name is the type name of the vCard as defined in -RFC 2426. -Pattern is a string which contains pattern variables -"%u", "%d" or "%s". -LDAPattributes is the list containing LDAP attributes. -The pattern variables -"%s" will be sequentially replaced -with the values of LDAP attributes from List_of_LDAP_attributes, -"%u" will be replaced with the user part of a JID, -and "%d" will be replaced with the domain part of a JID. -The default is: -
    [{"NICKNAME", "%u", []},
    - {"FN", "%s", ["displayName"]},
    - {"LAST", "%s", ["sn"]},
    - {"FIRST", "%s", ["givenName"]},
    - {"MIDDLE", "%s", ["initials"]},
    - {"ORGNAME", "%s", ["o"]},
    - {"ORGUNIT", "%s", ["ou"]},
    - {"CTRY", "%s", ["c"]},
    - {"LOCALITY", "%s", ["l"]},
    - {"STREET", "%s", ["street"]},
    - {"REGION", "%s", ["st"]},
    - {"PCODE", "%s", ["postalCode"]},
    - {"TITLE", "%s", ["title"]},
    - {"URL", "%s", ["labeleduri"]},
    - {"DESC", "%s", ["description"]},
    - {"TEL", "%s", ["telephoneNumber"]},
    - {"EMAIL", "%s", ["mail"]},
    - {"BDAY", "%s", ["birthDay"]},
    - {"ROLE", "%s", ["employeeType"]},
    - {"PHOTO", "%s", ["jpegPhoto"]}]
    -
    {ldap_search_fields, [ {Name, Attribute}, ...]}
    This option -defines the search form and the LDAP attributes to search within. -Name is the name of a search form -field which will be automatically translated by using the translation -files (see msgs/*.msg for available words). Attribute is the -LDAP attribute or the pattern "%u". The default is: -
    [{"User", "%u"},
    - {"Full Name", "displayName"},
    - {"Given Name", "givenName"},
    - {"Middle Name", "initials"},
    - {"Family Name", "sn"},
    - {"Nickname", "%u"},
    - {"Birthday", "birthDay"},
    - {"Country", "c"},
    - {"City", "l"},
    - {"Email", "mail"},
    - {"Organization Name", "o"},
    - {"Organization Unit", "ou"}]
    -
    {ldap_search_reported, [ {SearchField, VcardField}, ...]}
    This option -defines which search fields should be reported. -SearchField is the name of a search form -field which will be automatically translated by using the translation -files (see msgs/*.msg for available words). VcardField is the -vCard field name defined in the ldap_vcard_map option. The default -is: -
    [{"Full Name", "FN"},
    - {"Given Name", "FIRST"},
    - {"Middle Name", "MIDDLE"},
    - {"Family Name", "LAST"},
    - {"Nickname", "NICKNAME"},
    - {"Birthday", "BDAY"},
    - {"Country", "CTRY"},
    - {"City", "LOCALITY"},
    - {"Email", "EMAIL"},
    - {"Organization Name", "ORGNAME"},
    - {"Organization Unit", "ORGUNIT"}]
    -

    Examples: -

    • -

      Let’s say ldap.example.org is the name of our LDAP server. We have -users with their passwords in "ou=Users,dc=example,dc=org" directory. -Also we have addressbook, which contains users emails and their additional -infos in "ou=AddressBook,dc=example,dc=org" directory. Corresponding -authentication section should looks like this:

      %% authentication method
      -{auth_method, ldap}.
      -%% DNS name of our LDAP server
      -{ldap_servers, ["ldap.example.org"]}.
      -%% We want to authorize users from 'shadowAccount' object class only
      -{ldap_filter, "(objectClass=shadowAccount)"}.
      -

      Now we want to use users LDAP-info as their vCards. We have four attributes -defined in our LDAP schema: "mail" — email address, "givenName" -— first name, "sn" — second name, "birthDay" — birthday. -Also we want users to search each other. Let’s see how we can set it up:

      {modules,
      -  ...
      -  {mod_vcard_ldap,
      -   [
      -    %% We use the same server and port, but want to bind anonymously because
      -    %% our LDAP server accepts anonymous requests to
      -    %% "ou=AddressBook,dc=example,dc=org" subtree.
      -    {ldap_rootdn, ""},
      -    {ldap_password, ""},
      -    %% define the addressbook's base
      -    {ldap_base, "ou=AddressBook,dc=example,dc=org"},
      -    %% uidattr: user's part of JID is located in the "mail" attribute
      -    %% uidattr_format: common format for our emails
      -    {ldap_uids, [{"mail","%u@mail.example.org"}]},
      -    %% We have to define empty filter here, because entries in addressbook does not
      -    %% belong to shadowAccount object class
      -    {ldap_filter, ""},
      -    %% Now we want to define vCard pattern
      -    {ldap_vcard_map,
      -     [{"NICKNAME", "%u", []}, % just use user's part of JID as his nickname
      -      {"FIRST", "%s", ["givenName"]},
      -      {"LAST", "%s", ["sn"]},
      -      {"FN", "%s, %s", ["sn", "givenName"]}, % example: "Smith, John"
      -      {"EMAIL", "%s", ["mail"]},
      -      {"BDAY", "%s", ["birthDay"]}]},
      -    %% Search form
      -    {ldap_search_fields,
      -     [{"User", "%u"},
      -      {"Name", "givenName"},
      -      {"Family Name", "sn"},
      -      {"Email", "mail"},
      -      {"Birthday", "birthDay"}]},
      -    %% vCard fields to be reported
      -    %% Note that JID is always returned with search results
      -    {ldap_search_reported,
      -     [{"Full Name", "FN"},
      -      {"Nickname", "NICKNAME"},
      -      {"Birthday", "BDAY"}]}
      -  ]}
      -  ...
      -}.
      -

      Note that mod_vcard_ldap module checks an existence of the user before -searching his info in LDAP.

    • ldap_vcard_map example: -
      {ldap_vcard_map,
      - [{"NICKNAME", "%u", []},
      -  {"FN", "%s", ["displayName"]},
      -  {"CTRY", "Russia", []},
      -  {"EMAIL", "%u@%d", []},
      -  {"DESC", "%s\n%s", ["title", "description"]}
      - ]},
      -
    • ldap_search_fields example: -
      {ldap_search_fields,
      - [{"User", "uid"},
      -  {"Full Name", "displayName"},
      -  {"Email", "mail"}
      - ]},
      -
    • ldap_search_reported example: -
      {ldap_search_reported,
      - [{"Full Name", "FN"},
      -  {"Email", "EMAIL"},
      -  {"Birthday", "BDAY"},
      -  {"Nickname", "NICKNAME"}
      - ]},
      -

    -

    3.3.27  mod_vcard_xupdate

    -

    The user’s client can store an avatar in the user vCard. -The vCard-Based Avatars protocol (XEP-0153) -provides a method for clients to inform the contacts what is the avatar hash value. -However, simple or small clients may not implement that protocol.

    If this module is enabled, all the outgoing client presence stanzas get automatically -the avatar hash on behalf of the client. -So, the contacts receive the presence stanzas with the Update Data described -in XEP-0153 as if the client would had inserted it itself. -If the client had already included such element in the presence stanza, -it is replaced with the element generated by ejabberd.

    By enabling this module, each vCard modification produces a hash recalculation, -and each presence sent by a client produces hash retrieval and a -presence stanza rewrite. -For this reason, enabling this module will introduce a computational overhead -in servers with clients that change frequently their presence.

    -

    3.3.28  mod_version

    -

    This module implements Software Version (XEP-0092). Consequently, it -answers ejabberd’s version when queried.

    Options: -

    -{show_os, true|false}
    Should the operating system be revealed or not. -The default value is true. -
    {iqdisc, Discipline}
    This specifies -the processing discipline for Software Version (jabber:iq:version) IQ queries (see section 3.3.2). -

    -

    Chapter 4  Managing an ejabberd Server

    -

    4.1  ejabberdctl

    With the ejabberdctl command line administration script -you can execute ejabberdctl commands (described in the next section, 4.1.1) -and also many general ejabberd commands (described in section 4.2). -This means you can start, stop and perform many other administrative tasks -in a local or remote ejabberd server (by providing the argument --node NODENAME).

    The ejabberdctl script can be configured in the file ejabberdctl.cfg. -This file includes detailed information about each configurable option. See section 4.1.2.

    The ejabberdctl script returns a numerical status code. -Success is represented by 0, -error is represented by 1, -and other codes may be used for specific results. -This can be used by other scripts to determine automatically -if a command succeeded or failed, -for example using: echo $?

    -

    4.1.1  ejabberdctl Commands

    When ejabberdctl is executed without any parameter, -it displays the available options. If there isn’t an ejabberd server running, -the available parameters are: -

    -start
    Start ejabberd in background mode. This is the default method. -
    debug
    Attach an Erlang shell to an already existing ejabberd server. This allows to execute commands interactively in the ejabberd server. -
    live
    Start ejabberd in live mode: the shell keeps attached to the started server, showing log messages and allowing to execute interactive commands. -

    If there is an ejabberd server running in the system, -ejabberdctl shows the ejabberdctl commands described bellow -and all the ejabberd commands available in that server (see 4.2.1).

    The ejabberdctl commands are: -

    -help
    Get help about ejabberdctl or any available command. Try ejabberdctl help help. -
    status
    Check the status of the ejabberd server. -
    stop
    Stop the ejabberd server. -
    restart
    Restart the ejabberd server. -
    mnesia
    Get information about the Mnesia database. -

    The ejabberdctl script can be restricted to require authentication -and execute some ejabberd commands; see 4.2.2. -Add the option to the file ejabberd.cfg. -In this example there is no restriction: -

    {ejabberdctl_access_commands, []}.
    -

    If account robot1@example.org is registered in ejabberd with password abcdef -(which MD5 is E8B501798950FC58AAD83C8C14978E), -and ejabberd.cfg contains this setting: -

    {hosts, ["example.org"]}.
    -{acl, bots, {user, "robot1", "example.org"}}.
    -{access, ctlaccess, [{allow, bots}]}.
    -{ejabberdctl_access_commands, [ {ctlaccess, [registered_users, register], []} ]}.
    -

    then you can do this in the shell: -

    $ ejabberdctl registered_users example.org
    -Error: no_auth_provided
    -$ ejabberdctl --auth robot1 example.org E8B501798950FC58AAD83C8C14978E registered_users example.org
    -robot1
    -testuser1
    -testuser2
    -

    -

    4.1.2  Erlang Runtime System

    ejabberd is an Erlang/OTP application that runs inside an Erlang runtime system. -This system is configured using environment variables and command line parameters. -The ejabberdctl administration script uses many of those possibilities. -You can configure some of them with the file ejabberdctl.cfg, -which includes detailed description about them. -This section describes for reference purposes -all the environment variables and command line parameters.

    The environment variables: -

    -EJABBERD_CONFIG_PATH
    - Path to the ejabberd configuration file. -
    EJABBERD_MSGS_PATH
    - Path to the directory with translated strings. -
    EJABBERD_LOG_PATH
    - Path to the ejabberd service log file. -
    EJABBERD_SO_PATH
    - Path to the directory with binary system libraries. -
    EJABBERD_DOC_PATH
    - Path to the directory with ejabberd documentation. -
    EJABBERD_PID_PATH
    - Path to the PID file that ejabberd can create when started. -
    HOME
    - Path to the directory that is considered ejabberd’s home. - This path is used to read the file .erlang.cookie. -
    ERL_CRASH_DUMP
    - Path to the file where crash reports will be dumped. -
    ERL_INETRC
    - Indicates which IP name resolution to use. - If using -sname, specify either this option or -kernel inetrc filepath. -
    ERL_MAX_PORTS
    - Maximum number of simultaneously open Erlang ports. -
    ERL_MAX_ETS_TABLES
    - Maximum number of ETS and Mnesia tables. -

    The command line parameters: -

    --sname ejabberd
    - The Erlang node will be identified using only the first part - of the host name, i. e. other Erlang nodes outside this domain cannot contact - this node. This is the preferable option in most cases. -
    -name ejabberd
    - The Erlang node will be fully identified. -This is only useful if you plan to setup an ejabberd cluster with nodes in different networks. -
    -kernel inetrc ’"/etc/ejabberd/inetrc"’
    - Indicates which IP name resolution to use. - If using -sname, specify either this option or ERL_INETRC. -
    -kernel inet_dist_listen_min 4200 inet_dist_listen_min 4210
    - Define the first and last ports that epmd (section 5.2) can listen to. -
    -detached
    -Starts the Erlang system detached from the system console. - Useful for running daemons and backgrounds processes. -
    -noinput
    - Ensures that the Erlang system never tries to read any input. - Useful for running daemons and backgrounds processes. -
    -pa /var/lib/ejabberd/ebin
    - Specify the directory where Erlang binary files (*.beam) are located. -
    -s ejabberd
    - Tell Erlang runtime system to start the ejabberd application. -
    -mnesia dir ’"/var/lib/ejabberd/"’
    - Specify the Mnesia database directory. -
    -sasl sasl_error_logger {file, "/var/log/ejabberd/erlang.log"}
    - Path to the Erlang/OTP system log file. -SASL here means “System Architecture Support Libraries” -not “Simple Authentication and Security Layer”. -
    +K [true|false]
    - Kernel polling. -
    -smp [auto|enable|disable]
    - SMP support. -
    +P 250000
    - Maximum number of Erlang processes. -
    -remsh ejabberd@localhost
    - Open an Erlang shell in a remote Erlang node. -
    -hidden
    - The connections to other nodes are hidden (not published). - The result is that this node is not considered part of the cluster. - This is important when starting a temporary ctl or debug node. -

    -Note that some characters need to be escaped when used in shell scripts, for instance " and {}. -You can find other options in the Erlang manual page (erl -man erl).

    -

    4.2  ejabberd Commands

    An ejabberd command is an abstract function identified by a name, -with a defined number and type of calling arguments and type of result -that is registered in the ejabberd_commands service. -Those commands can be defined in any Erlang module and executed using any valid frontend.

    ejabberd includes a frontend to execute ejabberd commands: the script ejabberdctl. -Other known frontends that can be installed to execute ejabberd commands in different ways are: -ejabberd_xmlrpc (XML-RPC service), -mod_rest (HTTP POST service), -mod_shcommands (ejabberd WebAdmin page).

    -

    4.2.1  List of ejabberd Commands

    ejabberd includes a few ejabberd Commands by default. -When more modules are installed, new commands may be available in the frontends.

    The easiest way to get a list of the available commands, and get help for them is to use -the ejabberdctl script: -

    $ ejabberdctl help
    -Usage: ejabberdctl [--node nodename] [--auth user host password] command [options]
    -
    -Available commands in this ejabberd node:
    -  backup file                  Store the database to backup file
    -  connected_users              List all established sessions
    -  connected_users_number       Get the number of established sessions
    -  ...
    -

    The most interesting ones are: -

    -reopen_log
    Reopen the log files after they were renamed. -If the old files were not renamed before calling this command, -they are automatically renamed to "*-old.log". See section 7.1. -
    backup ejabberd.backup
    -Store internal Mnesia database to a binary backup file. -
    restore ejabberd.backup
    -Restore immediately from a binary backup file the internal Mnesia database. -This will consume a lot of memory if you have a large database, -so better use install_fallback. -
    install_fallback ejabberd.backup
    -The binary backup file is installed as fallback: -it will be used to restore the database at the next ejabberd start. -This means that, after running this command, you have to restart ejabberd. -This command requires less memory than restore. -
    dump ejabberd.dump
    -Dump internal Mnesia database to a text file dump. -
    load ejabberd.dump
    -Restore immediately from a text file dump. -This is not recommended for big databases, as it will consume much time, -memory and processor. In that case it’s preferable to use backup and install_fallback. -
    import_piefxis, export_piefxis, export_piefxis_host
    -These options can be used to migrate accounts -using XEP-0227 formatted XML files -from/to other Jabber/XMPP servers -or move users of a vhost to another ejabberd installation. -See also ejabberd migration kit. -
    import_file, import_dir
    -These options can be used to migrate accounts -using jabberd1.4 formatted XML files. -from other Jabber/XMPP servers -There exist tutorials to -migrate from other software to ejabberd. -
    delete_expired_messages
    This option can be used to delete old messages -in offline storage. This might be useful when the number of offline messages -is very high. -
    delete_old_messages days
    Delete offline messages older than the given days. -
    register user host password
    Register an account in that domain with the given password. -
    unregister user host
    Unregister the given account. -

    -

    4.2.2  Restrict Execution with AccessCommands

    The frontends can be configured to restrict access to certain commands. -In that case, authentication information must be provided. -In each frontend the AccessCommands option is defined -in a different place. But in all cases the option syntax is the same: -

    AccessCommands = [ {Access, CommandNames, Arguments}, ...]
    -Access = atom()
    -CommandNames = all | [CommandName]
    -CommandName = atom()
    -Arguments = [ {ArgumentName, ArgumentValue}, ...]
    -ArgumentName = atom()
    -ArgumentValue = any()
    -

    The default value is to not define any restriction: []. -The authentication information is provided when executing a command, -and is Username, Hostname and Password of a local XMPP account -that has permission to execute the corresponding command. -This means that the account must be registered in the local ejabberd, -because the information will be verified. -It is possible to provide the plaintext password or its MD5 sum.

    When one or several access restrictions are defined and the -authentication information is provided, -each restriction is verified until one matches completely: -the account matches the Access rule, -the command name is listed in CommandNames, -and the provided arguments do not contradict Arguments.

    As an example to understand the syntax, let’s suppose those options: -

    {hosts, ["example.org"]}.
    -{acl, bots, {user, "robot1", "example.org"}}.
    -{access, commaccess, [{allow, bots}]}.
    -

    This list of access restrictions allows only robot1@example.org to execute all commands: -

    [{commaccess, all, []}]
    -

    See another list of restrictions (the corresponding ACL and ACCESS are not shown): -

    [
    - %% This bot can execute all commands:
    - {bot, all, []},
    - %% This bot can only execute the command 'dump'. No argument restriction:
    - {bot_backups, [dump], []}
    - %% This bot can execute all commands,
    - %% but if a 'host' argument is provided, it must be "example.org":
    - {bot_all_example, all, [{host, "example.org"}]},
    - %% This bot can only execute the command 'register',
    - %% and if argument 'host' is provided, it must be "example.org":
    - {bot_reg_example, [register], [{host, "example.org"}]},
    - %% This bot can execute the commands 'register' and 'unregister',
    - %% if argument host is provided, it must be "test.org":
    - {_bot_reg_test, [register, unregister], [{host, "test.org"}]}
    -]
    -

    -

    4.3  Web Admin

    -

    The ejabberd Web Admin allows to administer most of ejabberd using a web browser.

    This feature is enabled by default: -a ejabberd_http listener with the option web_admin (see -section 3.1.3) is included in the listening ports. Then you can open -http://server:port/admin/ in your favourite web browser. You -will be asked to enter the username (the full Jabber ID) and password -of an ejabberd user with administrator rights. After authentication -you will see a page similar to figure 4.1.


    - -webadmmain.png - - -
    -
    Figure 4.1: Top page from the Web Admin
    - -

    -Here you can edit access restrictions, manage users, create backups, -manage the database, enable/disable ports listened for, view server -statistics,…

    The access rule configure determines what accounts can access the Web Admin and modify it. -The access rule webadmin_view is to grant only view access: those accounts can browse the Web Admin with read-only access.

    Example configurations: -

    • -You can serve the Web Admin on the same port as the -HTTP Polling interface. In this example -you should point your web browser to http://example.org:5280/admin/ to -administer all virtual hosts or to -http://example.org:5280/admin/server/example.com/ to administer only -the virtual host example.com. Before you get access to the Web Admin -you need to enter as username, the JID and password from a registered user -that is allowed to configure ejabberd. In this example you can enter as -username ‘admin@example.net’ to administer all virtual hosts (first -URL). If you log in with ‘admin@example.com’ on
      - http://example.org:5280/admin/server/example.com/ you can only -administer the virtual host example.com. -The account ‘reviewer@example.com’ can browse that vhost in read-only mode. -
      {acl, admins, {user, "admin", "example.net"}}.
      -{host_config, "example.com", [{acl, admins, {user, "admin", "example.com"}}]}.
      -{host_config, "example.com", [{acl, viewers, {user, "reviewer", "example.com"}}]}.
      -
      -{access, configure, [{allow, admins}]}.
      -{access, webadmin_view, [{allow, viewers}]}.
      -
      -{hosts, ["example.org"]}.
      -
      -{listen,
      - [
      -  ...
      -  {5280, ejabberd_http, [http_poll, web_admin]},
      -  ...
      - ]}.
      -
    • For security reasons, you can serve the Web Admin on a secured -connection, on a port differing from the HTTP Polling interface, and bind it -to the internal LAN IP. The Web Admin will be accessible by pointing your -web browser to https://192.168.1.1:5282/admin/: -
      -{hosts, ["example.org"]}.
      -
      -{listen,
      - [
      -  ...
      -  {5280, ejabberd_http, [
      -                         http_poll
      -                        ]},
      -  {{5282, "192.168.1.1"}, ejabberd_http, [
      -                                          web_admin,
      -                                          tls, {certfile, "/usr/local/etc/server.pem"}
      -                                         ]},
      -  ...
      - ]}.
      -

    Certain pages in the ejabberd Web Admin contain a link to a related -section in the ejabberd Installation and Operation Guide. -In order to view such links, a copy in HTML format of the Guide must -be installed in the system. -The file is searched by default in -"/share/doc/ejabberd/guide.html". -The directory of the documentation can be specified in -the environment variable EJABBERD_DOC_PATH. -See section 4.1.2.

    -

    4.4  Ad-hoc Commands

    If you enable mod_configure and mod_adhoc, -you can perform several administrative tasks in ejabberd -with a XMPP client. -The client must support Ad-Hoc Commands (XEP-0050), -and you must login in the XMPP server with -an account with proper privileges.

    -

    4.5  Change Computer Hostname

    ejabberd uses the distributed Mnesia database. -Being distributed, Mnesia enforces consistency of its file, -so it stores the name of the Erlang node in it (see section 5.4). -The name of an Erlang node includes the hostname of the computer. -So, the name of the Erlang node changes -if you change the name of the machine in which ejabberd runs, -or when you move ejabberd to a different machine.

    You have two ways to use the old Mnesia database in an ejabberd with new node name: -put the old node name in ejabberdctl.cfg, -or convert the database to the new node name.

    Those example steps will backup, convert and load the Mnesia database. -You need to have either the old Mnesia spool dir or a backup of Mnesia. -If you already have a backup file of the old database, you can go directly to step 5. -You also need to know the old node name and the new node name. -If you don’t know them, look for them by executing ejabberdctl -or in the ejabberd log files.

    Before starting, setup some variables: -

    OLDNODE=ejabberd@oldmachine
    -NEWNODE=ejabberd@newmachine
    -OLDFILE=/tmp/old.backup
    -NEWFILE=/tmp/new.backup
    -
    1. -Start ejabberd enforcing the old node name: -
      ejabberdctl --node $OLDNODE start
      -
    2. Generate a backup file: -
      ejabberdctl --node $OLDNODE backup $OLDFILE
      -
    3. Stop the old node: -
      ejabberdctl --node $OLDNODE stop
      -
    4. Make sure there aren’t files in the Mnesia spool dir. For example: -
      mkdir /var/lib/ejabberd/oldfiles
      -mv /var/lib/ejabberd/*.* /var/lib/ejabberd/oldfiles/
      -
    5. Start ejabberd. There isn’t any need to specify the node name anymore: -
      ejabberdctl start
      -
    6. Convert the backup to new node name: -
      ejabberdctl mnesia_change_nodename $OLDNODE $NEWNODE $OLDFILE $NEWFILE
      -
    7. Install the backup file as a fallback: -
      ejabberdctl install_fallback $NEWFILE
      -
    8. Stop ejabberd: -
      ejabberdctl stop
      -
      You may see an error message in the log files, it’s normal, so don’t worry: -
      Mnesia(ejabberd@newmachine):
      -** ERROR ** (ignoring core)
      -** FATAL ** A fallback is installed and Mnesia must be restarted.
      -  Forcing shutdown after mnesia_down from ejabberd@newmachine...
      -
    9. Now you can finally start ejabberd: -
      ejabberdctl start
      -
    10. Check that the information of the old database is available: accounts, rosters... -After you finish, remember to delete the temporary backup files from public directories. -

    -

    Chapter 5  Securing ejabberd

    -

    5.1  Firewall Settings

    -

    You need to take the following TCP ports in mind when configuring your firewall: -


    - - - - - - -
    PortDescription
    5222Standard port for Jabber/XMPP client connections, plain or STARTTLS.
    5223Standard port for Jabber client connections using the old SSL method.
    5269Standard port for Jabber/XMPP server connections.
    4369EPMD (section 5.2) listens for Erlang node name requests.
    port rangeUsed for connections between Erlang nodes. This range is configurable (see section 5.2).
    -

    -

    5.2  epmd

    epmd (Erlang Port Mapper Daemon) -is a small name server included in Erlang/OTP -and used by Erlang programs when establishing distributed Erlang communications. -ejabberd needs epmd to use ejabberdctl and also when clustering ejabberd nodes. -This small program is automatically started by Erlang, and is never stopped. -If ejabberd is stopped, and there aren’t any other Erlang programs -running in the system, you can safely stop epmd if you want.

    ejabberd runs inside an Erlang node. -To communicate with ejabberd, the script ejabberdctl starts a new Erlang node -and connects to the Erlang node that holds ejabberd. -In order for this communication to work, -epmd must be running and listening for name requests in the port 4369. -You should block the port 4369 in the firewall in such a way that -only the programs in your machine can access it.

    If you build a cluster of several ejabberd instances, -each ejabberd instance is called an ejabberd node. -Those ejabberd nodes use a special Erlang communication method to -build the cluster, and EPMD is again needed listening in the port 4369. -So, if you plan to build a cluster of ejabberd nodes -you must open the port 4369 for the machines involved in the cluster. -Remember to block the port so Internet doesn’t have access to it.

    Once an Erlang node solved the node name of another Erlang node using EPMD and port 4369, -the nodes communicate directly. -The ports used in this case by default are random, -but can be configured in the file ejabberdctl.cfg. -The Erlang command-line parameter used internally is, for example: -

    erl ... -kernel inet_dist_listen_min 4370 inet_dist_listen_max 4375
    -

    -

    5.3  Erlang Cookie

    The Erlang cookie is a string with numbers and letters. -An Erlang node reads the cookie at startup from the command-line parameter -setcookie. -If not indicated, the cookie is read from the cookie file $HOME/.erlang.cookie. -If this file does not exist, it is created immediately with a random cookie. -Two Erlang nodes communicate only if they have the same cookie. -Setting a cookie on the Erlang node allows you to structure your Erlang network -and define which nodes are allowed to connect to which.

    Thanks to Erlang cookies, you can prevent access to the Erlang node by mistake, -for example when there are several Erlang nodes running different programs in the same machine.

    Setting a secret cookie is a simple method -to difficult unauthorized access to your Erlang node. -However, the cookie system is not ultimately effective -to prevent unauthorized access or intrusion to an Erlang node. -The communication between Erlang nodes are not encrypted, -so the cookie could be read sniffing the traffic on the network. -The recommended way to secure the Erlang node is to block the port 4369.

    -

    5.4  Erlang Node Name

    An Erlang node may have a node name. -The name can be short (if indicated with the command-line parameter -sname) -or long (if indicated with the parameter -name). -Starting an Erlang node with -sname limits the communication between Erlang nodes to the LAN.

    Using the option -sname instead of -name is a simple method -to difficult unauthorized access to your Erlang node. -However, it is not ultimately effective to prevent access to the Erlang node, -because it may be possible to fake the fact that you are on another network -using a modified version of Erlang epmd. -The recommended way to secure the Erlang node is to block the port 4369.

    -

    5.5  Securing Sensitive Files

    ejabberd stores sensitive data in the file system either in plain text or binary files. -The file system permissions should be set to only allow the proper user to read, -write and execute those files and directories.

    -ejabberd configuration file: /etc/ejabberd/ejabberd.cfg
    -Contains the JID of administrators -and passwords of external components. -The backup files probably contain also this information, -so it is preferable to secure the whole /etc/ejabberd/ directory. -
    ejabberd service log: /var/log/ejabberd/ejabberd.log
    -Contains IP addresses of clients. -If the loglevel is set to 5, it contains whole conversations and passwords. -If a logrotate system is used, there may be several log files with similar information, -so it is preferable to secure the whole /var/log/ejabberd/ directory. -
    Mnesia database spool files in /var/lib/ejabberd/
    -The files store binary data, but some parts are still readable. -The files are generated by Mnesia and their permissions cannot be set directly, -so it is preferable to secure the whole /var/lib/ejabberd/ directory. -
    Erlang cookie file: /var/lib/ejabberd/.erlang.cookie
    -See section 5.3. -

    -

    Chapter 6  Clustering

    -

    -

    6.1  How it Works

    -

    A XMPP domain is served by one or more ejabberd nodes. These nodes can -be run on different machines that are connected via a network. They all -must have the ability to connect to port 4369 of all another nodes, and must -have the same magic cookie (see Erlang/OTP documentation, in other words the -file ~ejabberd/.erlang.cookie must be the same on all nodes). This is -needed because all nodes exchange information about connected users, s2s -connections, registered services, etc…

    Each ejabberd node has the following modules: -

    • -router, -
    • local router, -
    • session manager, -
    • s2s manager. -

    -

    6.1.1  Router

    -

    This module is the main router of XMPP packets on each node. It -routes them based on their destination’s domains. It uses a global -routing table. The domain of the packet’s destination is searched in the -routing table, and if it is found, the packet is routed to the -appropriate process. If not, it is sent to the s2s manager.

    -

    6.1.2  Local Router

    -

    This module routes packets which have a destination domain equal to -one of this server’s host names. If the destination JID has a non-empty user -part, it is routed to the session manager, otherwise it is processed depending -on its content.

    -

    6.1.3  Session Manager

    -

    This module routes packets to local users. It looks up to which user -resource a packet must be sent via a presence table. Then the packet is -either routed to the appropriate c2s process, or stored in offline -storage, or bounced back.

    -

    6.1.4  s2s Manager

    -

    This module routes packets to other XMPP servers. First, it -checks if an opened s2s connection from the domain of the packet’s -source to the domain of the packet’s destination exists. If that is the case, -the s2s manager routes the packet to the process -serving this connection, otherwise a new connection is opened.

    -

    6.2  Clustering Setup

    -

    Suppose you already configured ejabberd on one machine named (first), -and you need to setup another one to make an ejabberd cluster. Then do -following steps:

    1. -Copy ~ejabberd/.erlang.cookie file from first to -second.

      (alt) You can also add ‘-setcookie content_of_.erlang.cookie’ -option to all ‘erl’ commands below.

    2. On second run the following command as the ejabberd daemon user, -in the working directory of ejabberd:
      erl -sname ejabberd \
      -    -mnesia dir '"/var/lib/ejabberd/"' \
      -    -mnesia extra_db_nodes "['ejabberd@first']" \
      -    -s mnesia
      -

      This will start Mnesia serving the same database as ejabberd@first. -You can check this by running the command ‘mnesia:info().’. You -should see a lot of remote tables and a line like the following:

      Note: the Mnesia directory may be different in your system. -To know where does ejabberd expect Mnesia to be installed by default, -call 4.1 without options and it will show some help, -including the Mnesia database spool dir.

      running db nodes   = [ejabberd@first, ejabberd@second]
      -
    3. Now run the following in the same ‘erl’ session:
      mnesia:change_table_copy_type(schema, node(), disc_copies).
      -

      This will create local disc storage for the database.

      (alt) Change storage type of the scheme table to ‘RAM and disc -copy’ on the second node via the Web Admin.

    4. Now you can add replicas of various tables to this node with -‘mnesia:add_table_copy’ or -‘mnesia:change_table_copy_type’ as above (just replace -‘schema’ with another table name and ‘disc_copies’ -can be replaced with ‘ram_copies’ or -‘disc_only_copies’).

      Which tables to replicate is very dependant on your needs, you can get -some hints from the command ‘mnesia:info().’, by looking at the -size of tables and the default storage type for each table on ’first’.

      Replicating a table makes lookups in this table faster on this node. -Writing, on the other hand, will be slower. And of course if machine with one -of the replicas is down, other replicas will be used.

      Also section 5.3 (Table Fragmentation) of Mnesia User’s Guide can be helpful. -

      (alt) Same as in previous item, but for other tables.

    5. Run ‘init:stop().’ or just ‘q().’ to exit from -the Erlang shell. This probably can take some time if Mnesia has not yet -transfered and processed all data it needed from first.
    6. Now run ejabberd on second with a configuration similar as -on first: you probably do not need to duplicate ‘acl’ -and ‘access’ options because they will be taken from -first; and mod_irc should be -enabled only on one machine in the cluster. -

    You can repeat these steps for other machines supposed to serve this -domain.

    -

    6.3  Service Load-Balancing

    -

    -

    6.3.1  Components Load-Balancing

    -

    6.3.2  Domain Load-Balancing Algorithm

    -

    ejabberd includes an algorithm to load balance the components that are plugged on an ejabberd cluster. It means that you can plug one or several instances of the same component on each ejabberd cluster and that the traffic will be automatically distributed.

    The default distribution algorithm try to deliver to a local instance of a component. If several local instances are available, one instance is chosen randomly. If no instance is available locally, one instance is chosen randomly among the remote component instances.

    If you need a different behaviour, you can change the load balancing behaviour with the option domain_balancing. The syntax of the option is the following: -

    {domain_balancing, "component.example.com", BalancingCriteria}.

    Several balancing criteria are available: -

    • -destination: the full JID of the packet to attribute is used. -
    • source: the full JID of the packet from attribute is used. -
    • bare_destination: the bare JID (without resource) of the packet to attribute is used. -
    • bare_source: the bare JID (without resource) of the packet from attribute is used. -

    If the value corresponding to the criteria is the same, the same component instance in the cluster will be used.

    -

    6.3.3  Load-Balancing Buckets

    -

    When there is a risk of failure for a given component, domain balancing can cause service trouble. If one component is failing the service will not work correctly unless the sessions are rebalanced.

    In this case, it is best to limit the problem to the sessions handled by the failing component. This is what the domain_balancing_component_number option does, making the load balancing algorithm not dynamic, but sticky on a fix number of component instances.

    The syntax is: -

    {domain_balancing_component_number, "component.example.com", Number}.

    -

    Chapter 7  Debugging

    -

    -

    7.1  Log Files

    An ejabberd node writes two log files: -

    - ejabberd.log
    is the ejabberd service log, with the messages reported by ejabberd code -
    erlang.log
    is the Erlang/OTP system log, with the messages reported by Erlang/OTP using SASL (System Architecture Support Libraries) -

    The option loglevel modifies the verbosity of the file ejabberd.log. The syntax is: -

    {loglevel, Level}.

    The possible Level are: -

    - 0
    No ejabberd log at all (not recommended) -
    1
    Critical -
    2
    Error -
    3
    Warning -
    4
    Info -
    5
    Debug -

    -For example, the default configuration is: -

    {loglevel, 4}.
    -

    The log files grow continually, so it is recommended to rotate them periodically. -To rotate the log files, rename the files and then reopen them. -The ejabberdctl command reopen-log -(please refer to section 4.1.1) -reopens the log files, -and also renames the old ones if you didn’t rename them.

    -

    7.2  Debug Console

    The Debug Console is an Erlang shell attached to an already running ejabberd server. -With this Erlang shell, an experienced administrator can perform complex tasks.

    This shell gives complete control over the ejabberd server, -so it is important to use it with extremely care. -There are some simple and safe examples in the article -Interconnecting Erlang Nodes

    To exit the shell, close the window or press the keys: control+c control+c.

    -

    7.3  Watchdog Alerts

    -

    ejabberd includes a watchdog mechanism that may be useful to developers -when troubleshooting a problem related to memory usage. -If a process in the ejabberd server consumes more memory than the configured threshold, -a message is sent to the XMPP accounts defined with the option -watchdog_admins - in the ejabberd configuration file.

    The syntax is: -

    {watchdog_admins, [JID, ...]}.

    The memory consumed is measured in words: -a word on 32-bit architecture is 4 bytes, -and a word on 64-bit architecture is 8 bytes. -The threshold by default is 1000000 words. -This value can be configured with the option watchdog_large_heap, -or in a conversation with the watchdog alert bot.

    The syntax is: -

    {watchdog_large_heap, Number}.

    Example configuration: -

    {watchdog_admins, ["admin2@localhost", "admin2@example.org"]}.
    -{watchdog_large_heap, 30000000}.
    -

    To remove watchdog admins, remove them in the option. -To remove all watchdog admins, set the option with an empty list: -

    {watchdog_admins, []}.
    -

    -

    Appendix A  Internationalization and Localization

    -

    The source code of ejabberd supports localization. -The translators can edit the -gettext .po files -using any capable program (KBabel, Lokalize, Poedit...) or a simple text editor.

    Then gettext -is used to extract, update and export those .po files to the .msg format read by ejabberd. -To perform those management tasks, in the src/ directory execute make translations. -The translatable strings are extracted from source code to generate the file ejabberd.pot. -This file is merged with each .po file to produce updated .po files. -Finally those .po files are exported to .msg files, that have a format easily readable by ejabberd.

    All built-in modules support the xml:lang attribute inside IQ queries. -Figure A.1, for example, shows the reply to the following query: -

    <iq id='5'
    -    to='example.org'
    -    type='get'
    -    xml:lang='ru'>
    -  <query xmlns='http://jabber.org/protocol/disco#items'/>
    -</iq>
    -

    - -discorus.png - - -
    -
    Figure A.1: Service Discovery when xml:lang=’ru’
    - -

    The Web Admin also supports the Accept-Language HTTP header.


    - -webadmmainru.png - - -
    -
    Figure A.2: Web Admin showing a virtual host when the web browser provides the -HTTP header ‘Accept-Language: ru’
    - -

    -

    Appendix B  Release Notes

    -

    Release notes are available from ejabberd Home Page

    -

    Appendix C  Acknowledgements

    Thanks to all people who contributed to this guide: -

    -

    Appendix D  Copyright Information

    Ejabberd Installation and Operation Guide.
    -Copyright © 2003 — 2010 ProcessOne

    This document 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 document 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 document; if not, write to the Free Software Foundation, Inc., 51 Franklin -Street, Fifth Floor, Boston, MA 02110-1301, USA.

    - - - -
    This document was translated from LATEX by -HEVEA.
    - diff --git a/src/configure b/src/configure deleted file mode 100755 index ff51ca020..000000000 --- a/src/configure +++ /dev/null @@ -1,6310 +0,0 @@ -#! /bin/sh -# Guess values for system-dependent variables and create Makefiles. -# Generated by GNU Autoconf 2.67 for ejabberd 2.1.x. -# -# Report bugs to . -# -# -# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, -# 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software -# Foundation, Inc. -# -# -# This configure script is free software; the Free Software Foundation -# gives unlimited permission to copy, distribute and modify it. -## -------------------- ## -## M4sh Initialization. ## -## -------------------- ## - -# Be more Bourne compatible -DUALCASE=1; export DUALCASE # for MKS sh -if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : - emulate sh - NULLCMD=: - # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which - # is contrary to our usage. Disable this feature. - alias -g '${1+"$@"}'='"$@"' - setopt NO_GLOB_SUBST -else - case `(set -o) 2>/dev/null` in #( - *posix*) : - set -o posix ;; #( - *) : - ;; -esac -fi - - -as_nl=' -' -export as_nl -# Printing a long string crashes Solaris 7 /usr/bin/printf. -as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' -as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo -as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo -# Prefer a ksh shell builtin over an external printf program on Solaris, -# but without wasting forks for bash or zsh. -if test -z "$BASH_VERSION$ZSH_VERSION" \ - && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then - as_echo='print -r --' - as_echo_n='print -rn --' -elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then - as_echo='printf %s\n' - as_echo_n='printf %s' -else - if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then - as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' - as_echo_n='/usr/ucb/echo -n' - else - as_echo_body='eval expr "X$1" : "X\\(.*\\)"' - as_echo_n_body='eval - arg=$1; - case $arg in #( - *"$as_nl"*) - expr "X$arg" : "X\\(.*\\)$as_nl"; - arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; - esac; - expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" - ' - export as_echo_n_body - as_echo_n='sh -c $as_echo_n_body as_echo' - fi - export as_echo_body - as_echo='sh -c $as_echo_body as_echo' -fi - -# The user is always right. -if test "${PATH_SEPARATOR+set}" != set; then - PATH_SEPARATOR=: - (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { - (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || - PATH_SEPARATOR=';' - } -fi - - -# IFS -# We need space, tab and new line, in precisely that order. Quoting is -# there to prevent editors from complaining about space-tab. -# (If _AS_PATH_WALK were called with IFS unset, it would disable word -# splitting by setting IFS to empty value.) -IFS=" "" $as_nl" - -# Find who we are. Look in the path if we contain no directory separator. -case $0 in #(( - *[\\/]* ) as_myself=$0 ;; - *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break - done -IFS=$as_save_IFS - - ;; -esac -# We did not find ourselves, most probably we were run as `sh COMMAND' -# in which case we are not to be found in the path. -if test "x$as_myself" = x; then - as_myself=$0 -fi -if test ! -f "$as_myself"; then - $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 - exit 1 -fi - -# Unset variables that we do not need and which cause bugs (e.g. in -# pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" -# suppresses any "Segmentation fault" message there. '((' could -# trigger a bug in pdksh 5.2.14. -for as_var in BASH_ENV ENV MAIL MAILPATH -do eval test x\${$as_var+set} = xset \ - && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : -done -PS1='$ ' -PS2='> ' -PS4='+ ' - -# NLS nuisances. -LC_ALL=C -export LC_ALL -LANGUAGE=C -export LANGUAGE - -# CDPATH. -(unset CDPATH) >/dev/null 2>&1 && unset CDPATH - -if test "x$CONFIG_SHELL" = x; then - as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then : - emulate sh - NULLCMD=: - # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which - # is contrary to our usage. Disable this feature. - alias -g '\${1+\"\$@\"}'='\"\$@\"' - setopt NO_GLOB_SUBST -else - case \`(set -o) 2>/dev/null\` in #( - *posix*) : - set -o posix ;; #( - *) : - ;; -esac -fi -" - as_required="as_fn_return () { (exit \$1); } -as_fn_success () { as_fn_return 0; } -as_fn_failure () { as_fn_return 1; } -as_fn_ret_success () { return 0; } -as_fn_ret_failure () { return 1; } - -exitcode=0 -as_fn_success || { exitcode=1; echo as_fn_success failed.; } -as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; } -as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; } -as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; } -if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then : - -else - exitcode=1; echo positional parameters were not saved. -fi -test x\$exitcode = x0 || exit 1" - as_suggested=" as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO - as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO - eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" && - test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1 -test \$(( 1 + 1 )) = 2 || exit 1" - if (eval "$as_required") 2>/dev/null; then : - as_have_required=yes -else - as_have_required=no -fi - if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then : - -else - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -as_found=false -for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - as_found=: - case $as_dir in #( - /*) - for as_base in sh bash ksh sh5; do - # Try only shells that exist, to save several forks. - as_shell=$as_dir/$as_base - if { test -f "$as_shell" || test -f "$as_shell.exe"; } && - { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then : - CONFIG_SHELL=$as_shell as_have_required=yes - if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then : - break 2 -fi -fi - done;; - esac - as_found=false -done -$as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } && - { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then : - CONFIG_SHELL=$SHELL as_have_required=yes -fi; } -IFS=$as_save_IFS - - - if test "x$CONFIG_SHELL" != x; then : - # We cannot yet assume a decent shell, so we have to provide a - # neutralization value for shells without unset; and this also - # works around shells that cannot unset nonexistent variables. - BASH_ENV=/dev/null - ENV=/dev/null - (unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV - export CONFIG_SHELL - exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"} -fi - - if test x$as_have_required = xno; then : - $as_echo "$0: This script requires a shell more modern than all" - $as_echo "$0: the shells that I found on your system." - if test x${ZSH_VERSION+set} = xset ; then - $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should" - $as_echo "$0: be upgraded to zsh 4.3.4 or later." - else - $as_echo "$0: Please tell bug-autoconf@gnu.org and -$0: ejabberd@process-one.net about your system, including -$0: any error possibly output before this message. Then -$0: install a modern shell, or manually run the script -$0: under such a shell if you do have one." - fi - exit 1 -fi -fi -fi -SHELL=${CONFIG_SHELL-/bin/sh} -export SHELL -# Unset more variables known to interfere with behavior of common tools. -CLICOLOR_FORCE= GREP_OPTIONS= -unset CLICOLOR_FORCE GREP_OPTIONS - -## --------------------- ## -## M4sh Shell Functions. ## -## --------------------- ## -# as_fn_unset VAR -# --------------- -# Portably unset VAR. -as_fn_unset () -{ - { eval $1=; unset $1;} -} -as_unset=as_fn_unset - -# as_fn_set_status STATUS -# ----------------------- -# Set $? to STATUS, without forking. -as_fn_set_status () -{ - return $1 -} # as_fn_set_status - -# as_fn_exit STATUS -# ----------------- -# Exit the shell with STATUS, even in a "trap 0" or "set -e" context. -as_fn_exit () -{ - set +e - as_fn_set_status $1 - exit $1 -} # as_fn_exit - -# as_fn_mkdir_p -# ------------- -# Create "$as_dir" as a directory, including parents if necessary. -as_fn_mkdir_p () -{ - - case $as_dir in #( - -*) as_dir=./$as_dir;; - esac - test -d "$as_dir" || eval $as_mkdir_p || { - as_dirs= - while :; do - case $as_dir in #( - *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( - *) as_qdir=$as_dir;; - esac - as_dirs="'$as_qdir' $as_dirs" - as_dir=`$as_dirname -- "$as_dir" || -$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ - X"$as_dir" : 'X\(//\)[^/]' \| \ - X"$as_dir" : 'X\(//\)$' \| \ - X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || -$as_echo X"$as_dir" | - sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ - s//\1/ - q - } - /^X\(\/\/\)[^/].*/{ - s//\1/ - q - } - /^X\(\/\/\)$/{ - s//\1/ - q - } - /^X\(\/\).*/{ - s//\1/ - q - } - s/.*/./; q'` - test -d "$as_dir" && break - done - test -z "$as_dirs" || eval "mkdir $as_dirs" - } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" - - -} # as_fn_mkdir_p -# as_fn_append VAR VALUE -# ---------------------- -# Append the text in VALUE to the end of the definition contained in VAR. Take -# advantage of any shell optimizations that allow amortized linear growth over -# repeated appends, instead of the typical quadratic growth present in naive -# implementations. -if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : - eval 'as_fn_append () - { - eval $1+=\$2 - }' -else - as_fn_append () - { - eval $1=\$$1\$2 - } -fi # as_fn_append - -# as_fn_arith ARG... -# ------------------ -# Perform arithmetic evaluation on the ARGs, and store the result in the -# global $as_val. Take advantage of shells that can avoid forks. The arguments -# must be portable across $(()) and expr. -if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : - eval 'as_fn_arith () - { - as_val=$(( $* )) - }' -else - as_fn_arith () - { - as_val=`expr "$@" || test $? -eq 1` - } -fi # as_fn_arith - - -# as_fn_error STATUS ERROR [LINENO LOG_FD] -# ---------------------------------------- -# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are -# provided, also output the error to LOG_FD, referencing LINENO. Then exit the -# script with STATUS, using 1 if that was 0. -as_fn_error () -{ - as_status=$1; test $as_status -eq 0 && as_status=1 - if test "$4"; then - as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack - $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 - fi - $as_echo "$as_me: error: $2" >&2 - as_fn_exit $as_status -} # as_fn_error - -if expr a : '\(a\)' >/dev/null 2>&1 && - test "X`expr 00001 : '.*\(...\)'`" = X001; then - as_expr=expr -else - as_expr=false -fi - -if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then - as_basename=basename -else - as_basename=false -fi - -if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then - as_dirname=dirname -else - as_dirname=false -fi - -as_me=`$as_basename -- "$0" || -$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ - X"$0" : 'X\(//\)$' \| \ - X"$0" : 'X\(/\)' \| . 2>/dev/null || -$as_echo X/"$0" | - sed '/^.*\/\([^/][^/]*\)\/*$/{ - s//\1/ - q - } - /^X\/\(\/\/\)$/{ - s//\1/ - q - } - /^X\/\(\/\).*/{ - s//\1/ - q - } - s/.*/./; q'` - -# Avoid depending upon Character Ranges. -as_cr_letters='abcdefghijklmnopqrstuvwxyz' -as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' -as_cr_Letters=$as_cr_letters$as_cr_LETTERS -as_cr_digits='0123456789' -as_cr_alnum=$as_cr_Letters$as_cr_digits - - - as_lineno_1=$LINENO as_lineno_1a=$LINENO - as_lineno_2=$LINENO as_lineno_2a=$LINENO - eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" && - test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || { - # Blame Lee E. McMahon (1931-1989) for sed's syntax. :-) - sed -n ' - p - /[$]LINENO/= - ' <$as_myself | - sed ' - s/[$]LINENO.*/&-/ - t lineno - b - :lineno - N - :loop - s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ - t loop - s/-\n.*// - ' >$as_me.lineno && - chmod +x "$as_me.lineno" || - { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; } - - # Don't try to exec as it changes $[0], causing all sort of problems - # (the dirname of $[0] is not the place where we might find the - # original and so on. Autoconf is especially sensitive to this). - . "./$as_me.lineno" - # Exit status is that of the last command. - exit -} - -ECHO_C= ECHO_N= ECHO_T= -case `echo -n x` in #((((( --n*) - case `echo 'xy\c'` in - *c*) ECHO_T=' ';; # ECHO_T is single tab character. - xy) ECHO_C='\c';; - *) echo `echo ksh88 bug on AIX 6.1` > /dev/null - ECHO_T=' ';; - esac;; -*) - ECHO_N='-n';; -esac - -rm -f conf$$ conf$$.exe conf$$.file -if test -d conf$$.dir; then - rm -f conf$$.dir/conf$$.file -else - rm -f conf$$.dir - mkdir conf$$.dir 2>/dev/null -fi -if (echo >conf$$.file) 2>/dev/null; then - if ln -s conf$$.file conf$$ 2>/dev/null; then - as_ln_s='ln -s' - # ... but there are two gotchas: - # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. - # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. - # In both cases, we have to default to `cp -p'. - ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || - as_ln_s='cp -p' - elif ln conf$$.file conf$$ 2>/dev/null; then - as_ln_s=ln - else - as_ln_s='cp -p' - fi -else - as_ln_s='cp -p' -fi -rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file -rmdir conf$$.dir 2>/dev/null - -if mkdir -p . 2>/dev/null; then - as_mkdir_p='mkdir -p "$as_dir"' -else - test -d ./-p && rmdir ./-p - as_mkdir_p=false -fi - -if test -x / >/dev/null 2>&1; then - as_test_x='test -x' -else - if ls -dL / >/dev/null 2>&1; then - as_ls_L_option=L - else - as_ls_L_option= - fi - as_test_x=' - eval sh -c '\'' - if test -d "$1"; then - test -d "$1/."; - else - case $1 in #( - -*)set "./$1";; - esac; - case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in #(( - ???[sx]*):;;*)false;;esac;fi - '\'' sh - ' -fi -as_executable_p=$as_test_x - -# Sed expression to map a string onto a valid CPP name. -as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" - -# Sed expression to map a string onto a valid variable name. -as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" - - -test -n "$DJDIR" || exec 7<&0 &1 - -# Name of the host. -# hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status, -# so uname gets run too. -ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q` - -# -# Initializations. -# -ac_default_prefix=/usr/local -ac_clean_files= -ac_config_libobj_dir=. -LIBOBJS= -cross_compiling=no -subdirs= -MFLAGS= -MAKEFLAGS= - -# Identity of this package. -PACKAGE_NAME='ejabberd' -PACKAGE_TARNAME='ejabberd' -PACKAGE_VERSION='2.1.x' -PACKAGE_STRING='ejabberd 2.1.x' -PACKAGE_BUGREPORT='ejabberd@process-one.net' -PACKAGE_URL='' - -# Factoring default headers for most tests. -ac_includes_default="\ -#include -#ifdef HAVE_SYS_TYPES_H -# include -#endif -#ifdef HAVE_SYS_STAT_H -# include -#endif -#ifdef STDC_HEADERS -# include -# include -#else -# ifdef HAVE_STDLIB_H -# include -# endif -#endif -#ifdef HAVE_STRING_H -# if !defined STDC_HEADERS && defined HAVE_MEMORY_H -# include -# endif -# include -#endif -#ifdef HAVE_STRINGS_H -# include -#endif -#ifdef HAVE_INTTYPES_H -# include -#endif -#ifdef HAVE_STDINT_H -# include -#endif -#ifdef HAVE_UNISTD_H -# include -#endif" - -ac_default_prefix=/ -ac_subst_vars='LTLIBOBJS -ERLCFLAGS -target_os -target_vendor -target_cpu -target -host_os -host_vendor -host_cpu -host -build_os -build_vendor -build_cpu -build -md2 -INSTALLUSER -SSL_CFLAGS -SSL_LIBS -nif -full_xml -transient_supervisors -db_type -flash_hack -roster_gateway_workaround -hipe -PAM_LIBS -PAM_CFLAGS -make_pam -pam -ZLIB_LIBS -ZLIB_CFLAGS -make_ejabberd_zlib -ejabberd_zlib -make_web -web -make_tls -tls -make_odbc -odbc -make_eldap -eldap -make_mod_pubsub -mod_pubsub -make_mod_proxy65 -mod_proxy65 -make_mod_muc -mod_muc -make_mod_irc -mod_irc -LIBOBJS -EXPAT_LIBS -EXPAT_CFLAGS -EGREP -GREP -CPP -LIBICONV -ERLANG_SSLVER -ERLANG_LIBS -ERLANG_CFLAGS -ERL -ERLC -SET_MAKE -OBJEXT -EXEEXT -ac_ct_CC -CPPFLAGS -LDFLAGS -CFLAGS -CC -target_alias -host_alias -build_alias -LIBS -ECHO_T -ECHO_N -ECHO_C -DEFS -mandir -localedir -libdir -psdir -pdfdir -dvidir -htmldir -infodir -docdir -oldincludedir -includedir -localstatedir -sharedstatedir -sysconfdir -datadir -datarootdir -libexecdir -sbindir -bindir -program_transform_name -prefix -exec_prefix -PACKAGE_URL -PACKAGE_BUGREPORT -PACKAGE_STRING -PACKAGE_VERSION -PACKAGE_TARNAME -PACKAGE_NAME -PATH_SEPARATOR -SHELL' -ac_subst_files='' -ac_user_opts=' -enable_option_checking -with_erlang -with_libiconv_prefix -with_expat -enable_mod_irc -enable_mod_muc -enable_mod_proxy65 -enable_mod_pubsub -enable_eldap -enable_odbc -enable_tls -enable_web -enable_ejabberd_zlib -with_zlib -enable_pam -with_pam -enable_hipe -enable_roster_gateway_workaround -enable_flash_hack -enable_mssql -enable_transient_supervisors -enable_full_xml -enable_nif -with_openssl -enable_user -' - ac_precious_vars='build_alias -host_alias -target_alias -CC -CFLAGS -LDFLAGS -LIBS -CPPFLAGS -CPP -ERLC -ERLCFLAGS' - - -# Initialize some variables set by options. -ac_init_help= -ac_init_version=false -ac_unrecognized_opts= -ac_unrecognized_sep= -# The variables have the same names as the options, with -# dashes changed to underlines. -cache_file=/dev/null -exec_prefix=NONE -no_create= -no_recursion= -prefix=NONE -program_prefix=NONE -program_suffix=NONE -program_transform_name=s,x,x, -silent= -site= -srcdir= -verbose= -x_includes=NONE -x_libraries=NONE - -# Installation directory options. -# These are left unexpanded so users can "make install exec_prefix=/foo" -# and all the variables that are supposed to be based on exec_prefix -# by default will actually change. -# Use braces instead of parens because sh, perl, etc. also accept them. -# (The list follows the same order as the GNU Coding Standards.) -bindir='${exec_prefix}/bin' -sbindir='${exec_prefix}/sbin' -libexecdir='${exec_prefix}/libexec' -datarootdir='${prefix}/share' -datadir='${datarootdir}' -sysconfdir='${prefix}/etc' -sharedstatedir='${prefix}/com' -localstatedir='${prefix}/var' -includedir='${prefix}/include' -oldincludedir='/usr/include' -docdir='${datarootdir}/doc/${PACKAGE_TARNAME}' -infodir='${datarootdir}/info' -htmldir='${docdir}' -dvidir='${docdir}' -pdfdir='${docdir}' -psdir='${docdir}' -libdir='${exec_prefix}/lib' -localedir='${datarootdir}/locale' -mandir='${datarootdir}/man' - -ac_prev= -ac_dashdash= -for ac_option -do - # If the previous option needs an argument, assign it. - if test -n "$ac_prev"; then - eval $ac_prev=\$ac_option - ac_prev= - continue - fi - - case $ac_option in - *=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;; - *=) ac_optarg= ;; - *) ac_optarg=yes ;; - esac - - # Accept the important Cygnus configure options, so we can diagnose typos. - - case $ac_dashdash$ac_option in - --) - ac_dashdash=yes ;; - - -bindir | --bindir | --bindi | --bind | --bin | --bi) - ac_prev=bindir ;; - -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*) - bindir=$ac_optarg ;; - - -build | --build | --buil | --bui | --bu) - ac_prev=build_alias ;; - -build=* | --build=* | --buil=* | --bui=* | --bu=*) - build_alias=$ac_optarg ;; - - -cache-file | --cache-file | --cache-fil | --cache-fi \ - | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c) - ac_prev=cache_file ;; - -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \ - | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*) - cache_file=$ac_optarg ;; - - --config-cache | -C) - cache_file=config.cache ;; - - -datadir | --datadir | --datadi | --datad) - ac_prev=datadir ;; - -datadir=* | --datadir=* | --datadi=* | --datad=*) - datadir=$ac_optarg ;; - - -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \ - | --dataroo | --dataro | --datar) - ac_prev=datarootdir ;; - -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \ - | --dataroot=* | --dataroo=* | --dataro=* | --datar=*) - datarootdir=$ac_optarg ;; - - -disable-* | --disable-*) - ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` - # Reject names that are not valid shell variable names. - expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && - as_fn_error $? "invalid feature name: $ac_useropt" - ac_useropt_orig=$ac_useropt - ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` - case $ac_user_opts in - *" -"enable_$ac_useropt" -"*) ;; - *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig" - ac_unrecognized_sep=', ';; - esac - eval enable_$ac_useropt=no ;; - - -docdir | --docdir | --docdi | --doc | --do) - ac_prev=docdir ;; - -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*) - docdir=$ac_optarg ;; - - -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv) - ac_prev=dvidir ;; - -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*) - dvidir=$ac_optarg ;; - - -enable-* | --enable-*) - ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` - # Reject names that are not valid shell variable names. - expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && - as_fn_error $? "invalid feature name: $ac_useropt" - ac_useropt_orig=$ac_useropt - ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` - case $ac_user_opts in - *" -"enable_$ac_useropt" -"*) ;; - *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig" - ac_unrecognized_sep=', ';; - esac - eval enable_$ac_useropt=\$ac_optarg ;; - - -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ - | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ - | --exec | --exe | --ex) - ac_prev=exec_prefix ;; - -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \ - | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \ - | --exec=* | --exe=* | --ex=*) - exec_prefix=$ac_optarg ;; - - -gas | --gas | --ga | --g) - # Obsolete; use --with-gas. - with_gas=yes ;; - - -help | --help | --hel | --he | -h) - ac_init_help=long ;; - -help=r* | --help=r* | --hel=r* | --he=r* | -hr*) - ac_init_help=recursive ;; - -help=s* | --help=s* | --hel=s* | --he=s* | -hs*) - ac_init_help=short ;; - - -host | --host | --hos | --ho) - ac_prev=host_alias ;; - -host=* | --host=* | --hos=* | --ho=*) - host_alias=$ac_optarg ;; - - -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht) - ac_prev=htmldir ;; - -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \ - | --ht=*) - htmldir=$ac_optarg ;; - - -includedir | --includedir | --includedi | --included | --include \ - | --includ | --inclu | --incl | --inc) - ac_prev=includedir ;; - -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \ - | --includ=* | --inclu=* | --incl=* | --inc=*) - includedir=$ac_optarg ;; - - -infodir | --infodir | --infodi | --infod | --info | --inf) - ac_prev=infodir ;; - -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*) - infodir=$ac_optarg ;; - - -libdir | --libdir | --libdi | --libd) - ac_prev=libdir ;; - -libdir=* | --libdir=* | --libdi=* | --libd=*) - libdir=$ac_optarg ;; - - -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \ - | --libexe | --libex | --libe) - ac_prev=libexecdir ;; - -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \ - | --libexe=* | --libex=* | --libe=*) - libexecdir=$ac_optarg ;; - - -localedir | --localedir | --localedi | --localed | --locale) - ac_prev=localedir ;; - -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*) - localedir=$ac_optarg ;; - - -localstatedir | --localstatedir | --localstatedi | --localstated \ - | --localstate | --localstat | --localsta | --localst | --locals) - ac_prev=localstatedir ;; - -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \ - | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*) - localstatedir=$ac_optarg ;; - - -mandir | --mandir | --mandi | --mand | --man | --ma | --m) - ac_prev=mandir ;; - -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*) - mandir=$ac_optarg ;; - - -nfp | --nfp | --nf) - # Obsolete; use --without-fp. - with_fp=no ;; - - -no-create | --no-create | --no-creat | --no-crea | --no-cre \ - | --no-cr | --no-c | -n) - no_create=yes ;; - - -no-recursion | --no-recursion | --no-recursio | --no-recursi \ - | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) - no_recursion=yes ;; - - -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \ - | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \ - | --oldin | --oldi | --old | --ol | --o) - ac_prev=oldincludedir ;; - -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \ - | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \ - | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*) - oldincludedir=$ac_optarg ;; - - -prefix | --prefix | --prefi | --pref | --pre | --pr | --p) - ac_prev=prefix ;; - -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*) - prefix=$ac_optarg ;; - - -program-prefix | --program-prefix | --program-prefi | --program-pref \ - | --program-pre | --program-pr | --program-p) - ac_prev=program_prefix ;; - -program-prefix=* | --program-prefix=* | --program-prefi=* \ - | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*) - program_prefix=$ac_optarg ;; - - -program-suffix | --program-suffix | --program-suffi | --program-suff \ - | --program-suf | --program-su | --program-s) - ac_prev=program_suffix ;; - -program-suffix=* | --program-suffix=* | --program-suffi=* \ - | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*) - program_suffix=$ac_optarg ;; - - -program-transform-name | --program-transform-name \ - | --program-transform-nam | --program-transform-na \ - | --program-transform-n | --program-transform- \ - | --program-transform | --program-transfor \ - | --program-transfo | --program-transf \ - | --program-trans | --program-tran \ - | --progr-tra | --program-tr | --program-t) - ac_prev=program_transform_name ;; - -program-transform-name=* | --program-transform-name=* \ - | --program-transform-nam=* | --program-transform-na=* \ - | --program-transform-n=* | --program-transform-=* \ - | --program-transform=* | --program-transfor=* \ - | --program-transfo=* | --program-transf=* \ - | --program-trans=* | --program-tran=* \ - | --progr-tra=* | --program-tr=* | --program-t=*) - program_transform_name=$ac_optarg ;; - - -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd) - ac_prev=pdfdir ;; - -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*) - pdfdir=$ac_optarg ;; - - -psdir | --psdir | --psdi | --psd | --ps) - ac_prev=psdir ;; - -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*) - psdir=$ac_optarg ;; - - -q | -quiet | --quiet | --quie | --qui | --qu | --q \ - | -silent | --silent | --silen | --sile | --sil) - silent=yes ;; - - -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) - ac_prev=sbindir ;; - -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ - | --sbi=* | --sb=*) - sbindir=$ac_optarg ;; - - -sharedstatedir | --sharedstatedir | --sharedstatedi \ - | --sharedstated | --sharedstate | --sharedstat | --sharedsta \ - | --sharedst | --shareds | --shared | --share | --shar \ - | --sha | --sh) - ac_prev=sharedstatedir ;; - -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \ - | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \ - | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \ - | --sha=* | --sh=*) - sharedstatedir=$ac_optarg ;; - - -site | --site | --sit) - ac_prev=site ;; - -site=* | --site=* | --sit=*) - site=$ac_optarg ;; - - -srcdir | --srcdir | --srcdi | --srcd | --src | --sr) - ac_prev=srcdir ;; - -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*) - srcdir=$ac_optarg ;; - - -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \ - | --syscon | --sysco | --sysc | --sys | --sy) - ac_prev=sysconfdir ;; - -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \ - | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*) - sysconfdir=$ac_optarg ;; - - -target | --target | --targe | --targ | --tar | --ta | --t) - ac_prev=target_alias ;; - -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*) - target_alias=$ac_optarg ;; - - -v | -verbose | --verbose | --verbos | --verbo | --verb) - verbose=yes ;; - - -version | --version | --versio | --versi | --vers | -V) - ac_init_version=: ;; - - -with-* | --with-*) - ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` - # Reject names that are not valid shell variable names. - expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && - as_fn_error $? "invalid package name: $ac_useropt" - ac_useropt_orig=$ac_useropt - ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` - case $ac_user_opts in - *" -"with_$ac_useropt" -"*) ;; - *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig" - ac_unrecognized_sep=', ';; - esac - eval with_$ac_useropt=\$ac_optarg ;; - - -without-* | --without-*) - ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` - # Reject names that are not valid shell variable names. - expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && - as_fn_error $? "invalid package name: $ac_useropt" - ac_useropt_orig=$ac_useropt - ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` - case $ac_user_opts in - *" -"with_$ac_useropt" -"*) ;; - *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig" - ac_unrecognized_sep=', ';; - esac - eval with_$ac_useropt=no ;; - - --x) - # Obsolete; use --with-x. - with_x=yes ;; - - -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \ - | --x-incl | --x-inc | --x-in | --x-i) - ac_prev=x_includes ;; - -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \ - | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*) - x_includes=$ac_optarg ;; - - -x-libraries | --x-libraries | --x-librarie | --x-librari \ - | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l) - ac_prev=x_libraries ;; - -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \ - | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) - x_libraries=$ac_optarg ;; - - -*) as_fn_error $? "unrecognized option: \`$ac_option' -Try \`$0 --help' for more information" - ;; - - *=*) - ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` - # Reject names that are not valid shell variable names. - case $ac_envvar in #( - '' | [0-9]* | *[!_$as_cr_alnum]* ) - as_fn_error $? "invalid variable name: \`$ac_envvar'" ;; - esac - eval $ac_envvar=\$ac_optarg - export $ac_envvar ;; - - *) - # FIXME: should be removed in autoconf 3.0. - $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2 - expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && - $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2 - : ${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option} - ;; - - esac -done - -if test -n "$ac_prev"; then - ac_option=--`echo $ac_prev | sed 's/_/-/g'` - as_fn_error $? "missing argument to $ac_option" -fi - -if test -n "$ac_unrecognized_opts"; then - case $enable_option_checking in - no) ;; - fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;; - *) $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;; - esac -fi - -# Check all directory arguments for consistency. -for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ - datadir sysconfdir sharedstatedir localstatedir includedir \ - oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ - libdir localedir mandir -do - eval ac_val=\$$ac_var - # Remove trailing slashes. - case $ac_val in - */ ) - ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'` - eval $ac_var=\$ac_val;; - esac - # Be sure to have absolute directory names. - case $ac_val in - [\\/$]* | ?:[\\/]* ) continue;; - NONE | '' ) case $ac_var in *prefix ) continue;; esac;; - esac - as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val" -done - -# There might be people who depend on the old broken behavior: `$host' -# used to hold the argument of --host etc. -# FIXME: To remove some day. -build=$build_alias -host=$host_alias -target=$target_alias - -# FIXME: To remove some day. -if test "x$host_alias" != x; then - if test "x$build_alias" = x; then - cross_compiling=maybe - $as_echo "$as_me: WARNING: if you wanted to set the --build type, don't use --host. - If a cross compiler is detected then cross compile mode will be used" >&2 - elif test "x$build_alias" != "x$host_alias"; then - cross_compiling=yes - fi -fi - -ac_tool_prefix= -test -n "$host_alias" && ac_tool_prefix=$host_alias- - -test "$silent" = yes && exec 6>/dev/null - - -ac_pwd=`pwd` && test -n "$ac_pwd" && -ac_ls_di=`ls -di .` && -ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || - as_fn_error $? "working directory cannot be determined" -test "X$ac_ls_di" = "X$ac_pwd_ls_di" || - as_fn_error $? "pwd does not report name of working directory" - - -# Find the source files, if location was not specified. -if test -z "$srcdir"; then - ac_srcdir_defaulted=yes - # Try the directory containing this script, then the parent directory. - ac_confdir=`$as_dirname -- "$as_myself" || -$as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ - X"$as_myself" : 'X\(//\)[^/]' \| \ - X"$as_myself" : 'X\(//\)$' \| \ - X"$as_myself" : 'X\(/\)' \| . 2>/dev/null || -$as_echo X"$as_myself" | - sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ - s//\1/ - q - } - /^X\(\/\/\)[^/].*/{ - s//\1/ - q - } - /^X\(\/\/\)$/{ - s//\1/ - q - } - /^X\(\/\).*/{ - s//\1/ - q - } - s/.*/./; q'` - srcdir=$ac_confdir - if test ! -r "$srcdir/$ac_unique_file"; then - srcdir=.. - fi -else - ac_srcdir_defaulted=no -fi -if test ! -r "$srcdir/$ac_unique_file"; then - test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." - as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir" -fi -ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" -ac_abs_confdir=`( - cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg" - pwd)` -# When building in place, set srcdir=. -if test "$ac_abs_confdir" = "$ac_pwd"; then - srcdir=. -fi -# Remove unnecessary trailing slashes from srcdir. -# Double slashes in file names in object file debugging info -# mess up M-x gdb in Emacs. -case $srcdir in -*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;; -esac -for ac_var in $ac_precious_vars; do - eval ac_env_${ac_var}_set=\${${ac_var}+set} - eval ac_env_${ac_var}_value=\$${ac_var} - eval ac_cv_env_${ac_var}_set=\${${ac_var}+set} - eval ac_cv_env_${ac_var}_value=\$${ac_var} -done - -# -# Report the --help message. -# -if test "$ac_init_help" = "long"; then - # Omit some internal or obsolete options to make the list less imposing. - # This message is too long to be a string in the A/UX 3.1 sh. - cat <<_ACEOF -\`configure' configures ejabberd 2.1.x to adapt to many kinds of systems. - -Usage: $0 [OPTION]... [VAR=VALUE]... - -To assign environment variables (e.g., CC, CFLAGS...), specify them as -VAR=VALUE. See below for descriptions of some of the useful variables. - -Defaults for the options are specified in brackets. - -Configuration: - -h, --help display this help and exit - --help=short display options specific to this package - --help=recursive display the short help of all the included packages - -V, --version display version information and exit - -q, --quiet, --silent do not print \`checking ...' messages - --cache-file=FILE cache test results in FILE [disabled] - -C, --config-cache alias for \`--cache-file=config.cache' - -n, --no-create do not create output files - --srcdir=DIR find the sources in DIR [configure dir or \`..'] - -Installation directories: - --prefix=PREFIX install architecture-independent files in PREFIX - [$ac_default_prefix] - --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX - [PREFIX] - -By default, \`make install' will install all the files in -\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify -an installation prefix other than \`$ac_default_prefix' using \`--prefix', -for instance \`--prefix=\$HOME'. - -For better control, use the options below. - -Fine tuning of the installation directories: - --bindir=DIR user executables [EPREFIX/bin] - --sbindir=DIR system admin executables [EPREFIX/sbin] - --libexecdir=DIR program executables [EPREFIX/libexec] - --sysconfdir=DIR read-only single-machine data [PREFIX/etc] - --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] - --localstatedir=DIR modifiable single-machine data [PREFIX/var] - --libdir=DIR object code libraries [EPREFIX/lib] - --includedir=DIR C header files [PREFIX/include] - --oldincludedir=DIR C header files for non-gcc [/usr/include] - --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] - --datadir=DIR read-only architecture-independent data [DATAROOTDIR] - --infodir=DIR info documentation [DATAROOTDIR/info] - --localedir=DIR locale-dependent data [DATAROOTDIR/locale] - --mandir=DIR man documentation [DATAROOTDIR/man] - --docdir=DIR documentation root [DATAROOTDIR/doc/ejabberd] - --htmldir=DIR html documentation [DOCDIR] - --dvidir=DIR dvi documentation [DOCDIR] - --pdfdir=DIR pdf documentation [DOCDIR] - --psdir=DIR ps documentation [DOCDIR] -_ACEOF - - cat <<\_ACEOF - -System types: - --build=BUILD configure for building on BUILD [guessed] - --host=HOST cross-compile to build programs to run on HOST [BUILD] - --target=TARGET configure for building compilers for TARGET [HOST] -_ACEOF -fi - -if test -n "$ac_init_help"; then - case $ac_init_help in - short | recursive ) echo "Configuration of ejabberd 2.1.x:";; - esac - cat <<\_ACEOF - -Optional Features: - --disable-option-checking ignore unrecognized --enable/--with options - --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) - --enable-FEATURE[=ARG] include FEATURE [ARG=yes] - --enable-mod_irc enable mod_irc (default: yes) - --enable-mod_muc enable mod_muc (default: yes) - --enable-mod_proxy65 enable mod_proxy65 (default: yes) - --enable-mod_pubsub enable mod_pubsub (default: yes) - --enable-eldap enable eldap (default: yes) - --enable-odbc enable odbc (default: no) - --enable-tls enable tls (default: yes) - --enable-web enable web (default: yes) - --enable-ejabberd_zlib enable ejabberd_zlib (default: yes) - --enable-pam enable pam (default: no) - --enable-hipe compile natively with HiPE, not recommended - (default: no) - --enable-roster-gateway-workaround - turn on workaround for processing gateway - subscriptions (default: no) - --enable-flash-hack support Adobe Flash client XML (default: no) - --enable-mssql use Microsoft SQL Server database (default: no, - requires --enable-odbc) - --enable-transient_supervisors - use Erlang supervision for transient process - (default: yes) - --enable-full-xml use XML features in XMPP stream (ex: CDATA) - (default: no, requires XML compliant clients) - --enable-nif replace some functions with C equivalents. Requires - Erlang R13B04 or higher (default: no) - --enable-user[[[=USER]]] - allow this system user to start ejabberd (default: - no) - -Optional Packages: - --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] - --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no) - --with-erlang=PREFIX path to erlc and erl - --with-libiconv-prefix=PREFIX - prefix where libiconv is installed - --with-expat=PREFIX prefix where EXPAT is installed - --with-zlib=PREFIX prefix where zlib is installed - --with-pam=PREFIX prefix where PAM is installed - --with-openssl=PREFIX prefix where OPENSSL is installed - -Some influential environment variables: - CC C compiler command - CFLAGS C compiler flags - LDFLAGS linker flags, e.g. -L if you have libraries in a - nonstandard directory - LIBS libraries to pass to the linker, e.g. -l - CPPFLAGS (Objective) C/C++ preprocessor flags, e.g. -I if - you have headers in a nonstandard directory - CPP C preprocessor - ERLC Erlang/OTP compiler command [autodetected] - ERLCFLAGS Erlang/OTP compiler flags [none] - -Use these variables to override the choices made by `configure' or to help -it to find libraries and programs with nonstandard names/locations. - -Report bugs to . -_ACEOF -ac_status=$? -fi - -if test "$ac_init_help" = "recursive"; then - # If there are subdirs, report their specific --help. - for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue - test -d "$ac_dir" || - { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } || - continue - ac_builddir=. - -case "$ac_dir" in -.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; -*) - ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` - # A ".." for each directory in $ac_dir_suffix. - ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` - case $ac_top_builddir_sub in - "") ac_top_builddir_sub=. ac_top_build_prefix= ;; - *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; - esac ;; -esac -ac_abs_top_builddir=$ac_pwd -ac_abs_builddir=$ac_pwd$ac_dir_suffix -# for backward compatibility: -ac_top_builddir=$ac_top_build_prefix - -case $srcdir in - .) # We are building in place. - ac_srcdir=. - ac_top_srcdir=$ac_top_builddir_sub - ac_abs_top_srcdir=$ac_pwd ;; - [\\/]* | ?:[\\/]* ) # Absolute name. - ac_srcdir=$srcdir$ac_dir_suffix; - ac_top_srcdir=$srcdir - ac_abs_top_srcdir=$srcdir ;; - *) # Relative name. - ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix - ac_top_srcdir=$ac_top_build_prefix$srcdir - ac_abs_top_srcdir=$ac_pwd/$srcdir ;; -esac -ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix - - cd "$ac_dir" || { ac_status=$?; continue; } - # Check for guested configure. - if test -f "$ac_srcdir/configure.gnu"; then - echo && - $SHELL "$ac_srcdir/configure.gnu" --help=recursive - elif test -f "$ac_srcdir/configure"; then - echo && - $SHELL "$ac_srcdir/configure" --help=recursive - else - $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 - fi || ac_status=$? - cd "$ac_pwd" || { ac_status=$?; break; } - done -fi - -test -n "$ac_init_help" && exit $ac_status -if $ac_init_version; then - cat <<\_ACEOF -ejabberd configure 2.1.x -generated by GNU Autoconf 2.67 - -Copyright (C) 2010 Free Software Foundation, Inc. -This configure script is free software; the Free Software Foundation -gives unlimited permission to copy, distribute and modify it. -_ACEOF - exit -fi - -## ------------------------ ## -## Autoconf initialization. ## -## ------------------------ ## - -# ac_fn_c_try_compile LINENO -# -------------------------- -# Try to compile conftest.$ac_ext, and return whether this succeeded. -ac_fn_c_try_compile () -{ - as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack - rm -f conftest.$ac_objext - if { { ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_compile") 2>conftest.err - ac_status=$? - if test -s conftest.err; then - grep -v '^ *+' conftest.err >conftest.er1 - cat conftest.er1 >&5 - mv -f conftest.er1 conftest.err - fi - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then : - ac_retval=0 -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_retval=1 -fi - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} - as_fn_set_status $ac_retval - -} # ac_fn_c_try_compile - -# ac_fn_c_try_link LINENO -# ----------------------- -# Try to link conftest.$ac_ext, and return whether this succeeded. -ac_fn_c_try_link () -{ - as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack - rm -f conftest.$ac_objext conftest$ac_exeext - if { { ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_link") 2>conftest.err - ac_status=$? - if test -s conftest.err; then - grep -v '^ *+' conftest.err >conftest.er1 - cat conftest.er1 >&5 - mv -f conftest.er1 conftest.err - fi - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && { - test "$cross_compiling" = yes || - $as_test_x conftest$ac_exeext - }; then : - ac_retval=0 -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_retval=1 -fi - # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information - # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would - # interfere with the next link command; also delete a directory that is - # left behind by Apple's compiler. We do this before executing the actions. - rm -rf conftest.dSYM conftest_ipa8_conftest.oo - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} - as_fn_set_status $ac_retval - -} # ac_fn_c_try_link - -# ac_fn_c_try_cpp LINENO -# ---------------------- -# Try to preprocess conftest.$ac_ext, and return whether this succeeded. -ac_fn_c_try_cpp () -{ - as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack - if { { ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err - ac_status=$? - if test -s conftest.err; then - grep -v '^ *+' conftest.err >conftest.er1 - cat conftest.er1 >&5 - mv -f conftest.er1 conftest.err - fi - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; } > conftest.i && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then : - ac_retval=0 -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_retval=1 -fi - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} - as_fn_set_status $ac_retval - -} # ac_fn_c_try_cpp - -# ac_fn_c_check_header_mongrel LINENO HEADER VAR INCLUDES -# ------------------------------------------------------- -# Tests whether HEADER exists, giving a warning if it cannot be compiled using -# the include files in INCLUDES and setting the cache variable VAR -# accordingly. -ac_fn_c_check_header_mongrel () -{ - as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack - if eval "test \"\${$3+set}\"" = set; then : - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 -$as_echo_n "checking for $2... " >&6; } -if eval "test \"\${$3+set}\"" = set; then : - $as_echo_n "(cached) " >&6 -fi -eval ac_res=\$$3 - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 -$as_echo "$ac_res" >&6; } -else - # Is the header compilable? -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5 -$as_echo_n "checking $2 usability... " >&6; } -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -$4 -#include <$2> -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - ac_header_compiler=yes -else - ac_header_compiler=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5 -$as_echo "$ac_header_compiler" >&6; } - -# Is the header present? -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5 -$as_echo_n "checking $2 presence... " >&6; } -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include <$2> -_ACEOF -if ac_fn_c_try_cpp "$LINENO"; then : - ac_header_preproc=yes -else - ac_header_preproc=no -fi -rm -f conftest.err conftest.i conftest.$ac_ext -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5 -$as_echo "$ac_header_preproc" >&6; } - -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in #(( - yes:no: ) - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&5 -$as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&2;} - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 -$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} - ;; - no:yes:* ) - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cannot be compiled" >&5 -$as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;} - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: check for missing prerequisite headers?" >&5 -$as_echo "$as_me: WARNING: $2: check for missing prerequisite headers?" >&2;} - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf documentation" >&5 -$as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;} - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&5 -$as_echo "$as_me: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&2;} - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 -$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} -( $as_echo "## --------------------------------------- ## -## Report this to ejabberd@process-one.net ## -## --------------------------------------- ##" - ) | sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 -$as_echo_n "checking for $2... " >&6; } -if eval "test \"\${$3+set}\"" = set; then : - $as_echo_n "(cached) " >&6 -else - eval "$3=\$ac_header_compiler" -fi -eval ac_res=\$$3 - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 -$as_echo "$ac_res" >&6; } -fi - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} - -} # ac_fn_c_check_header_mongrel - -# ac_fn_c_try_run LINENO -# ---------------------- -# Try to link conftest.$ac_ext, and return whether this succeeded. Assumes -# that executables *can* be run. -ac_fn_c_try_run () -{ - as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack - if { { ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; } && { ac_try='./conftest$ac_exeext' - { { case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; }; }; then : - ac_retval=0 -else - $as_echo "$as_me: program exited with status $ac_status" >&5 - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_retval=$ac_status -fi - rm -rf conftest.dSYM conftest_ipa8_conftest.oo - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} - as_fn_set_status $ac_retval - -} # ac_fn_c_try_run - -# ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES -# ------------------------------------------------------- -# Tests whether HEADER exists and can be compiled using the include files in -# INCLUDES, setting the cache variable VAR accordingly. -ac_fn_c_check_header_compile () -{ - as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 -$as_echo_n "checking for $2... " >&6; } -if eval "test \"\${$3+set}\"" = set; then : - $as_echo_n "(cached) " >&6 -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -$4 -#include <$2> -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - eval "$3=yes" -else - eval "$3=no" -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -eval ac_res=\$$3 - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 -$as_echo "$ac_res" >&6; } - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} - -} # ac_fn_c_check_header_compile - -# ac_fn_erl_try_run LINENO -# ------------------------ -# Try to link conftest.$ac_ext, and return whether this succeeded. Assumes -# that executables *can* be run. -ac_fn_erl_try_run () -{ - as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack - if { { ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; } && { ac_try='./conftest$ac_exeext' - { { case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; }; }; then : - ac_retval=0 -else - $as_echo "$as_me: program exited with status $ac_status" >&5 - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_retval=$ac_status -fi - rm -rf conftest.dSYM conftest_ipa8_conftest.oo - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} - as_fn_set_status $ac_retval - -} # ac_fn_erl_try_run -cat >config.log <<_ACEOF -This file contains any messages produced by compilers while -running configure, to aid debugging if configure makes a mistake. - -It was created by ejabberd $as_me 2.1.x, which was -generated by GNU Autoconf 2.67. Invocation command line was - - $ $0 $@ - -_ACEOF -exec 5>>config.log -{ -cat <<_ASUNAME -## --------- ## -## Platform. ## -## --------- ## - -hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` -uname -m = `(uname -m) 2>/dev/null || echo unknown` -uname -r = `(uname -r) 2>/dev/null || echo unknown` -uname -s = `(uname -s) 2>/dev/null || echo unknown` -uname -v = `(uname -v) 2>/dev/null || echo unknown` - -/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` -/bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` - -/bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` -/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` -/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` -/usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` -/bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` -/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` -/bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` - -_ASUNAME - -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - $as_echo "PATH: $as_dir" - done -IFS=$as_save_IFS - -} >&5 - -cat >&5 <<_ACEOF - - -## ----------- ## -## Core tests. ## -## ----------- ## - -_ACEOF - - -# Keep a trace of the command line. -# Strip out --no-create and --no-recursion so they do not pile up. -# Strip out --silent because we don't want to record it for future runs. -# Also quote any args containing shell meta-characters. -# Make two passes to allow for proper duplicate-argument suppression. -ac_configure_args= -ac_configure_args0= -ac_configure_args1= -ac_must_keep_next=false -for ac_pass in 1 2 -do - for ac_arg - do - case $ac_arg in - -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; - -q | -quiet | --quiet | --quie | --qui | --qu | --q \ - | -silent | --silent | --silen | --sile | --sil) - continue ;; - *\'*) - ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; - esac - case $ac_pass in - 1) as_fn_append ac_configure_args0 " '$ac_arg'" ;; - 2) - as_fn_append ac_configure_args1 " '$ac_arg'" - if test $ac_must_keep_next = true; then - ac_must_keep_next=false # Got value, back to normal. - else - case $ac_arg in - *=* | --config-cache | -C | -disable-* | --disable-* \ - | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ - | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ - | -with-* | --with-* | -without-* | --without-* | --x) - case "$ac_configure_args0 " in - "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; - esac - ;; - -* ) ac_must_keep_next=true ;; - esac - fi - as_fn_append ac_configure_args " '$ac_arg'" - ;; - esac - done -done -{ ac_configure_args0=; unset ac_configure_args0;} -{ ac_configure_args1=; unset ac_configure_args1;} - -# When interrupted or exit'd, cleanup temporary files, and complete -# config.log. We remove comments because anyway the quotes in there -# would cause problems or look ugly. -# WARNING: Use '\'' to represent an apostrophe within the trap. -# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. -trap 'exit_status=$? - # Save into config.log some information that might help in debugging. - { - echo - - $as_echo "## ---------------- ## -## Cache variables. ## -## ---------------- ##" - echo - # The following way of writing the cache mishandles newlines in values, -( - for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do - eval ac_val=\$$ac_var - case $ac_val in #( - *${as_nl}*) - case $ac_var in #( - *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 -$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; - esac - case $ac_var in #( - _ | IFS | as_nl) ;; #( - BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( - *) { eval $ac_var=; unset $ac_var;} ;; - esac ;; - esac - done - (set) 2>&1 | - case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( - *${as_nl}ac_space=\ *) - sed -n \ - "s/'\''/'\''\\\\'\'''\''/g; - s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" - ;; #( - *) - sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" - ;; - esac | - sort -) - echo - - $as_echo "## ----------------- ## -## Output variables. ## -## ----------------- ##" - echo - for ac_var in $ac_subst_vars - do - eval ac_val=\$$ac_var - case $ac_val in - *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; - esac - $as_echo "$ac_var='\''$ac_val'\''" - done | sort - echo - - if test -n "$ac_subst_files"; then - $as_echo "## ------------------- ## -## File substitutions. ## -## ------------------- ##" - echo - for ac_var in $ac_subst_files - do - eval ac_val=\$$ac_var - case $ac_val in - *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; - esac - $as_echo "$ac_var='\''$ac_val'\''" - done | sort - echo - fi - - if test -s confdefs.h; then - $as_echo "## ----------- ## -## confdefs.h. ## -## ----------- ##" - echo - cat confdefs.h - echo - fi - test "$ac_signal" != 0 && - $as_echo "$as_me: caught signal $ac_signal" - $as_echo "$as_me: exit $exit_status" - } >&5 - rm -f core *.core core.conftest.* && - rm -f -r conftest* confdefs* conf$$* $ac_clean_files && - exit $exit_status -' 0 -for ac_signal in 1 2 13 15; do - trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal -done -ac_signal=0 - -# confdefs.h avoids OS command line length limits that DEFS can exceed. -rm -f -r conftest* confdefs.h - -$as_echo "/* confdefs.h */" > confdefs.h - -# Predefined preprocessor variables. - -cat >>confdefs.h <<_ACEOF -#define PACKAGE_NAME "$PACKAGE_NAME" -_ACEOF - -cat >>confdefs.h <<_ACEOF -#define PACKAGE_TARNAME "$PACKAGE_TARNAME" -_ACEOF - -cat >>confdefs.h <<_ACEOF -#define PACKAGE_VERSION "$PACKAGE_VERSION" -_ACEOF - -cat >>confdefs.h <<_ACEOF -#define PACKAGE_STRING "$PACKAGE_STRING" -_ACEOF - -cat >>confdefs.h <<_ACEOF -#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" -_ACEOF - -cat >>confdefs.h <<_ACEOF -#define PACKAGE_URL "$PACKAGE_URL" -_ACEOF - - -# Let the site file select an alternate cache file if it wants to. -# Prefer an explicitly selected file to automatically selected ones. -ac_site_file1=NONE -ac_site_file2=NONE -if test -n "$CONFIG_SITE"; then - # We do not want a PATH search for config.site. - case $CONFIG_SITE in #(( - -*) ac_site_file1=./$CONFIG_SITE;; - */*) ac_site_file1=$CONFIG_SITE;; - *) ac_site_file1=./$CONFIG_SITE;; - esac -elif test "x$prefix" != xNONE; then - ac_site_file1=$prefix/share/config.site - ac_site_file2=$prefix/etc/config.site -else - ac_site_file1=$ac_default_prefix/share/config.site - ac_site_file2=$ac_default_prefix/etc/config.site -fi -for ac_site_file in "$ac_site_file1" "$ac_site_file2" -do - test "x$ac_site_file" = xNONE && continue - if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5 -$as_echo "$as_me: loading site script $ac_site_file" >&6;} - sed 's/^/| /' "$ac_site_file" >&5 - . "$ac_site_file" \ - || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -as_fn_error $? "failed to load site script $ac_site_file -See \`config.log' for more details" "$LINENO" 5 ; } - fi -done - -if test -r "$cache_file"; then - # Some versions of bash will fail to source /dev/null (special files - # actually), so we avoid doing that. DJGPP emulates it as a regular file. - if test /dev/null != "$cache_file" && test -f "$cache_file"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5 -$as_echo "$as_me: loading cache $cache_file" >&6;} - case $cache_file in - [\\/]* | ?:[\\/]* ) . "$cache_file";; - *) . "./$cache_file";; - esac - fi -else - { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5 -$as_echo "$as_me: creating cache $cache_file" >&6;} - >$cache_file -fi - -# Check that the precious variables saved in the cache have kept the same -# value. -ac_cache_corrupted=false -for ac_var in $ac_precious_vars; do - eval ac_old_set=\$ac_cv_env_${ac_var}_set - eval ac_new_set=\$ac_env_${ac_var}_set - eval ac_old_val=\$ac_cv_env_${ac_var}_value - eval ac_new_val=\$ac_env_${ac_var}_value - case $ac_old_set,$ac_new_set in - set,) - { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 -$as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} - ac_cache_corrupted=: ;; - ,set) - { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5 -$as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} - ac_cache_corrupted=: ;; - ,);; - *) - if test "x$ac_old_val" != "x$ac_new_val"; then - # differences in whitespace do not lead to failure. - ac_old_val_w=`echo x $ac_old_val` - ac_new_val_w=`echo x $ac_new_val` - if test "$ac_old_val_w" != "$ac_new_val_w"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5 -$as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} - ac_cache_corrupted=: - else - { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5 -$as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;} - eval $ac_var=\$ac_old_val - fi - { $as_echo "$as_me:${as_lineno-$LINENO}: former value: \`$ac_old_val'" >&5 -$as_echo "$as_me: former value: \`$ac_old_val'" >&2;} - { $as_echo "$as_me:${as_lineno-$LINENO}: current value: \`$ac_new_val'" >&5 -$as_echo "$as_me: current value: \`$ac_new_val'" >&2;} - fi;; - esac - # Pass precious variables to config.status. - if test "$ac_new_set" = set; then - case $ac_new_val in - *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; - *) ac_arg=$ac_var=$ac_new_val ;; - esac - case " $ac_configure_args " in - *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. - *) as_fn_append ac_configure_args " '$ac_arg'" ;; - esac - fi -done -if $ac_cache_corrupted; then - { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} - { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5 -$as_echo "$as_me: error: changes in the environment can compromise the build" >&2;} - as_fn_error $? "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5 -fi -## -------------------- ## -## Main body of script. ## -## -------------------- ## - -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu - - - -# Checks for programs. -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu -if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. -set dummy ${ac_tool_prefix}gcc; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_CC+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_CC="${ac_tool_prefix}gcc" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -CC=$ac_cv_prog_CC -if test -n "$CC"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 -$as_echo "$CC" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - -fi -if test -z "$ac_cv_prog_CC"; then - ac_ct_CC=$CC - # Extract the first word of "gcc", so it can be a program name with args. -set dummy gcc; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_ac_ct_CC+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$ac_ct_CC"; then - ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_ac_ct_CC="gcc" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -ac_ct_CC=$ac_cv_prog_ac_ct_CC -if test -n "$ac_ct_CC"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 -$as_echo "$ac_ct_CC" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - if test "x$ac_ct_CC" = x; then - CC="" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 -$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} -ac_tool_warned=yes ;; -esac - CC=$ac_ct_CC - fi -else - CC="$ac_cv_prog_CC" -fi - -if test -z "$CC"; then - if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. -set dummy ${ac_tool_prefix}cc; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_CC+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_CC="${ac_tool_prefix}cc" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -CC=$ac_cv_prog_CC -if test -n "$CC"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 -$as_echo "$CC" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - - fi -fi -if test -z "$CC"; then - # Extract the first word of "cc", so it can be a program name with args. -set dummy cc; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_CC+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. -else - ac_prog_rejected=no -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then - ac_prog_rejected=yes - continue - fi - ac_cv_prog_CC="cc" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -if test $ac_prog_rejected = yes; then - # We found a bogon in the path, so make sure we never use it. - set dummy $ac_cv_prog_CC - shift - if test $# != 0; then - # We chose a different compiler from the bogus one. - # However, it has the same basename, so the bogon will be chosen - # first if we set CC to just the basename; use the full file name. - shift - ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" - fi -fi -fi -fi -CC=$ac_cv_prog_CC -if test -n "$CC"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 -$as_echo "$CC" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - -fi -if test -z "$CC"; then - if test -n "$ac_tool_prefix"; then - for ac_prog in cl.exe - do - # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. -set dummy $ac_tool_prefix$ac_prog; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_CC+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_CC="$ac_tool_prefix$ac_prog" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -CC=$ac_cv_prog_CC -if test -n "$CC"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 -$as_echo "$CC" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - - test -n "$CC" && break - done -fi -if test -z "$CC"; then - ac_ct_CC=$CC - for ac_prog in cl.exe -do - # Extract the first word of "$ac_prog", so it can be a program name with args. -set dummy $ac_prog; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_ac_ct_CC+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -n "$ac_ct_CC"; then - ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_ac_ct_CC="$ac_prog" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -ac_ct_CC=$ac_cv_prog_ac_ct_CC -if test -n "$ac_ct_CC"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 -$as_echo "$ac_ct_CC" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - - test -n "$ac_ct_CC" && break -done - - if test "x$ac_ct_CC" = x; then - CC="" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 -$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} -ac_tool_warned=yes ;; -esac - CC=$ac_ct_CC - fi -fi - -fi - - -test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -as_fn_error $? "no acceptable C compiler found in \$PATH -See \`config.log' for more details" "$LINENO" 5 ; } - -# Provide some information about the compiler. -$as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5 -set X $ac_compile -ac_compiler=$2 -for ac_option in --version -v -V -qversion; do - { { ac_try="$ac_compiler $ac_option >&5" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_compiler $ac_option >&5") 2>conftest.err - ac_status=$? - if test -s conftest.err; then - sed '10a\ -... rest of stderr output deleted ... - 10q' conftest.err >conftest.er1 - cat conftest.er1 >&5 - fi - rm -f conftest.er1 conftest.err - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; } -done - -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -ac_clean_files_save=$ac_clean_files -ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out" -# Try to create an executable without -o first, disregard a.out. -# It will help us diagnose broken compilers, and finding out an intuition -# of exeext. -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5 -$as_echo_n "checking whether the C compiler works... " >&6; } -ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` - -# The possible output files: -ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*" - -ac_rmfiles= -for ac_file in $ac_files -do - case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; - * ) ac_rmfiles="$ac_rmfiles $ac_file";; - esac -done -rm -f $ac_rmfiles - -if { { ac_try="$ac_link_default" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_link_default") 2>&5 - ac_status=$? - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; }; then : - # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. -# So ignore a value of `no', otherwise this would lead to `EXEEXT = no' -# in a Makefile. We should not override ac_cv_exeext if it was cached, -# so that the user can short-circuit this test for compilers unknown to -# Autoconf. -for ac_file in $ac_files '' -do - test -f "$ac_file" || continue - case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) - ;; - [ab].out ) - # We found the default executable, but exeext='' is most - # certainly right. - break;; - *.* ) - if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no; - then :; else - ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` - fi - # We set ac_cv_exeext here because the later test for it is not - # safe: cross compilers may not add the suffix if given an `-o' - # argument, so we may need to know it at that point already. - # Even if this section looks crufty: it has the advantage of - # actually working. - break;; - * ) - break;; - esac -done -test "$ac_cv_exeext" = no && ac_cv_exeext= - -else - ac_file='' -fi -if test -z "$ac_file"; then : - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -$as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -as_fn_error 77 "C compiler cannot create executables -See \`config.log' for more details" "$LINENO" 5 ; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 -$as_echo "yes" >&6; } -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5 -$as_echo_n "checking for C compiler default output file name... " >&6; } -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5 -$as_echo "$ac_file" >&6; } -ac_exeext=$ac_cv_exeext - -rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out -ac_clean_files=$ac_clean_files_save -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5 -$as_echo_n "checking for suffix of executables... " >&6; } -if { { ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; }; then : - # If both `conftest.exe' and `conftest' are `present' (well, observable) -# catch `conftest.exe'. For instance with Cygwin, `ls conftest' will -# work properly (i.e., refer to `conftest.exe'), while it won't with -# `rm'. -for ac_file in conftest.exe conftest conftest.*; do - test -f "$ac_file" || continue - case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; - *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` - break;; - * ) break;; - esac -done -else - { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -as_fn_error $? "cannot compute suffix of executables: cannot compile and link -See \`config.log' for more details" "$LINENO" 5 ; } -fi -rm -f conftest conftest$ac_cv_exeext -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5 -$as_echo "$ac_cv_exeext" >&6; } - -rm -f conftest.$ac_ext -EXEEXT=$ac_cv_exeext -ac_exeext=$EXEEXT -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include -int -main () -{ -FILE *f = fopen ("conftest.out", "w"); - return ferror (f) || fclose (f) != 0; - - ; - return 0; -} -_ACEOF -ac_clean_files="$ac_clean_files conftest.out" -# Check that the compiler produces executables we can run. If not, either -# the compiler is broken, or we cross compile. -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5 -$as_echo_n "checking whether we are cross compiling... " >&6; } -if test "$cross_compiling" != yes; then - { { ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; } - if { ac_try='./conftest$ac_cv_exeext' - { { case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; }; }; then - cross_compiling=no - else - if test "$cross_compiling" = maybe; then - cross_compiling=yes - else - { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -as_fn_error $? "cannot run C compiled programs. -If you meant to cross compile, use \`--host'. -See \`config.log' for more details" "$LINENO" 5 ; } - fi - fi -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5 -$as_echo "$cross_compiling" >&6; } - -rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out -ac_clean_files=$ac_clean_files_save -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5 -$as_echo_n "checking for suffix of object files... " >&6; } -if test "${ac_cv_objext+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -rm -f conftest.o conftest.obj -if { { ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" -$as_echo "$ac_try_echo"; } >&5 - (eval "$ac_compile") 2>&5 - ac_status=$? - $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 - test $ac_status = 0; }; then : - for ac_file in conftest.o conftest.obj conftest.*; do - test -f "$ac_file" || continue; - case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;; - *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` - break;; - esac -done -else - $as_echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -as_fn_error $? "cannot compute suffix of object files: cannot compile -See \`config.log' for more details" "$LINENO" 5 ; } -fi -rm -f conftest.$ac_cv_objext conftest.$ac_ext -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5 -$as_echo "$ac_cv_objext" >&6; } -OBJEXT=$ac_cv_objext -ac_objext=$OBJEXT -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5 -$as_echo_n "checking whether we are using the GNU C compiler... " >&6; } -if test "${ac_cv_c_compiler_gnu+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ -#ifndef __GNUC__ - choke me -#endif - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - ac_compiler_gnu=yes -else - ac_compiler_gnu=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -ac_cv_c_compiler_gnu=$ac_compiler_gnu - -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5 -$as_echo "$ac_cv_c_compiler_gnu" >&6; } -if test $ac_compiler_gnu = yes; then - GCC=yes -else - GCC= -fi -ac_test_CFLAGS=${CFLAGS+set} -ac_save_CFLAGS=$CFLAGS -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5 -$as_echo_n "checking whether $CC accepts -g... " >&6; } -if test "${ac_cv_prog_cc_g+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - ac_save_c_werror_flag=$ac_c_werror_flag - ac_c_werror_flag=yes - ac_cv_prog_cc_g=no - CFLAGS="-g" - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_prog_cc_g=yes -else - CFLAGS="" - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - -else - ac_c_werror_flag=$ac_save_c_werror_flag - CFLAGS="-g" - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_prog_cc_g=yes -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - ac_c_werror_flag=$ac_save_c_werror_flag -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5 -$as_echo "$ac_cv_prog_cc_g" >&6; } -if test "$ac_test_CFLAGS" = set; then - CFLAGS=$ac_save_CFLAGS -elif test $ac_cv_prog_cc_g = yes; then - if test "$GCC" = yes; then - CFLAGS="-g -O2" - else - CFLAGS="-g" - fi -else - if test "$GCC" = yes; then - CFLAGS="-O2" - else - CFLAGS= - fi -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5 -$as_echo_n "checking for $CC option to accept ISO C89... " >&6; } -if test "${ac_cv_prog_cc_c89+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - ac_cv_prog_cc_c89=no -ac_save_CC=$CC -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include -#include -#include -#include -/* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ -struct buf { int x; }; -FILE * (*rcsopen) (struct buf *, struct stat *, int); -static char *e (p, i) - char **p; - int i; -{ - return p[i]; -} -static char *f (char * (*g) (char **, int), char **p, ...) -{ - char *s; - va_list v; - va_start (v,p); - s = g (p, va_arg (v,int)); - va_end (v); - return s; -} - -/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has - function prototypes and stuff, but not '\xHH' hex character constants. - These don't provoke an error unfortunately, instead are silently treated - as 'x'. The following induces an error, until -std is added to get - proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an - array size at least. It's necessary to write '\x00'==0 to get something - that's true only with -std. */ -int osf4_cc_array ['\x00' == 0 ? 1 : -1]; - -/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters - inside strings and character constants. */ -#define FOO(x) 'x' -int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1]; - -int test (int i, double x); -struct s1 {int (*f) (int a);}; -struct s2 {int (*f) (double a);}; -int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); -int argc; -char **argv; -int -main () -{ -return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; - ; - return 0; -} -_ACEOF -for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \ - -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" -do - CC="$ac_save_CC $ac_arg" - if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_prog_cc_c89=$ac_arg -fi -rm -f core conftest.err conftest.$ac_objext - test "x$ac_cv_prog_cc_c89" != "xno" && break -done -rm -f conftest.$ac_ext -CC=$ac_save_CC - -fi -# AC_CACHE_VAL -case "x$ac_cv_prog_cc_c89" in - x) - { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 -$as_echo "none needed" >&6; } ;; - xno) - { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 -$as_echo "unsupported" >&6; } ;; - *) - CC="$CC $ac_cv_prog_cc_c89" - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5 -$as_echo "$ac_cv_prog_cc_c89" >&6; } ;; -esac -if test "x$ac_cv_prog_cc_c89" != xno; then : - -fi - -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ${MAKE-make} sets \$(MAKE)" >&5 -$as_echo_n "checking whether ${MAKE-make} sets \$(MAKE)... " >&6; } -set x ${MAKE-make} -ac_make=`$as_echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'` -if eval "test \"\${ac_cv_prog_make_${ac_make}_set+set}\"" = set; then : - $as_echo_n "(cached) " >&6 -else - cat >conftest.make <<\_ACEOF -SHELL = /bin/sh -all: - @echo '@@@%%%=$(MAKE)=@@@%%%' -_ACEOF -# GNU make sometimes prints "make[1]: Entering ...", which would confuse us. -case `${MAKE-make} -f conftest.make 2>/dev/null` in - *@@@%%%=?*=@@@%%%*) - eval ac_cv_prog_make_${ac_make}_set=yes;; - *) - eval ac_cv_prog_make_${ac_make}_set=no;; -esac -rm -f conftest.make -fi -if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 -$as_echo "yes" >&6; } - SET_MAKE= -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } - SET_MAKE="MAKE=${MAKE-make}" -fi - - -if test "x$GCC" = "xyes"; then - CFLAGS="$CFLAGS -Wall" -fi - -#locating erlang - -# Check whether --with-erlang was given. -if test "${with_erlang+set}" = set; then : - withval=$with_erlang; -fi - - - if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}erlc", so it can be a program name with args. -set dummy ${ac_tool_prefix}erlc; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_ERLC+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - case $ERLC in - [\\/]* | ?:[\\/]*) - ac_cv_path_ERLC="$ERLC" # Let the user override the test with a path. - ;; - *) - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -as_dummy="$with_erlang:$with_erlang/bin:$PATH" -for as_dir in $as_dummy -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_path_ERLC="$as_dir/$ac_word$ac_exec_ext" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - - ;; -esac -fi -ERLC=$ac_cv_path_ERLC -if test -n "$ERLC"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ERLC" >&5 -$as_echo "$ERLC" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - -fi -if test -z "$ac_cv_path_ERLC"; then - ac_pt_ERLC=$ERLC - # Extract the first word of "erlc", so it can be a program name with args. -set dummy erlc; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_ac_pt_ERLC+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - case $ac_pt_ERLC in - [\\/]* | ?:[\\/]*) - ac_cv_path_ac_pt_ERLC="$ac_pt_ERLC" # Let the user override the test with a path. - ;; - *) - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -as_dummy="$with_erlang:$with_erlang/bin:$PATH" -for as_dir in $as_dummy -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_path_ac_pt_ERLC="$as_dir/$ac_word$ac_exec_ext" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - - ;; -esac -fi -ac_pt_ERLC=$ac_cv_path_ac_pt_ERLC -if test -n "$ac_pt_ERLC"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_ERLC" >&5 -$as_echo "$ac_pt_ERLC" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - if test "x$ac_pt_ERLC" = x; then - ERLC="" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 -$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} -ac_tool_warned=yes ;; -esac - ERLC=$ac_pt_ERLC - fi -else - ERLC="$ac_cv_path_ERLC" -fi - - if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}erl", so it can be a program name with args. -set dummy ${ac_tool_prefix}erl; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_ERL+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - case $ERL in - [\\/]* | ?:[\\/]*) - ac_cv_path_ERL="$ERL" # Let the user override the test with a path. - ;; - *) - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -as_dummy="$with_erlang:$with_erlang/bin:$PATH" -for as_dir in $as_dummy -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_path_ERL="$as_dir/$ac_word$ac_exec_ext" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - - ;; -esac -fi -ERL=$ac_cv_path_ERL -if test -n "$ERL"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ERL" >&5 -$as_echo "$ERL" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - -fi -if test -z "$ac_cv_path_ERL"; then - ac_pt_ERL=$ERL - # Extract the first word of "erl", so it can be a program name with args. -set dummy erl; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_ac_pt_ERL+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - case $ac_pt_ERL in - [\\/]* | ?:[\\/]*) - ac_cv_path_ac_pt_ERL="$ac_pt_ERL" # Let the user override the test with a path. - ;; - *) - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -as_dummy="$with_erlang:$with_erlang/bin:$PATH" -for as_dir in $as_dummy -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_path_ac_pt_ERL="$as_dir/$ac_word$ac_exec_ext" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - - ;; -esac -fi -ac_pt_ERL=$ac_cv_path_ac_pt_ERL -if test -n "$ac_pt_ERL"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_ERL" >&5 -$as_echo "$ac_pt_ERL" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - if test "x$ac_pt_ERL" = x; then - ERL="" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 -$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} -ac_tool_warned=yes ;; -esac - ERL=$ac_pt_ERL - fi -else - ERL="$ac_cv_path_ERL" -fi - - - if test "z$ERLC" = "z" || test "z$ERL" = "z"; then - as_fn_error $? "erlang not found" "$LINENO" 5 - fi - - - cat >>conftest.erl <<_EOF - --module(conftest). --author('alexey@sevcom.net'). - --export([start/0]). - -start() -> - EIDirS = code:lib_dir("erl_interface") ++ "\n", - EILibS = libpath("erl_interface") ++ "\n", - RootDirS = code:root_dir() ++ "\n", - file:write_file("conftest.out", list_to_binary(EIDirS ++ EILibS ++ ssldef() ++ RootDirS)), - halt(). - -ssldef() -> - OTP = (catch erlang:system_info(otp_release)), - if - OTP >= "R14" -> "-DSSL40\n"; - OTP >= "R12" -> "-DSSL39\n"; - true -> "\n" - end. - -%% return physical architecture based on OS/Processor -archname() -> - ArchStr = erlang:system_info(system_architecture), - case os:type() of - {win32, _} -> "windows"; - {unix,UnixName} -> - Specs = string:tokens(ArchStr,"-"), - Cpu = case lists:nth(2,Specs) of - "pc" -> "x86"; - _ -> hd(Specs) - end, - atom_to_list(UnixName) ++ "-" ++ Cpu; - _ -> "generic" - end. - -%% Return arch-based library path or a default value if this directory -%% does not exist -libpath(App) -> - PrivDir = code:priv_dir(App), - ArchDir = archname(), - LibArchDir = filename:join([PrivDir,"lib",ArchDir]), - case file:list_dir(LibArchDir) of - %% Arch lib dir exists: We use it - {ok, _List} -> LibArchDir; - %% Arch lib dir does not exist: Return the default value - %% ({error, enoent}): - _Error -> code:lib_dir("erl_interface") ++ "/lib" - end. - -_EOF - - if ! $ERLC conftest.erl; then - as_fn_error $? "could not compile sample program" "$LINENO" 5 - fi - - if ! $ERL -s conftest -noshell; then - as_fn_error $? "could not run sample program" "$LINENO" 5 - fi - - if ! test -f conftest.out; then - as_fn_error $? "erlang program was not properly executed, (conftest.out was not produced)" "$LINENO" 5 - fi - - # First line - ERLANG_EI_DIR=`cat conftest.out | head -n 1` - # Second line - ERLANG_EI_LIB=`cat conftest.out | head -n 2 | tail -n 1` - # Third line - ERLANG_SSLVER=`cat conftest.out | head -n 3 | tail -n 1` - # End line - ERLANG_DIR=`cat conftest.out | tail -n 1` - - ERLANG_CFLAGS="-I$ERLANG_EI_DIR/include -I$ERLANG_DIR/usr/include" - ERLANG_LIBS="-L$ERLANG_EI_LIB -lerl_interface -lei" - - - - - - - -#locating iconv - - - -# Check whether --with-libiconv-prefix was given. -if test "${with_libiconv_prefix+set}" = set; then : - withval=$with_libiconv_prefix; - for dir in `echo "$withval" | tr : ' '`; do - if test -d $dir/include; then CPPFLAGS="$CPPFLAGS -I$dir/include"; fi - if test -d $dir/include; then CFLAGS="$CFLAGS -I$dir/include"; fi - if test -d $dir/lib; then LDFLAGS="$LDFLAGS -L$dir/lib"; fi - done - -fi - - - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for iconv" >&5 -$as_echo_n "checking for iconv... " >&6; } -if test "${am_cv_func_iconv+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - - am_cv_func_iconv="no, consider installing GNU libiconv" - am_cv_lib_iconv=no - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include -#include -int -main () -{ -iconv_t cd = iconv_open("",""); - iconv(cd,NULL,NULL,NULL,NULL); - iconv_close(cd); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO"; then : - am_cv_func_iconv=yes -fi -rm -f core conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext - if test "$am_cv_func_iconv" != yes; then - am_save_LIBS="$LIBS" - LIBS="$LIBS -liconv" - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include -#include -int -main () -{ -iconv_t cd = iconv_open("",""); - iconv(cd,NULL,NULL,NULL,NULL); - iconv_close(cd); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO"; then : - am_cv_lib_iconv=yes - am_cv_func_iconv=yes -fi -rm -f core conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext - LIBS="$am_save_LIBS" - fi - if test "$am_cv_func_iconv" != yes; then - am_save_LIBS="$LIBS" - am_save_CFLAGS="$CFLAGS" - am_save_LDFLAGS="$LDFLAGS" - LIBS="$LIBS -liconv" - LDFLAGS="$LDFLAGS -L/usr/local/lib" - CFLAGS="$CFLAGS -I/usr/local/include" - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include -#include -int -main () -{ -iconv_t cd = iconv_open("",""); - iconv(cd,NULL,NULL,NULL,NULL); - iconv_close(cd); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO"; then : - am_cv_lib_iconv=yes - am_cv_func_iconv=yes - CPPFLAGS="$CPPFLAGS -I/usr/local/include" -else - LDFLAGS="$am_save_LDFLAGS" - CFLAGS="$am_save_CFLAGS" -fi -rm -f core conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext - LIBS="$am_save_LIBS" - fi - - -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_func_iconv" >&5 -$as_echo "$am_cv_func_iconv" >&6; } - if test "$am_cv_func_iconv" = yes; then - -$as_echo "#define HAVE_ICONV 1" >>confdefs.h - - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for iconv declaration" >&5 -$as_echo_n "checking for iconv declaration... " >&6; } - if test "${am_cv_proto_iconv+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -#include -#include -extern -#ifdef __cplusplus -"C" -#endif -#if defined(__STDC__) || defined(__cplusplus) -size_t iconv (iconv_t cd, char * *inbuf, size_t *inbytesleft, char * *outbuf, size_t *outbytesleft); -#else -size_t iconv(); -#endif - -int -main () -{ - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - am_cv_proto_iconv_arg1="" -else - am_cv_proto_iconv_arg1="const" -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - am_cv_proto_iconv="extern size_t iconv (iconv_t cd, $am_cv_proto_iconv_arg1 char * *inbuf, size_t *inbytesleft, char * *outbuf, size_t *outbytesleft);" -fi - - am_cv_proto_iconv=`echo "$am_cv_proto_iconv" | tr -s ' ' | sed -e 's/( /(/'` - { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${ac_t:- - }$am_cv_proto_iconv" >&5 -$as_echo "${ac_t:- - }$am_cv_proto_iconv" >&6; } - -cat >>confdefs.h <<_ACEOF -#define ICONV_CONST $am_cv_proto_iconv_arg1 -_ACEOF - - fi - LIBICONV= - if test "$am_cv_lib_iconv" = yes; then - LIBICONV="-liconv" - fi - - -#locating libexpat -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5 -$as_echo_n "checking how to run the C preprocessor... " >&6; } -# On Suns, sometimes $CPP names a directory. -if test -n "$CPP" && test -d "$CPP"; then - CPP= -fi -if test -z "$CPP"; then - if test "${ac_cv_prog_CPP+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - # Double quotes because CPP needs to be expanded - for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" - do - ac_preproc_ok=false -for ac_c_preproc_warn_flag in '' yes -do - # Use a header file that comes with gcc, so configuring glibc - # with a fresh cross-compiler works. - # Prefer to if __STDC__ is defined, since - # exists even on freestanding compilers. - # On the NeXT, cc -E runs the code through the compiler's parser, - # not just through cpp. "Syntax error" is here to catch this case. - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#ifdef __STDC__ -# include -#else -# include -#endif - Syntax error -_ACEOF -if ac_fn_c_try_cpp "$LINENO"; then : - -else - # Broken: fails on valid input. -continue -fi -rm -f conftest.err conftest.i conftest.$ac_ext - - # OK, works on sane cases. Now check whether nonexistent headers - # can be detected and how. - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include -_ACEOF -if ac_fn_c_try_cpp "$LINENO"; then : - # Broken: success on invalid input. -continue -else - # Passes both tests. -ac_preproc_ok=: -break -fi -rm -f conftest.err conftest.i conftest.$ac_ext - -done -# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. -rm -f conftest.i conftest.err conftest.$ac_ext -if $ac_preproc_ok; then : - break -fi - - done - ac_cv_prog_CPP=$CPP - -fi - CPP=$ac_cv_prog_CPP -else - ac_cv_prog_CPP=$CPP -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5 -$as_echo "$CPP" >&6; } -ac_preproc_ok=false -for ac_c_preproc_warn_flag in '' yes -do - # Use a header file that comes with gcc, so configuring glibc - # with a fresh cross-compiler works. - # Prefer to if __STDC__ is defined, since - # exists even on freestanding compilers. - # On the NeXT, cc -E runs the code through the compiler's parser, - # not just through cpp. "Syntax error" is here to catch this case. - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#ifdef __STDC__ -# include -#else -# include -#endif - Syntax error -_ACEOF -if ac_fn_c_try_cpp "$LINENO"; then : - -else - # Broken: fails on valid input. -continue -fi -rm -f conftest.err conftest.i conftest.$ac_ext - - # OK, works on sane cases. Now check whether nonexistent headers - # can be detected and how. - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include -_ACEOF -if ac_fn_c_try_cpp "$LINENO"; then : - # Broken: success on invalid input. -continue -else - # Passes both tests. -ac_preproc_ok=: -break -fi -rm -f conftest.err conftest.i conftest.$ac_ext - -done -# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. -rm -f conftest.i conftest.err conftest.$ac_ext -if $ac_preproc_ok; then : - -else - { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -as_fn_error $? "C preprocessor \"$CPP\" fails sanity check -See \`config.log' for more details" "$LINENO" 5 ; } -fi - -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu - - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5 -$as_echo_n "checking for grep that handles long lines and -e... " >&6; } -if test "${ac_cv_path_GREP+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test -z "$GREP"; then - ac_path_GREP_found=false - # Loop through the user's path and test for each of PROGNAME-LIST - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_prog in grep ggrep; do - for ac_exec_ext in '' $ac_executable_extensions; do - ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" - { test -f "$ac_path_GREP" && $as_test_x "$ac_path_GREP"; } || continue -# Check for GNU ac_path_GREP and select it if it is found. - # Check for GNU $ac_path_GREP -case `"$ac_path_GREP" --version 2>&1` in -*GNU*) - ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; -*) - ac_count=0 - $as_echo_n 0123456789 >"conftest.in" - while : - do - cat "conftest.in" "conftest.in" >"conftest.tmp" - mv "conftest.tmp" "conftest.in" - cp "conftest.in" "conftest.nl" - $as_echo 'GREP' >> "conftest.nl" - "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break - diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break - as_fn_arith $ac_count + 1 && ac_count=$as_val - if test $ac_count -gt ${ac_path_GREP_max-0}; then - # Best one so far, save it but keep looking for a better one - ac_cv_path_GREP="$ac_path_GREP" - ac_path_GREP_max=$ac_count - fi - # 10*(2^10) chars as input seems more than enough - test $ac_count -gt 10 && break - done - rm -f conftest.in conftest.tmp conftest.nl conftest.out;; -esac - - $ac_path_GREP_found && break 3 - done - done - done -IFS=$as_save_IFS - if test -z "$ac_cv_path_GREP"; then - as_fn_error $? "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 - fi -else - ac_cv_path_GREP=$GREP -fi - -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5 -$as_echo "$ac_cv_path_GREP" >&6; } - GREP="$ac_cv_path_GREP" - - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5 -$as_echo_n "checking for egrep... " >&6; } -if test "${ac_cv_path_EGREP+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 - then ac_cv_path_EGREP="$GREP -E" - else - if test -z "$EGREP"; then - ac_path_EGREP_found=false - # Loop through the user's path and test for each of PROGNAME-LIST - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_prog in egrep; do - for ac_exec_ext in '' $ac_executable_extensions; do - ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" - { test -f "$ac_path_EGREP" && $as_test_x "$ac_path_EGREP"; } || continue -# Check for GNU ac_path_EGREP and select it if it is found. - # Check for GNU $ac_path_EGREP -case `"$ac_path_EGREP" --version 2>&1` in -*GNU*) - ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; -*) - ac_count=0 - $as_echo_n 0123456789 >"conftest.in" - while : - do - cat "conftest.in" "conftest.in" >"conftest.tmp" - mv "conftest.tmp" "conftest.in" - cp "conftest.in" "conftest.nl" - $as_echo 'EGREP' >> "conftest.nl" - "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break - diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break - as_fn_arith $ac_count + 1 && ac_count=$as_val - if test $ac_count -gt ${ac_path_EGREP_max-0}; then - # Best one so far, save it but keep looking for a better one - ac_cv_path_EGREP="$ac_path_EGREP" - ac_path_EGREP_max=$ac_count - fi - # 10*(2^10) chars as input seems more than enough - test $ac_count -gt 10 && break - done - rm -f conftest.in conftest.tmp conftest.nl conftest.out;; -esac - - $ac_path_EGREP_found && break 3 - done - done - done -IFS=$as_save_IFS - if test -z "$ac_cv_path_EGREP"; then - as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 - fi -else - ac_cv_path_EGREP=$EGREP -fi - - fi -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5 -$as_echo "$ac_cv_path_EGREP" >&6; } - EGREP="$ac_cv_path_EGREP" - - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5 -$as_echo_n "checking for ANSI C header files... " >&6; } -if test "${ac_cv_header_stdc+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include -#include -#include -#include - -int -main () -{ - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_header_stdc=yes -else - ac_cv_header_stdc=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - -if test $ac_cv_header_stdc = yes; then - # SunOS 4.x string.h does not declare mem*, contrary to ANSI. - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include - -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "memchr" >/dev/null 2>&1; then : - -else - ac_cv_header_stdc=no -fi -rm -f conftest* - -fi - -if test $ac_cv_header_stdc = yes; then - # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include - -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "free" >/dev/null 2>&1; then : - -else - ac_cv_header_stdc=no -fi -rm -f conftest* - -fi - -if test $ac_cv_header_stdc = yes; then - # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. - if test "$cross_compiling" = yes; then : - : -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include -#include -#if ((' ' & 0x0FF) == 0x020) -# define ISLOWER(c) ('a' <= (c) && (c) <= 'z') -# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) -#else -# define ISLOWER(c) \ - (('a' <= (c) && (c) <= 'i') \ - || ('j' <= (c) && (c) <= 'r') \ - || ('s' <= (c) && (c) <= 'z')) -# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) -#endif - -#define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) -int -main () -{ - int i; - for (i = 0; i < 256; i++) - if (XOR (islower (i), ISLOWER (i)) - || toupper (i) != TOUPPER (i)) - return 2; - return 0; -} -_ACEOF -if ac_fn_c_try_run "$LINENO"; then : - -else - ac_cv_header_stdc=no -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ - conftest.$ac_objext conftest.beam conftest.$ac_ext -fi - -fi -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5 -$as_echo "$ac_cv_header_stdc" >&6; } -if test $ac_cv_header_stdc = yes; then - -$as_echo "#define STDC_HEADERS 1" >>confdefs.h - -fi - -# On IRIX 5.3, sys/types and inttypes.h are conflicting. -for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ - inttypes.h stdint.h unistd.h -do : - as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` -ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default -" -if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : - cat >>confdefs.h <<_ACEOF -#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 -_ACEOF - -fi - -done - - - -# Check whether --with-expat was given. -if test "${with_expat+set}" = set; then : - withval=$with_expat; -fi - - - EXPAT_CFLAGS= - EXPAT_LIBS= - if test x"$with_expat" != x; then - EXPAT_CFLAGS="-I$with_expat/include" - EXPAT_LIBS="-L$with_expat/lib" - fi - - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for XML_ParserCreate in -lexpat" >&5 -$as_echo_n "checking for XML_ParserCreate in -lexpat... " >&6; } -if test "${ac_cv_lib_expat_XML_ParserCreate+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lexpat "$EXPAT_LIBS" $LIBS" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char XML_ParserCreate (); -int -main () -{ -return XML_ParserCreate (); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO"; then : - ac_cv_lib_expat_XML_ParserCreate=yes -else - ac_cv_lib_expat_XML_ParserCreate=no -fi -rm -f core conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_expat_XML_ParserCreate" >&5 -$as_echo "$ac_cv_lib_expat_XML_ParserCreate" >&6; } -if test "x$ac_cv_lib_expat_XML_ParserCreate" = x""yes; then : - EXPAT_LIBS="$EXPAT_LIBS -lexpat" - expat_found=yes -else - expat_found=no -fi - - if test $expat_found = no; then - as_fn_error $? "Could not find development files of Expat library" "$LINENO" 5 - fi - expat_save_CFLAGS="$CFLAGS" - CFLAGS="$CFLAGS $EXPAT_CFLAGS" - expat_save_CPPFLAGS="$CPPFLAGS" - CPPFLAGS="$CPPFLAGS $EXPAT_CFLAGS" - for ac_header in expat.h -do : - ac_fn_c_check_header_mongrel "$LINENO" "expat.h" "ac_cv_header_expat_h" "$ac_includes_default" -if test "x$ac_cv_header_expat_h" = x""yes; then : - cat >>confdefs.h <<_ACEOF -#define HAVE_EXPAT_H 1 -_ACEOF - -else - expat_found=no -fi - -done - - if test $expat_found = no; then - as_fn_error $? "Could not find expat.h" "$LINENO" 5 - fi - CFLAGS="$expat_save_CFLAGS" - CPPFLAGS="$expat_save_CPPFLAGS" - - - - - -# Checks for typedefs, structures, and compiler characteristics. -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for an ANSI C-conforming const" >&5 -$as_echo_n "checking for an ANSI C-conforming const... " >&6; } -if test "${ac_cv_c_const+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -int -main () -{ -/* FIXME: Include the comments suggested by Paul. */ -#ifndef __cplusplus - /* Ultrix mips cc rejects this. */ - typedef int charset[2]; - const charset cs; - /* SunOS 4.1.1 cc rejects this. */ - char const *const *pcpcc; - char **ppc; - /* NEC SVR4.0.2 mips cc rejects this. */ - struct point {int x, y;}; - static struct point const zero = {0,0}; - /* AIX XL C 1.02.0.0 rejects this. - It does not let you subtract one const X* pointer from another in - an arm of an if-expression whose if-part is not a constant - expression */ - const char *g = "string"; - pcpcc = &g + (g ? g-g : 0); - /* HPUX 7.0 cc rejects these. */ - ++pcpcc; - ppc = (char**) pcpcc; - pcpcc = (char const *const *) ppc; - { /* SCO 3.2v4 cc rejects this. */ - char *t; - char const *s = 0 ? (char *) 0 : (char const *) 0; - - *t++ = 0; - if (s) return 0; - } - { /* Someone thinks the Sun supposedly-ANSI compiler will reject this. */ - int x[] = {25, 17}; - const int *foo = &x[0]; - ++foo; - } - { /* Sun SC1.0 ANSI compiler rejects this -- but not the above. */ - typedef const int *iptr; - iptr p = 0; - ++p; - } - { /* AIX XL C 1.02.0.0 rejects this saying - "k.c", line 2.27: 1506-025 (S) Operand must be a modifiable lvalue. */ - struct s { int j; const int *ap[3]; }; - struct s *b; b->j = 5; - } - { /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */ - const int foo = 10; - if (!foo) return 0; - } - return !cs[0] && !zero.x; -#endif - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_c_const=yes -else - ac_cv_c_const=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_const" >&5 -$as_echo "$ac_cv_c_const" >&6; } -if test $ac_cv_c_const = no; then - -$as_echo "#define const /**/" >>confdefs.h - -fi - - -# Check Erlang headers are installed -#AC_CHECK_HEADER(erl_driver.h,,[AC_MSG_ERROR([cannot find Erlang header files])]) - -# Change default prefix - - -# Checks for library functions. -for ac_header in stdlib.h -do : - ac_fn_c_check_header_mongrel "$LINENO" "stdlib.h" "ac_cv_header_stdlib_h" "$ac_includes_default" -if test "x$ac_cv_header_stdlib_h" = x""yes; then : - cat >>confdefs.h <<_ACEOF -#define HAVE_STDLIB_H 1 -_ACEOF - -fi - -done - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU libc compatible malloc" >&5 -$as_echo_n "checking for GNU libc compatible malloc... " >&6; } -if test "${ac_cv_func_malloc_0_nonnull+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test "$cross_compiling" = yes; then : - ac_cv_func_malloc_0_nonnull=no -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#if defined STDC_HEADERS || defined HAVE_STDLIB_H -# include -#else -char *malloc (); -#endif - -int -main () -{ -return ! malloc (0); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_run "$LINENO"; then : - ac_cv_func_malloc_0_nonnull=yes -else - ac_cv_func_malloc_0_nonnull=no -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ - conftest.$ac_objext conftest.beam conftest.$ac_ext -fi - -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_malloc_0_nonnull" >&5 -$as_echo "$ac_cv_func_malloc_0_nonnull" >&6; } -if test $ac_cv_func_malloc_0_nonnull = yes; then : - -$as_echo "#define HAVE_MALLOC 1" >>confdefs.h - -else - $as_echo "#define HAVE_MALLOC 0" >>confdefs.h - - case " $LIBOBJS " in - *" malloc.$ac_objext "* ) ;; - *) LIBOBJS="$LIBOBJS malloc.$ac_objext" - ;; -esac - - -$as_echo "#define malloc rpl_malloc" >>confdefs.h - -fi - - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5 -$as_echo_n "checking for ANSI C header files... " >&6; } -if test "${ac_cv_header_stdc+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include -#include -#include -#include - -int -main () -{ - - ; - return 0; -} -_ACEOF -if ac_fn_c_try_compile "$LINENO"; then : - ac_cv_header_stdc=yes -else - ac_cv_header_stdc=no -fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - -if test $ac_cv_header_stdc = yes; then - # SunOS 4.x string.h does not declare mem*, contrary to ANSI. - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include - -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "memchr" >/dev/null 2>&1; then : - -else - ac_cv_header_stdc=no -fi -rm -f conftest* - -fi - -if test $ac_cv_header_stdc = yes; then - # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include - -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "free" >/dev/null 2>&1; then : - -else - ac_cv_header_stdc=no -fi -rm -f conftest* - -fi - -if test $ac_cv_header_stdc = yes; then - # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. - if test "$cross_compiling" = yes; then : - : -else - cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ -#include -#include -#if ((' ' & 0x0FF) == 0x020) -# define ISLOWER(c) ('a' <= (c) && (c) <= 'z') -# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) -#else -# define ISLOWER(c) \ - (('a' <= (c) && (c) <= 'i') \ - || ('j' <= (c) && (c) <= 'r') \ - || ('s' <= (c) && (c) <= 'z')) -# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) -#endif - -#define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) -int -main () -{ - int i; - for (i = 0; i < 256; i++) - if (XOR (islower (i), ISLOWER (i)) - || toupper (i) != TOUPPER (i)) - return 2; - return 0; -} -_ACEOF -if ac_fn_c_try_run "$LINENO"; then : - -else - ac_cv_header_stdc=no -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ - conftest.$ac_objext conftest.beam conftest.$ac_ext -fi - -fi -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5 -$as_echo "$ac_cv_header_stdc" >&6; } -if test $ac_cv_header_stdc = yes; then - -$as_echo "#define STDC_HEADERS 1" >>confdefs.h - -fi - - - -mod_irc= -make_mod_irc= -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether build mod_irc" >&5 -$as_echo_n "checking whether build mod_irc... " >&6; } -# Check whether --enable-mod_irc was given. -if test "${enable_mod_irc+set}" = set; then : - enableval=$enable_mod_irc; mr_enable_mod_irc="$enableval" -else - mr_enable_mod_irc=yes -fi - -if test "$mr_enable_mod_irc" = "yes"; then -mod_irc=mod_irc -make_mod_irc=mod_irc/Makefile -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $mr_enable_mod_irc" >&5 -$as_echo "$mr_enable_mod_irc" >&6; } - - - - - -mod_muc= -make_mod_muc= -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether build mod_muc" >&5 -$as_echo_n "checking whether build mod_muc... " >&6; } -# Check whether --enable-mod_muc was given. -if test "${enable_mod_muc+set}" = set; then : - enableval=$enable_mod_muc; mr_enable_mod_muc="$enableval" -else - mr_enable_mod_muc=yes -fi - -if test "$mr_enable_mod_muc" = "yes"; then -mod_muc=mod_muc -make_mod_muc=mod_muc/Makefile -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $mr_enable_mod_muc" >&5 -$as_echo "$mr_enable_mod_muc" >&6; } - - - - - -mod_proxy65= -make_mod_proxy65= -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether build mod_proxy65" >&5 -$as_echo_n "checking whether build mod_proxy65... " >&6; } -# Check whether --enable-mod_proxy65 was given. -if test "${enable_mod_proxy65+set}" = set; then : - enableval=$enable_mod_proxy65; mr_enable_mod_proxy65="$enableval" -else - mr_enable_mod_proxy65=yes -fi - -if test "$mr_enable_mod_proxy65" = "yes"; then -mod_proxy65=mod_proxy65 -make_mod_proxy65=mod_proxy65/Makefile -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $mr_enable_mod_proxy65" >&5 -$as_echo "$mr_enable_mod_proxy65" >&6; } - - - - - -mod_pubsub= -make_mod_pubsub= -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether build mod_pubsub" >&5 -$as_echo_n "checking whether build mod_pubsub... " >&6; } -# Check whether --enable-mod_pubsub was given. -if test "${enable_mod_pubsub+set}" = set; then : - enableval=$enable_mod_pubsub; mr_enable_mod_pubsub="$enableval" -else - mr_enable_mod_pubsub=yes -fi - -if test "$mr_enable_mod_pubsub" = "yes"; then -mod_pubsub=mod_pubsub -make_mod_pubsub=mod_pubsub/Makefile -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $mr_enable_mod_pubsub" >&5 -$as_echo "$mr_enable_mod_pubsub" >&6; } - - - - - -eldap= -make_eldap= -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether build eldap" >&5 -$as_echo_n "checking whether build eldap... " >&6; } -# Check whether --enable-eldap was given. -if test "${enable_eldap+set}" = set; then : - enableval=$enable_eldap; mr_enable_eldap="$enableval" -else - mr_enable_eldap=yes -fi - -if test "$mr_enable_eldap" = "yes"; then -eldap=eldap -make_eldap=eldap/Makefile -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $mr_enable_eldap" >&5 -$as_echo "$mr_enable_eldap" >&6; } - - - - - -odbc= -make_odbc= -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether build odbc" >&5 -$as_echo_n "checking whether build odbc... " >&6; } -# Check whether --enable-odbc was given. -if test "${enable_odbc+set}" = set; then : - enableval=$enable_odbc; mr_enable_odbc="$enableval" -else - mr_enable_odbc=no -fi - -if test "$mr_enable_odbc" = "yes"; then -odbc=odbc -make_odbc=odbc/Makefile -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $mr_enable_odbc" >&5 -$as_echo "$mr_enable_odbc" >&6; } - - - - - -tls= -make_tls= -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether build tls" >&5 -$as_echo_n "checking whether build tls... " >&6; } -# Check whether --enable-tls was given. -if test "${enable_tls+set}" = set; then : - enableval=$enable_tls; mr_enable_tls="$enableval" -else - mr_enable_tls=yes -fi - -if test "$mr_enable_tls" = "yes"; then -tls=tls -make_tls=tls/Makefile -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $mr_enable_tls" >&5 -$as_echo "$mr_enable_tls" >&6; } - - - - - -web= -make_web= -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether build web" >&5 -$as_echo_n "checking whether build web... " >&6; } -# Check whether --enable-web was given. -if test "${enable_web+set}" = set; then : - enableval=$enable_web; mr_enable_web="$enableval" -else - mr_enable_web=yes -fi - -if test "$mr_enable_web" = "yes"; then -web=web -make_web=web/Makefile -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $mr_enable_web" >&5 -$as_echo "$mr_enable_web" >&6; } - - - - - - -ejabberd_zlib= -make_ejabberd_zlib= -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether build ejabberd_zlib" >&5 -$as_echo_n "checking whether build ejabberd_zlib... " >&6; } -# Check whether --enable-ejabberd_zlib was given. -if test "${enable_ejabberd_zlib+set}" = set; then : - enableval=$enable_ejabberd_zlib; mr_enable_ejabberd_zlib="$enableval" -else - mr_enable_ejabberd_zlib=yes -fi - -if test "$mr_enable_ejabberd_zlib" = "yes"; then -ejabberd_zlib=ejabberd_zlib -make_ejabberd_zlib=ejabberd_zlib/Makefile -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $mr_enable_ejabberd_zlib" >&5 -$as_echo "$mr_enable_ejabberd_zlib" >&6; } - - - - -#locating zlib - -# Check whether --with-zlib was given. -if test "${with_zlib+set}" = set; then : - withval=$with_zlib; -fi - - -if test x"$ejabberd_zlib" != x; then - ZLIB_CFLAGS= - ZLIB_LIBS= - if test x"$with_zlib" != x; then - ZLIB_CFLAGS="-I$with_zlib/include" - ZLIB_LIBS="-L$with_zlib/lib" - fi - - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for gzgets in -lz" >&5 -$as_echo_n "checking for gzgets in -lz... " >&6; } -if test "${ac_cv_lib_z_gzgets+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lz "$ZLIB_LIBS" $LIBS" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char gzgets (); -int -main () -{ -return gzgets (); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO"; then : - ac_cv_lib_z_gzgets=yes -else - ac_cv_lib_z_gzgets=no -fi -rm -f core conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_z_gzgets" >&5 -$as_echo "$ac_cv_lib_z_gzgets" >&6; } -if test "x$ac_cv_lib_z_gzgets" = x""yes; then : - ZLIB_LIBS="$ZLIB_LIBS -lz" - zlib_found=yes -else - zlib_found=no -fi - - if test $zlib_found = no; then - as_fn_error $? "Could not find development files of zlib library. Install them or disable \`ejabberd_zlib' with: --disable-ejabberd_zlib" "$LINENO" 5 - fi - zlib_save_CFLAGS="$CFLAGS" - CFLAGS="$CFLAGS $ZLIB_CFLAGS" - zlib_save_CPPFLAGS="$CFLAGS" - CPPFLAGS="$CPPFLAGS $ZLIB_CFLAGS" - for ac_header in zlib.h -do : - ac_fn_c_check_header_mongrel "$LINENO" "zlib.h" "ac_cv_header_zlib_h" "$ac_includes_default" -if test "x$ac_cv_header_zlib_h" = x""yes; then : - cat >>confdefs.h <<_ACEOF -#define HAVE_ZLIB_H 1 -_ACEOF - -else - zlib_found=no -fi - -done - - if test $zlib_found = no; then - as_fn_error $? "Could not find zlib.h. Install it or disable \`ejabberd_zlib' with: --disable-ejabberd_zlib" "$LINENO" 5 - fi - CFLAGS="$zlib_save_CFLAGS" - CPPFLAGS="$zlib_save_CPPFLAGS" - - - -fi - - - -pam= -make_pam= -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether build pam" >&5 -$as_echo_n "checking whether build pam... " >&6; } -# Check whether --enable-pam was given. -if test "${enable_pam+set}" = set; then : - enableval=$enable_pam; mr_enable_pam="$enableval" -else - mr_enable_pam=no -fi - -if test "$mr_enable_pam" = "yes"; then -pam=pam -make_pam=pam/Makefile -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $mr_enable_pam" >&5 -$as_echo "$mr_enable_pam" >&6; } - - - - -#locating PAM - -# Check whether --with-pam was given. -if test "${with_pam+set}" = set; then : - withval=$with_pam; -fi - -if test x"$pam" != x; then - PAM_CFLAGS= - PAM_LIBS= - if test x"$with_pam" != x; then - PAM_CFLAGS="-I$with_pam/include" - PAM_LIBS="-L$with_pam/lib" - fi - - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pam_start in -lpam" >&5 -$as_echo_n "checking for pam_start in -lpam... " >&6; } -if test "${ac_cv_lib_pam_pam_start+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lpam "$PAM_LIBS" $LIBS" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char pam_start (); -int -main () -{ -return pam_start (); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO"; then : - ac_cv_lib_pam_pam_start=yes -else - ac_cv_lib_pam_pam_start=no -fi -rm -f core conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pam_pam_start" >&5 -$as_echo "$ac_cv_lib_pam_pam_start" >&6; } -if test "x$ac_cv_lib_pam_pam_start" = x""yes; then : - PAM_LIBS="$PAM_LIBS -lpam" - pam_found=yes -else - pam_found=no -fi - - if test $pam_found = no; then - as_fn_error $? "Could not find development files of PAM library. Install them or disable \`pam' with: --disable-pam" "$LINENO" 5 - fi - pam_save_CFLAGS="$CFLAGS" - CFLAGS="$CFLAGS $PAM_CFLAGS" - pam_save_CPPFLAGS="$CPPFLAGS" - CPPFLAGS="$CPPFLAGS $PAM_CFLAGS" - for ac_header in security/pam_appl.h -do : - ac_fn_c_check_header_mongrel "$LINENO" "security/pam_appl.h" "ac_cv_header_security_pam_appl_h" "$ac_includes_default" -if test "x$ac_cv_header_security_pam_appl_h" = x""yes; then : - cat >>confdefs.h <<_ACEOF -#define HAVE_SECURITY_PAM_APPL_H 1 -_ACEOF - -else - pam_found=no -fi - -done - - if test $pam_found = no; then - as_fn_error $? "Could not find security/pam_appl.h. Install it or disable \`pam' with: --disable-pam" "$LINENO" 5 - fi - CFLAGS="$pam_save_CFLAGS" - CPPFLAGS="$pam_save_CPPFLAGS" - - - -fi - - -# Check whether --enable-hipe was given. -if test "${enable_hipe+set}" = set; then : - enableval=$enable_hipe; case "${enableval}" in - yes) hipe=true ;; - no) hipe=false ;; - *) as_fn_error $? "bad value ${enableval} for --enable-hipe" "$LINENO" 5 ;; -esac -else - hipe=false -fi - - - -# Check whether --enable-roster_gateway_workaround was given. -if test "${enable_roster_gateway_workaround+set}" = set; then : - enableval=$enable_roster_gateway_workaround; case "${enableval}" in - yes) roster_gateway_workaround=true ;; - no) roster_gateway_workaround=false ;; - *) as_fn_error $? "bad value ${enableval} for --enable-roster-gateway-workaround" "$LINENO" 5 ;; -esac -else - roster_gateway_workaround=false -fi - - - -# Check whether --enable-flash_hack was given. -if test "${enable_flash_hack+set}" = set; then : - enableval=$enable_flash_hack; case "${enableval}" in - yes) flash_hack=true ;; - no) flash_hack=false ;; - *) as_fn_error $? "bad value ${enableval} for --enable-flash-hack" "$LINENO" 5 ;; -esac -else - flash_hack=false -fi - - - -# Check whether --enable-mssql was given. -if test "${enable_mssql+set}" = set; then : - enableval=$enable_mssql; case "${enableval}" in - yes) db_type=mssql ;; - no) db_type=generic ;; - *) as_fn_error $? "bad value ${enableval} for --enable-mssql" "$LINENO" 5 ;; -esac -else - db_type=generic -fi - - - -# Check whether --enable-transient_supervisors was given. -if test "${enable_transient_supervisors+set}" = set; then : - enableval=$enable_transient_supervisors; case "${enableval}" in - yes) transient_supervisors=true ;; - no) transient_supervisors=false ;; - *) as_fn_error $? "bad value ${enableval} for --enable-transient_supervisors" "$LINENO" 5 ;; -esac -else - transient_supervisors=true -fi - - - -# Check whether --enable-full_xml was given. -if test "${enable_full_xml+set}" = set; then : - enableval=$enable_full_xml; case "${enableval}" in - yes) full_xml=true ;; - no) full_xml=false ;; - *) as_fn_error $? "bad value ${enableval} for --enable-full-xml" "$LINENO" 5 ;; -esac -else - full_xml=false -fi - - - -# Check whether --enable-nif was given. -if test "${enable_nif+set}" = set; then : - enableval=$enable_nif; case "${enableval}" in - yes) nif=true ;; - no) nif=false ;; - *) as_fn_error $? "bad value ${enableval} for --enable-nif" "$LINENO" 5 ;; -esac -else - nif=false -fi - - - -ac_config_files="$ac_config_files Makefile $make_mod_irc $make_mod_muc $make_mod_pubsub $make_mod_proxy65 $make_eldap $make_pam $make_web stringprep/Makefile stun/Makefile $make_tls $make_odbc $make_ejabberd_zlib" - -#openssl - -# Check whether --with-openssl was given. -if test "${with_openssl+set}" = set; then : - withval=$with_openssl; -fi - -unset SSL_LIBS; -unset SSL_CFLAGS; -have_openssl=no -if test x"$tls" != x; then - for ssl_prefix in $withval /usr/local/ssl /usr/lib/ssl /usr/ssl /usr/pkg /usr/local /usr; do - printf "looking for openssl in $ssl_prefix...\n" - SSL_CFLAGS="-I$ssl_prefix/include" - SSL_LIBS="-L$ssl_prefix/lib -lcrypto" - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for SSL_new in -lssl" >&5 -$as_echo_n "checking for SSL_new in -lssl... " >&6; } -if test "${ac_cv_lib_ssl_SSL_new+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - ac_check_lib_save_LIBS=$LIBS -LIBS="-lssl $SSL_LIBS $SSL_CFLAGS $LIBS" -cat confdefs.h - <<_ACEOF >conftest.$ac_ext -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char SSL_new (); -int -main () -{ -return SSL_new (); - ; - return 0; -} -_ACEOF -if ac_fn_c_try_link "$LINENO"; then : - ac_cv_lib_ssl_SSL_new=yes -else - ac_cv_lib_ssl_SSL_new=no -fi -rm -f core conftest.err conftest.$ac_objext \ - conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_ssl_SSL_new" >&5 -$as_echo "$ac_cv_lib_ssl_SSL_new" >&6; } -if test "x$ac_cv_lib_ssl_SSL_new" = x""yes; then : - have_openssl=yes -else - have_openssl=no -fi - - if test x"$have_openssl" = xyes; then - save_CPPFLAGS=$CPPFLAGS - CPPFLAGS="-I$ssl_prefix/include $CPPFLAGS" - for ac_header in openssl/ssl.h -do : - ac_fn_c_check_header_mongrel "$LINENO" "openssl/ssl.h" "ac_cv_header_openssl_ssl_h" "$ac_includes_default" -if test "x$ac_cv_header_openssl_ssl_h" = x""yes; then : - cat >>confdefs.h <<_ACEOF -#define HAVE_OPENSSL_SSL_H 1 -_ACEOF - have_openssl_h=yes -fi - -done - - CPPFLAGS=$save_CPPFLAGS - if test x"$have_openssl_h" = xyes; then - have_openssl=yes - printf "openssl found in $ssl_prefix\n"; - SSL_LIBS="-L$ssl_prefix/lib -lssl -lcrypto" - CPPFLAGS="-I$ssl_prefix/include $CPPFLAGS" - SSL_CFLAGS="-DHAVE_SSL" - break - fi - else - # Clear this from the autoconf cache, so in the next pass of - # this loop with different -L arguments, it will test again. - unset ac_cv_lib_ssl_SSL_new - fi - done -if test x${have_openssl} != xyes; then - as_fn_error $? "Could not find development files of OpenSSL library. Install them or disable \`tls' with: --disable-tls" "$LINENO" 5 -fi - - -fi - -# If ssl is kerberized it need krb5.h -# On RedHat and OpenBSD, krb5.h is in an unsual place: -KRB5_INCLUDE="`krb5-config --cflags 2>/dev/null`" -if test -n "$KRB5_INCLUDE" ; then - CPPFLAGS="$CPPFLAGS $KRB5_INCLUDE" -else - # For RedHat For BSD - for D in /usr/kerberos/include /usr/include/kerberos /usr/include/kerberosV - do - if test -d $D ; then - CPPFLAGS="$CPPFLAGS -I$D" - fi - done -fi -ac_fn_c_check_header_mongrel "$LINENO" "krb5.h" "ac_cv_header_krb5_h" "$ac_includes_default" -if test "x$ac_cv_header_krb5_h" = x""yes; then : - -fi - - - -ENABLEUSER="" -# Check whether --enable-user was given. -if test "${enable_user+set}" = set; then : - enableval=$enable_user; case "${enableval}" in - yes) ENABLEUSER=`whoami` ;; - no) ENABLEUSER="" ;; - *) ENABLEUSER=$enableval - esac -fi - -if test "$ENABLEUSER" != ""; then - echo "allow this system user to start ejabberd: $ENABLEUSER" - INSTALLUSER=$ENABLEUSER - -fi - -ac_fn_c_check_header_mongrel "$LINENO" "openssl/md2.h" "ac_cv_header_openssl_md2_h" "$ac_includes_default" -if test "x$ac_cv_header_openssl_md2_h" = x""yes; then : - md2=true -else - md2=false -fi - - - - -ac_aux_dir= -for ac_dir in "$srcdir" "$srcdir/.." "$srcdir/../.."; do - if test -f "$ac_dir/install-sh"; then - ac_aux_dir=$ac_dir - ac_install_sh="$ac_aux_dir/install-sh -c" - break - elif test -f "$ac_dir/install.sh"; then - ac_aux_dir=$ac_dir - ac_install_sh="$ac_aux_dir/install.sh -c" - break - elif test -f "$ac_dir/shtool"; then - ac_aux_dir=$ac_dir - ac_install_sh="$ac_aux_dir/shtool install -c" - break - fi -done -if test -z "$ac_aux_dir"; then - as_fn_error $? "cannot find install-sh, install.sh, or shtool in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" "$LINENO" 5 -fi - -# These three variables are undocumented and unsupported, -# and are intended to be withdrawn in a future Autoconf release. -# They can cause serious problems if a builder's source tree is in a directory -# whose full name contains unusual characters. -ac_config_guess="$SHELL $ac_aux_dir/config.guess" # Please don't use this var. -ac_config_sub="$SHELL $ac_aux_dir/config.sub" # Please don't use this var. -ac_configure="$SHELL $ac_aux_dir/configure" # Please don't use this var. - - -# Make sure we can run config.sub. -$SHELL "$ac_aux_dir/config.sub" sun4 >/dev/null 2>&1 || - as_fn_error $? "cannot run $SHELL $ac_aux_dir/config.sub" "$LINENO" 5 - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking build system type" >&5 -$as_echo_n "checking build system type... " >&6; } -if test "${ac_cv_build+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - ac_build_alias=$build_alias -test "x$ac_build_alias" = x && - ac_build_alias=`$SHELL "$ac_aux_dir/config.guess"` -test "x$ac_build_alias" = x && - as_fn_error $? "cannot guess build type; you must specify one" "$LINENO" 5 -ac_cv_build=`$SHELL "$ac_aux_dir/config.sub" $ac_build_alias` || - as_fn_error $? "$SHELL $ac_aux_dir/config.sub $ac_build_alias failed" "$LINENO" 5 - -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_build" >&5 -$as_echo "$ac_cv_build" >&6; } -case $ac_cv_build in -*-*-*) ;; -*) as_fn_error $? "invalid value of canonical build" "$LINENO" 5 ;; -esac -build=$ac_cv_build -ac_save_IFS=$IFS; IFS='-' -set x $ac_cv_build -shift -build_cpu=$1 -build_vendor=$2 -shift; shift -# Remember, the first character of IFS is used to create $*, -# except with old shells: -build_os=$* -IFS=$ac_save_IFS -case $build_os in *\ *) build_os=`echo "$build_os" | sed 's/ /-/g'`;; esac - - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking host system type" >&5 -$as_echo_n "checking host system type... " >&6; } -if test "${ac_cv_host+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test "x$host_alias" = x; then - ac_cv_host=$ac_cv_build -else - ac_cv_host=`$SHELL "$ac_aux_dir/config.sub" $host_alias` || - as_fn_error $? "$SHELL $ac_aux_dir/config.sub $host_alias failed" "$LINENO" 5 -fi - -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_host" >&5 -$as_echo "$ac_cv_host" >&6; } -case $ac_cv_host in -*-*-*) ;; -*) as_fn_error $? "invalid value of canonical host" "$LINENO" 5 ;; -esac -host=$ac_cv_host -ac_save_IFS=$IFS; IFS='-' -set x $ac_cv_host -shift -host_cpu=$1 -host_vendor=$2 -shift; shift -# Remember, the first character of IFS is used to create $*, -# except with old shells: -host_os=$* -IFS=$ac_save_IFS -case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac - - -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking target system type" >&5 -$as_echo_n "checking target system type... " >&6; } -if test "${ac_cv_target+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - if test "x$target_alias" = x; then - ac_cv_target=$ac_cv_host -else - ac_cv_target=`$SHELL "$ac_aux_dir/config.sub" $target_alias` || - as_fn_error $? "$SHELL $ac_aux_dir/config.sub $target_alias failed" "$LINENO" 5 -fi - -fi -{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_target" >&5 -$as_echo "$ac_cv_target" >&6; } -case $ac_cv_target in -*-*-*) ;; -*) as_fn_error $? "invalid value of canonical target" "$LINENO" 5 ;; -esac -target=$ac_cv_target -ac_save_IFS=$IFS; IFS='-' -set x $ac_cv_target -shift -target_cpu=$1 -target_vendor=$2 -shift; shift -# Remember, the first character of IFS is used to create $*, -# except with old shells: -target_os=$* -IFS=$ac_save_IFS -case $target_os in *\ *) target_os=`echo "$target_os" | sed 's/ /-/g'`;; esac - - -# The aliases save the names the user supplied, while $host etc. -# will get canonicalized. -test -n "$target_alias" && - test "$program_prefix$program_suffix$program_transform_name" = \ - NONENONEs,x,x, && - program_prefix=${target_alias}- - -#AC_DEFINE_UNQUOTED(CPU_VENDOR_OS, "$target") -#AC_SUBST(target_os) - - -case "$target_os" in - *darwin10*) - echo "Target OS is 'Darwin10'" - ac_ext=erl -ac_compile='$ERLC $ERLCFLAGS -b beam conftest.$ac_ext >&5' -ac_link='$ERLC $ERLCFLAGS -b beam conftest.$ac_ext >&5 && echo "#!/bin/sh" > conftest$ac_exeext && $as_echo "\"$ERL\" -run conftest start -run init stop -noshell" >> conftest$ac_exeext && chmod +x conftest$ac_exeext' - - if test -n "$ERLC"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for erlc" >&5 -$as_echo_n "checking for erlc... " >&6; } - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ERLC" >&5 -$as_echo "$ERLC" >&6; } -else - if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}erlc", so it can be a program name with args. -set dummy ${ac_tool_prefix}erlc; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_ERLC+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - case $ERLC in - [\\/]* | ?:[\\/]*) - ac_cv_path_ERLC="$ERLC" # Let the user override the test with a path. - ;; - *) - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_path_ERLC="$as_dir/$ac_word$ac_exec_ext" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - - ;; -esac -fi -ERLC=$ac_cv_path_ERLC -if test -n "$ERLC"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ERLC" >&5 -$as_echo "$ERLC" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - -fi -if test -z "$ac_cv_path_ERLC"; then - ac_pt_ERLC=$ERLC - # Extract the first word of "erlc", so it can be a program name with args. -set dummy erlc; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_ac_pt_ERLC+set}" = set; then : - $as_echo_n "(cached) " >&6 -else - case $ac_pt_ERLC in - [\\/]* | ?:[\\/]*) - ac_cv_path_ac_pt_ERLC="$ac_pt_ERLC" # Let the user override the test with a path. - ;; - *) - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_path_ac_pt_ERLC="$as_dir/$ac_word$ac_exec_ext" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - - ;; -esac -fi -ac_pt_ERLC=$ac_cv_path_ac_pt_ERLC -if test -n "$ac_pt_ERLC"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_ERLC" >&5 -$as_echo "$ac_pt_ERLC" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - if test "x$ac_pt_ERLC" = x; then - ERLC="" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 -$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} -ac_tool_warned=yes ;; -esac - ERLC=$ac_pt_ERLC - fi -else - ERLC="$ac_cv_path_ERLC" -fi - -fi - - -if test "$cross_compiling" = yes; then : - { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} -as_fn_error $? "cannot run test program while cross compiling -See \`config.log' for more details" "$LINENO" 5 ; } -else - cat > conftest.$ac_ext <<_ACEOF --module(conftest). --export([start/0]). - -start() -> - halt(case erlang:system_info(wordsize) of - 8 -> 0; 4 -> 1 end) -. - -_ACEOF -if ac_fn_erl_try_run "$LINENO"; then : - { $as_echo "$as_me:${as_lineno-$LINENO}: found 64-bit Erlang" >&5 -$as_echo "$as_me: found 64-bit Erlang" >&6;} - CBIT=-m64 -else - { $as_echo "$as_me:${as_lineno-$LINENO}: found 32-bit Erlang" >&5 -$as_echo "$as_me: found 32-bit Erlang" >&6;} - CBIT=-m32 -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ - conftest.$ac_objext conftest.beam conftest.$ac_ext -fi - - ;; - *) - echo "Target OS is '$target_os'" - CBIT="" - ;; -esac -CFLAGS="$CFLAGS $CBIT" -LD_SHARED="$LD_SHARED $CBIT" -echo "CBIT is set to '$CBIT'" - -cat >confcache <<\_ACEOF -# This file is a shell script that caches the results of configure -# tests run on this system so they can be shared between configure -# scripts and configure runs, see configure's option --config-cache. -# It is not useful on other systems. If it contains results you don't -# want to keep, you may remove or edit it. -# -# config.status only pays attention to the cache file if you give it -# the --recheck option to rerun configure. -# -# `ac_cv_env_foo' variables (set or unset) will be overridden when -# loading this file, other *unset* `ac_cv_foo' will be assigned the -# following values. - -_ACEOF - -# The following way of writing the cache mishandles newlines in values, -# but we know of no workaround that is simple, portable, and efficient. -# So, we kill variables containing newlines. -# Ultrix sh set writes to stderr and can't be redirected directly, -# and sets the high bit in the cache file unless we assign to the vars. -( - for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do - eval ac_val=\$$ac_var - case $ac_val in #( - *${as_nl}*) - case $ac_var in #( - *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 -$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; - esac - case $ac_var in #( - _ | IFS | as_nl) ;; #( - BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( - *) { eval $ac_var=; unset $ac_var;} ;; - esac ;; - esac - done - - (set) 2>&1 | - case $as_nl`(ac_space=' '; set) 2>&1` in #( - *${as_nl}ac_space=\ *) - # `set' does not quote correctly, so add quotes: double-quote - # substitution turns \\\\ into \\, and sed turns \\ into \. - sed -n \ - "s/'/'\\\\''/g; - s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" - ;; #( - *) - # `set' quotes correctly as required by POSIX, so do not add quotes. - sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" - ;; - esac | - sort -) | - sed ' - /^ac_cv_env_/b end - t clear - :clear - s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/ - t end - s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/ - :end' >>confcache -if diff "$cache_file" confcache >/dev/null 2>&1; then :; else - if test -w "$cache_file"; then - test "x$cache_file" != "x/dev/null" && - { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5 -$as_echo "$as_me: updating cache $cache_file" >&6;} - cat confcache >$cache_file - else - { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5 -$as_echo "$as_me: not updating unwritable cache $cache_file" >&6;} - fi -fi -rm -f confcache - -test "x$prefix" = xNONE && prefix=$ac_default_prefix -# Let make expand exec_prefix. -test "x$exec_prefix" = xNONE && exec_prefix='${prefix}' - -# Transform confdefs.h into DEFS. -# Protect against shell expansion while executing Makefile rules. -# Protect against Makefile macro expansion. -# -# If the first sed substitution is executed (which looks for macros that -# take arguments), then branch to the quote section. Otherwise, -# look for a macro that doesn't take arguments. -ac_script=' -:mline -/\\$/{ - N - s,\\\n,, - b mline -} -t clear -:clear -s/^[ ]*#[ ]*define[ ][ ]*\([^ (][^ (]*([^)]*)\)[ ]*\(.*\)/-D\1=\2/g -t quote -s/^[ ]*#[ ]*define[ ][ ]*\([^ ][^ ]*\)[ ]*\(.*\)/-D\1=\2/g -t quote -b any -:quote -s/[ `~#$^&*(){}\\|;'\''"<>?]/\\&/g -s/\[/\\&/g -s/\]/\\&/g -s/\$/$$/g -H -:any -${ - g - s/^\n// - s/\n/ /g - p -} -' -DEFS=`sed -n "$ac_script" confdefs.h` - - -ac_libobjs= -ac_ltlibobjs= -U= -for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue - # 1. Remove the extension, and $U if already installed. - ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' - ac_i=`$as_echo "$ac_i" | sed "$ac_script"` - # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR - # will be set to the directory where LIBOBJS objects are built. - as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext" - as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo' -done -LIBOBJS=$ac_libobjs - -LTLIBOBJS=$ac_ltlibobjs - - - -: ${CONFIG_STATUS=./config.status} -ac_write_fail=0 -ac_clean_files_save=$ac_clean_files -ac_clean_files="$ac_clean_files $CONFIG_STATUS" -{ $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5 -$as_echo "$as_me: creating $CONFIG_STATUS" >&6;} -as_write_fail=0 -cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1 -#! $SHELL -# Generated by $as_me. -# Run this file to recreate the current configuration. -# Compiler output produced by configure, useful for debugging -# configure, is in config.log if it exists. - -debug=false -ac_cs_recheck=false -ac_cs_silent=false - -SHELL=\${CONFIG_SHELL-$SHELL} -export SHELL -_ASEOF -cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1 -## -------------------- ## -## M4sh Initialization. ## -## -------------------- ## - -# Be more Bourne compatible -DUALCASE=1; export DUALCASE # for MKS sh -if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : - emulate sh - NULLCMD=: - # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which - # is contrary to our usage. Disable this feature. - alias -g '${1+"$@"}'='"$@"' - setopt NO_GLOB_SUBST -else - case `(set -o) 2>/dev/null` in #( - *posix*) : - set -o posix ;; #( - *) : - ;; -esac -fi - - -as_nl=' -' -export as_nl -# Printing a long string crashes Solaris 7 /usr/bin/printf. -as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' -as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo -as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo -# Prefer a ksh shell builtin over an external printf program on Solaris, -# but without wasting forks for bash or zsh. -if test -z "$BASH_VERSION$ZSH_VERSION" \ - && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then - as_echo='print -r --' - as_echo_n='print -rn --' -elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then - as_echo='printf %s\n' - as_echo_n='printf %s' -else - if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then - as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' - as_echo_n='/usr/ucb/echo -n' - else - as_echo_body='eval expr "X$1" : "X\\(.*\\)"' - as_echo_n_body='eval - arg=$1; - case $arg in #( - *"$as_nl"*) - expr "X$arg" : "X\\(.*\\)$as_nl"; - arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; - esac; - expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" - ' - export as_echo_n_body - as_echo_n='sh -c $as_echo_n_body as_echo' - fi - export as_echo_body - as_echo='sh -c $as_echo_body as_echo' -fi - -# The user is always right. -if test "${PATH_SEPARATOR+set}" != set; then - PATH_SEPARATOR=: - (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { - (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || - PATH_SEPARATOR=';' - } -fi - - -# IFS -# We need space, tab and new line, in precisely that order. Quoting is -# there to prevent editors from complaining about space-tab. -# (If _AS_PATH_WALK were called with IFS unset, it would disable word -# splitting by setting IFS to empty value.) -IFS=" "" $as_nl" - -# Find who we are. Look in the path if we contain no directory separator. -case $0 in #(( - *[\\/]* ) as_myself=$0 ;; - *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break - done -IFS=$as_save_IFS - - ;; -esac -# We did not find ourselves, most probably we were run as `sh COMMAND' -# in which case we are not to be found in the path. -if test "x$as_myself" = x; then - as_myself=$0 -fi -if test ! -f "$as_myself"; then - $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 - exit 1 -fi - -# Unset variables that we do not need and which cause bugs (e.g. in -# pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" -# suppresses any "Segmentation fault" message there. '((' could -# trigger a bug in pdksh 5.2.14. -for as_var in BASH_ENV ENV MAIL MAILPATH -do eval test x\${$as_var+set} = xset \ - && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : -done -PS1='$ ' -PS2='> ' -PS4='+ ' - -# NLS nuisances. -LC_ALL=C -export LC_ALL -LANGUAGE=C -export LANGUAGE - -# CDPATH. -(unset CDPATH) >/dev/null 2>&1 && unset CDPATH - - -# as_fn_error STATUS ERROR [LINENO LOG_FD] -# ---------------------------------------- -# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are -# provided, also output the error to LOG_FD, referencing LINENO. Then exit the -# script with STATUS, using 1 if that was 0. -as_fn_error () -{ - as_status=$1; test $as_status -eq 0 && as_status=1 - if test "$4"; then - as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack - $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 - fi - $as_echo "$as_me: error: $2" >&2 - as_fn_exit $as_status -} # as_fn_error - - -# as_fn_set_status STATUS -# ----------------------- -# Set $? to STATUS, without forking. -as_fn_set_status () -{ - return $1 -} # as_fn_set_status - -# as_fn_exit STATUS -# ----------------- -# Exit the shell with STATUS, even in a "trap 0" or "set -e" context. -as_fn_exit () -{ - set +e - as_fn_set_status $1 - exit $1 -} # as_fn_exit - -# as_fn_unset VAR -# --------------- -# Portably unset VAR. -as_fn_unset () -{ - { eval $1=; unset $1;} -} -as_unset=as_fn_unset -# as_fn_append VAR VALUE -# ---------------------- -# Append the text in VALUE to the end of the definition contained in VAR. Take -# advantage of any shell optimizations that allow amortized linear growth over -# repeated appends, instead of the typical quadratic growth present in naive -# implementations. -if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : - eval 'as_fn_append () - { - eval $1+=\$2 - }' -else - as_fn_append () - { - eval $1=\$$1\$2 - } -fi # as_fn_append - -# as_fn_arith ARG... -# ------------------ -# Perform arithmetic evaluation on the ARGs, and store the result in the -# global $as_val. Take advantage of shells that can avoid forks. The arguments -# must be portable across $(()) and expr. -if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : - eval 'as_fn_arith () - { - as_val=$(( $* )) - }' -else - as_fn_arith () - { - as_val=`expr "$@" || test $? -eq 1` - } -fi # as_fn_arith - - -if expr a : '\(a\)' >/dev/null 2>&1 && - test "X`expr 00001 : '.*\(...\)'`" = X001; then - as_expr=expr -else - as_expr=false -fi - -if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then - as_basename=basename -else - as_basename=false -fi - -if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then - as_dirname=dirname -else - as_dirname=false -fi - -as_me=`$as_basename -- "$0" || -$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ - X"$0" : 'X\(//\)$' \| \ - X"$0" : 'X\(/\)' \| . 2>/dev/null || -$as_echo X/"$0" | - sed '/^.*\/\([^/][^/]*\)\/*$/{ - s//\1/ - q - } - /^X\/\(\/\/\)$/{ - s//\1/ - q - } - /^X\/\(\/\).*/{ - s//\1/ - q - } - s/.*/./; q'` - -# Avoid depending upon Character Ranges. -as_cr_letters='abcdefghijklmnopqrstuvwxyz' -as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' -as_cr_Letters=$as_cr_letters$as_cr_LETTERS -as_cr_digits='0123456789' -as_cr_alnum=$as_cr_Letters$as_cr_digits - -ECHO_C= ECHO_N= ECHO_T= -case `echo -n x` in #((((( --n*) - case `echo 'xy\c'` in - *c*) ECHO_T=' ';; # ECHO_T is single tab character. - xy) ECHO_C='\c';; - *) echo `echo ksh88 bug on AIX 6.1` > /dev/null - ECHO_T=' ';; - esac;; -*) - ECHO_N='-n';; -esac - -rm -f conf$$ conf$$.exe conf$$.file -if test -d conf$$.dir; then - rm -f conf$$.dir/conf$$.file -else - rm -f conf$$.dir - mkdir conf$$.dir 2>/dev/null -fi -if (echo >conf$$.file) 2>/dev/null; then - if ln -s conf$$.file conf$$ 2>/dev/null; then - as_ln_s='ln -s' - # ... but there are two gotchas: - # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. - # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. - # In both cases, we have to default to `cp -p'. - ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || - as_ln_s='cp -p' - elif ln conf$$.file conf$$ 2>/dev/null; then - as_ln_s=ln - else - as_ln_s='cp -p' - fi -else - as_ln_s='cp -p' -fi -rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file -rmdir conf$$.dir 2>/dev/null - - -# as_fn_mkdir_p -# ------------- -# Create "$as_dir" as a directory, including parents if necessary. -as_fn_mkdir_p () -{ - - case $as_dir in #( - -*) as_dir=./$as_dir;; - esac - test -d "$as_dir" || eval $as_mkdir_p || { - as_dirs= - while :; do - case $as_dir in #( - *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( - *) as_qdir=$as_dir;; - esac - as_dirs="'$as_qdir' $as_dirs" - as_dir=`$as_dirname -- "$as_dir" || -$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ - X"$as_dir" : 'X\(//\)[^/]' \| \ - X"$as_dir" : 'X\(//\)$' \| \ - X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || -$as_echo X"$as_dir" | - sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ - s//\1/ - q - } - /^X\(\/\/\)[^/].*/{ - s//\1/ - q - } - /^X\(\/\/\)$/{ - s//\1/ - q - } - /^X\(\/\).*/{ - s//\1/ - q - } - s/.*/./; q'` - test -d "$as_dir" && break - done - test -z "$as_dirs" || eval "mkdir $as_dirs" - } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" - - -} # as_fn_mkdir_p -if mkdir -p . 2>/dev/null; then - as_mkdir_p='mkdir -p "$as_dir"' -else - test -d ./-p && rmdir ./-p - as_mkdir_p=false -fi - -if test -x / >/dev/null 2>&1; then - as_test_x='test -x' -else - if ls -dL / >/dev/null 2>&1; then - as_ls_L_option=L - else - as_ls_L_option= - fi - as_test_x=' - eval sh -c '\'' - if test -d "$1"; then - test -d "$1/."; - else - case $1 in #( - -*)set "./$1";; - esac; - case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in #(( - ???[sx]*):;;*)false;;esac;fi - '\'' sh - ' -fi -as_executable_p=$as_test_x - -# Sed expression to map a string onto a valid CPP name. -as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" - -# Sed expression to map a string onto a valid variable name. -as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" - - -exec 6>&1 -## ----------------------------------- ## -## Main body of $CONFIG_STATUS script. ## -## ----------------------------------- ## -_ASEOF -test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1 - -cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 -# Save the log message, to keep $0 and so on meaningful, and to -# report actual input values of CONFIG_FILES etc. instead of their -# values after options handling. -ac_log=" -This file was extended by ejabberd $as_me 2.1.x, which was -generated by GNU Autoconf 2.67. Invocation command line was - - CONFIG_FILES = $CONFIG_FILES - CONFIG_HEADERS = $CONFIG_HEADERS - CONFIG_LINKS = $CONFIG_LINKS - CONFIG_COMMANDS = $CONFIG_COMMANDS - $ $0 $@ - -on `(hostname || uname -n) 2>/dev/null | sed 1q` -" - -_ACEOF - -case $ac_config_files in *" -"*) set x $ac_config_files; shift; ac_config_files=$*;; -esac - - - -cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 -# Files that config.status was made for. -config_files="$ac_config_files" - -_ACEOF - -cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 -ac_cs_usage="\ -\`$as_me' instantiates files and other configuration actions -from templates according to the current configuration. Unless the files -and actions are specified as TAGs, all are instantiated by default. - -Usage: $0 [OPTION]... [TAG]... - - -h, --help print this help, then exit - -V, --version print version number and configuration settings, then exit - --config print configuration, then exit - -q, --quiet, --silent - do not print progress messages - -d, --debug don't remove temporary files - --recheck update $as_me by reconfiguring in the same conditions - --file=FILE[:TEMPLATE] - instantiate the configuration file FILE - -Configuration files: -$config_files - -Report bugs to ." - -_ACEOF -cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 -ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`" -ac_cs_version="\\ -ejabberd config.status 2.1.x -configured by $0, generated by GNU Autoconf 2.67, - with options \\"\$ac_cs_config\\" - -Copyright (C) 2010 Free Software Foundation, Inc. -This config.status script is free software; the Free Software Foundation -gives unlimited permission to copy, distribute and modify it." - -ac_pwd='$ac_pwd' -srcdir='$srcdir' -test -n "\$AWK" || AWK=awk -_ACEOF - -cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 -# The default lists apply if the user does not specify any file. -ac_need_defaults=: -while test $# != 0 -do - case $1 in - --*=?*) - ac_option=`expr "X$1" : 'X\([^=]*\)='` - ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'` - ac_shift=: - ;; - --*=) - ac_option=`expr "X$1" : 'X\([^=]*\)='` - ac_optarg= - ac_shift=: - ;; - *) - ac_option=$1 - ac_optarg=$2 - ac_shift=shift - ;; - esac - - case $ac_option in - # Handling of the options. - -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) - ac_cs_recheck=: ;; - --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) - $as_echo "$ac_cs_version"; exit ;; - --config | --confi | --conf | --con | --co | --c ) - $as_echo "$ac_cs_config"; exit ;; - --debug | --debu | --deb | --de | --d | -d ) - debug=: ;; - --file | --fil | --fi | --f ) - $ac_shift - case $ac_optarg in - *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; - '') as_fn_error $? "missing file argument" ;; - esac - as_fn_append CONFIG_FILES " '$ac_optarg'" - ac_need_defaults=false;; - --he | --h | --help | --hel | -h ) - $as_echo "$ac_cs_usage"; exit ;; - -q | -quiet | --quiet | --quie | --qui | --qu | --q \ - | -silent | --silent | --silen | --sile | --sil | --si | --s) - ac_cs_silent=: ;; - - # This is an error. - -*) as_fn_error $? "unrecognized option: \`$1' -Try \`$0 --help' for more information." ;; - - *) as_fn_append ac_config_targets " $1" - ac_need_defaults=false ;; - - esac - shift -done - -ac_configure_extra_args= - -if $ac_cs_silent; then - exec 6>/dev/null - ac_configure_extra_args="$ac_configure_extra_args --silent" -fi - -_ACEOF -cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 -if \$ac_cs_recheck; then - set X '$SHELL' '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion - shift - \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6 - CONFIG_SHELL='$SHELL' - export CONFIG_SHELL - exec "\$@" -fi - -_ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 -exec 5>>config.log -{ - echo - sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX -## Running $as_me. ## -_ASBOX - $as_echo "$ac_log" -} >&5 - -_ACEOF -cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 -_ACEOF - -cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 - -# Handling of arguments. -for ac_config_target in $ac_config_targets -do - case $ac_config_target in - "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;; - "$make_mod_irc") CONFIG_FILES="$CONFIG_FILES $make_mod_irc" ;; - "$make_mod_muc") CONFIG_FILES="$CONFIG_FILES $make_mod_muc" ;; - "$make_mod_pubsub") CONFIG_FILES="$CONFIG_FILES $make_mod_pubsub" ;; - "$make_mod_proxy65") CONFIG_FILES="$CONFIG_FILES $make_mod_proxy65" ;; - "$make_eldap") CONFIG_FILES="$CONFIG_FILES $make_eldap" ;; - "$make_pam") CONFIG_FILES="$CONFIG_FILES $make_pam" ;; - "$make_web") CONFIG_FILES="$CONFIG_FILES $make_web" ;; - "stringprep/Makefile") CONFIG_FILES="$CONFIG_FILES stringprep/Makefile" ;; - "stun/Makefile") CONFIG_FILES="$CONFIG_FILES stun/Makefile" ;; - "$make_tls") CONFIG_FILES="$CONFIG_FILES $make_tls" ;; - "$make_odbc") CONFIG_FILES="$CONFIG_FILES $make_odbc" ;; - "$make_ejabberd_zlib") CONFIG_FILES="$CONFIG_FILES $make_ejabberd_zlib" ;; - - *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5 ;; - esac -done - - -# If the user did not use the arguments to specify the items to instantiate, -# then the envvar interface is used. Set only those that are not. -# We use the long form for the default assignment because of an extremely -# bizarre bug on SunOS 4.1.3. -if $ac_need_defaults; then - test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files -fi - -# Have a temporary directory for convenience. Make it in the build tree -# simply because there is no reason against having it here, and in addition, -# creating and moving files from /tmp can sometimes cause problems. -# Hook for its removal unless debugging. -# Note that there is a small window in which the directory will not be cleaned: -# after its creation but before its name has been assigned to `$tmp'. -$debug || -{ - tmp= - trap 'exit_status=$? - { test -z "$tmp" || test ! -d "$tmp" || rm -fr "$tmp"; } && exit $exit_status -' 0 - trap 'as_fn_exit 1' 1 2 13 15 -} -# Create a (secure) tmp directory for tmp files. - -{ - tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` && - test -n "$tmp" && test -d "$tmp" -} || -{ - tmp=./conf$$-$RANDOM - (umask 077 && mkdir "$tmp") -} || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5 - -# Set up the scripts for CONFIG_FILES section. -# No need to generate them if there are no CONFIG_FILES. -# This happens for instance with `./config.status config.h'. -if test -n "$CONFIG_FILES"; then - - -ac_cr=`echo X | tr X '\015'` -# On cygwin, bash can eat \r inside `` if the user requested igncr. -# But we know of no other shell where ac_cr would be empty at this -# point, so we can use a bashism as a fallback. -if test "x$ac_cr" = x; then - eval ac_cr=\$\'\\r\' -fi -ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null` -if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then - ac_cs_awk_cr='\\r' -else - ac_cs_awk_cr=$ac_cr -fi - -echo 'BEGIN {' >"$tmp/subs1.awk" && -_ACEOF - - -{ - echo "cat >conf$$subs.awk <<_ACEOF" && - echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' && - echo "_ACEOF" -} >conf$$subs.sh || - as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 -ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'` -ac_delim='%!_!# ' -for ac_last_try in false false false false false :; do - . ./conf$$subs.sh || - as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 - - ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X` - if test $ac_delim_n = $ac_delim_num; then - break - elif $ac_last_try; then - as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 - else - ac_delim="$ac_delim!$ac_delim _$ac_delim!! " - fi -done -rm -f conf$$subs.sh - -cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 -cat >>"\$tmp/subs1.awk" <<\\_ACAWK && -_ACEOF -sed -n ' -h -s/^/S["/; s/!.*/"]=/ -p -g -s/^[^!]*!// -:repl -t repl -s/'"$ac_delim"'$// -t delim -:nl -h -s/\(.\{148\}\)..*/\1/ -t more1 -s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/ -p -n -b repl -:more1 -s/["\\]/\\&/g; s/^/"/; s/$/"\\/ -p -g -s/.\{148\}// -t nl -:delim -h -s/\(.\{148\}\)..*/\1/ -t more2 -s/["\\]/\\&/g; s/^/"/; s/$/"/ -p -b -:more2 -s/["\\]/\\&/g; s/^/"/; s/$/"\\/ -p -g -s/.\{148\}// -t delim -' >$CONFIG_STATUS || ac_write_fail=1 -rm -f conf$$subs.awk -cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 -_ACAWK -cat >>"\$tmp/subs1.awk" <<_ACAWK && - for (key in S) S_is_set[key] = 1 - FS = "" - -} -{ - line = $ 0 - nfields = split(line, field, "@") - substed = 0 - len = length(field[1]) - for (i = 2; i < nfields; i++) { - key = field[i] - keylen = length(key) - if (S_is_set[key]) { - value = S[key] - line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3) - len += length(value) + length(field[++i]) - substed = 1 - } else - len += 1 + keylen - } - - print line -} - -_ACAWK -_ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 -if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then - sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g" -else - cat -fi < "$tmp/subs1.awk" > "$tmp/subs.awk" \ - || as_fn_error $? "could not setup config files machinery" "$LINENO" 5 -_ACEOF - -# VPATH may cause trouble with some makes, so we remove sole $(srcdir), -# ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and -# trailing colons and then remove the whole line if VPATH becomes empty -# (actually we leave an empty line to preserve line numbers). -if test "x$srcdir" = x.; then - ac_vpsub='/^[ ]*VPATH[ ]*=[ ]*/{ -h -s/// -s/^/:/ -s/[ ]*$/:/ -s/:\$(srcdir):/:/g -s/:\${srcdir}:/:/g -s/:@srcdir@:/:/g -s/^:*// -s/:*$// -x -s/\(=[ ]*\).*/\1/ -G -s/\n// -s/^[^=]*=[ ]*$// -}' -fi - -cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 -fi # test -n "$CONFIG_FILES" - - -eval set X " :F $CONFIG_FILES " -shift -for ac_tag -do - case $ac_tag in - :[FHLC]) ac_mode=$ac_tag; continue;; - esac - case $ac_mode$ac_tag in - :[FHL]*:*);; - :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5 ;; - :[FH]-) ac_tag=-:-;; - :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; - esac - ac_save_IFS=$IFS - IFS=: - set x $ac_tag - IFS=$ac_save_IFS - shift - ac_file=$1 - shift - - case $ac_mode in - :L) ac_source=$1;; - :[FH]) - ac_file_inputs= - for ac_f - do - case $ac_f in - -) ac_f="$tmp/stdin";; - *) # Look for the file first in the build tree, then in the source tree - # (if the path is not absolute). The absolute path cannot be DOS-style, - # because $ac_f cannot contain `:'. - test -f "$ac_f" || - case $ac_f in - [\\/$]*) false;; - *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; - esac || - as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5 ;; - esac - case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac - as_fn_append ac_file_inputs " '$ac_f'" - done - - # Let's still pretend it is `configure' which instantiates (i.e., don't - # use $as_me), people would be surprised to read: - # /* config.h. Generated by config.status. */ - configure_input='Generated from '` - $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g' - `' by configure.' - if test x"$ac_file" != x-; then - configure_input="$ac_file. $configure_input" - { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5 -$as_echo "$as_me: creating $ac_file" >&6;} - fi - # Neutralize special characters interpreted by sed in replacement strings. - case $configure_input in #( - *\&* | *\|* | *\\* ) - ac_sed_conf_input=`$as_echo "$configure_input" | - sed 's/[\\\\&|]/\\\\&/g'`;; #( - *) ac_sed_conf_input=$configure_input;; - esac - - case $ac_tag in - *:-:* | *:-) cat >"$tmp/stdin" \ - || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; - esac - ;; - esac - - ac_dir=`$as_dirname -- "$ac_file" || -$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ - X"$ac_file" : 'X\(//\)[^/]' \| \ - X"$ac_file" : 'X\(//\)$' \| \ - X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || -$as_echo X"$ac_file" | - sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ - s//\1/ - q - } - /^X\(\/\/\)[^/].*/{ - s//\1/ - q - } - /^X\(\/\/\)$/{ - s//\1/ - q - } - /^X\(\/\).*/{ - s//\1/ - q - } - s/.*/./; q'` - as_dir="$ac_dir"; as_fn_mkdir_p - ac_builddir=. - -case "$ac_dir" in -.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; -*) - ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` - # A ".." for each directory in $ac_dir_suffix. - ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` - case $ac_top_builddir_sub in - "") ac_top_builddir_sub=. ac_top_build_prefix= ;; - *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; - esac ;; -esac -ac_abs_top_builddir=$ac_pwd -ac_abs_builddir=$ac_pwd$ac_dir_suffix -# for backward compatibility: -ac_top_builddir=$ac_top_build_prefix - -case $srcdir in - .) # We are building in place. - ac_srcdir=. - ac_top_srcdir=$ac_top_builddir_sub - ac_abs_top_srcdir=$ac_pwd ;; - [\\/]* | ?:[\\/]* ) # Absolute name. - ac_srcdir=$srcdir$ac_dir_suffix; - ac_top_srcdir=$srcdir - ac_abs_top_srcdir=$srcdir ;; - *) # Relative name. - ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix - ac_top_srcdir=$ac_top_build_prefix$srcdir - ac_abs_top_srcdir=$ac_pwd/$srcdir ;; -esac -ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix - - - case $ac_mode in - :F) - # - # CONFIG_FILE - # - -_ACEOF - -cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 -# If the template does not know about datarootdir, expand it. -# FIXME: This hack should be removed a few years after 2.60. -ac_datarootdir_hack=; ac_datarootdir_seen= -ac_sed_dataroot=' -/datarootdir/ { - p - q -} -/@datadir@/p -/@docdir@/p -/@infodir@/p -/@localedir@/p -/@mandir@/p' -case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in -*datarootdir*) ac_datarootdir_seen=yes;; -*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 -$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} -_ACEOF -cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 - ac_datarootdir_hack=' - s&@datadir@&$datadir&g - s&@docdir@&$docdir&g - s&@infodir@&$infodir&g - s&@localedir@&$localedir&g - s&@mandir@&$mandir&g - s&\\\${datarootdir}&$datarootdir&g' ;; -esac -_ACEOF - -# Neutralize VPATH when `$srcdir' = `.'. -# Shell code in configure.ac might set extrasub. -# FIXME: do we really want to maintain this feature? -cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 -ac_sed_extra="$ac_vpsub -$extrasub -_ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 -:t -/@[a-zA-Z_][a-zA-Z_0-9]*@/!b -s|@configure_input@|$ac_sed_conf_input|;t t -s&@top_builddir@&$ac_top_builddir_sub&;t t -s&@top_build_prefix@&$ac_top_build_prefix&;t t -s&@srcdir@&$ac_srcdir&;t t -s&@abs_srcdir@&$ac_abs_srcdir&;t t -s&@top_srcdir@&$ac_top_srcdir&;t t -s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t -s&@builddir@&$ac_builddir&;t t -s&@abs_builddir@&$ac_abs_builddir&;t t -s&@abs_top_builddir@&$ac_abs_top_builddir&;t t -$ac_datarootdir_hack -" -eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$tmp/subs.awk" >$tmp/out \ - || as_fn_error $? "could not create $ac_file" "$LINENO" 5 - -test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && - { ac_out=`sed -n '/\${datarootdir}/p' "$tmp/out"`; test -n "$ac_out"; } && - { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' "$tmp/out"`; test -z "$ac_out"; } && - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir' -which seems to be undefined. Please make sure it is defined" >&5 -$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' -which seems to be undefined. Please make sure it is defined" >&2;} - - rm -f "$tmp/stdin" - case $ac_file in - -) cat "$tmp/out" && rm -f "$tmp/out";; - *) rm -f "$ac_file" && mv "$tmp/out" "$ac_file";; - esac \ - || as_fn_error $? "could not create $ac_file" "$LINENO" 5 - ;; - - - - esac - -done # for ac_tag - - -as_fn_exit 0 -_ACEOF -ac_clean_files=$ac_clean_files_save - -test $ac_write_fail = 0 || - as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5 - - -# configure is writing to config.log, and then calls config.status. -# config.status does its own redirection, appending to config.log. -# Unfortunately, on DOS this fails, as config.log is still kept open -# by configure, so config.status won't be able to write to it; its -# output is simply discarded. So we exec the FD to /dev/null, -# effectively closing config.log, so it can be properly (re)opened and -# appended to by config.status. When coming back to configure, we -# need to make the FD available again. -if test "$no_create" != yes; then - ac_cs_success=: - ac_config_status_args= - test "$silent" = yes && - ac_config_status_args="$ac_config_status_args --quiet" - exec 5>/dev/null - $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false - exec 5>>config.log - # Use ||, not &&, to avoid exiting from the if with $? = 1, which - # would make configure fail if this is the last instruction. - $ac_cs_success || as_fn_exit 1 -fi -if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5 -$as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;} -fi - From c576f340f93a6166a1c276935759bc40ad1f7763 Mon Sep 17 00:00:00 2001 From: Christophe Romain Date: Fri, 17 Sep 2010 06:27:41 +0200 Subject: [PATCH 55/85] upgrade to lattest pubsub schema --- src/mod_pubsub/pubsub_clean.erl | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/src/mod_pubsub/pubsub_clean.erl b/src/mod_pubsub/pubsub_clean.erl index 6e32ccb35..579ccc0f1 100644 --- a/src/mod_pubsub/pubsub_clean.erl +++ b/src/mod_pubsub/pubsub_clean.erl @@ -2,7 +2,7 @@ -define(TIMEOUT, 1000*600). % 1 minute --export([start/0, loop/0, subscribed/1, offline/1]). +-export([start/0, loop/0, offline/1]). start() -> Pid = spawn(?MODULE, loop, []), @@ -24,17 +24,12 @@ purge() -> I=element(3,N), lists:foreach(fun(JID) -> mnesia:dirty_delete({pubsub_state, {JID, I}}) - end, offline(subscribed(I))) + end, offline(pubsub_debug:subscribed(I))) end, mnesia:dirty_all_keys(pubsub_node)); true -> ok end. -subscribed(NodeId) -> - lists:map(fun(S) -> - element(1,element(2,S)) - end, mnesia:dirty_match_object({pubsub_state, {'_',NodeId},'_',none,subscribed})). - offline(Jids) -> lists:filter(fun({U,S,""}) -> ejabberd_sm:get_user_resources(U,S) == []; ({U,S,R}) -> not lists:member(R,ejabberd_sm:get_user_resources(U,S)) From 694af699825f302b24f9cb7dc93b365a1bfd246d Mon Sep 17 00:00:00 2001 From: Christophe Romain Date: Fri, 17 Sep 2010 06:46:40 +0200 Subject: [PATCH 56/85] ejabberd.app now set to version 2.2.x --- src/ejabberd.app | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ejabberd.app b/src/ejabberd.app index 67653d241..ea85a9f26 100644 --- a/src/ejabberd.app +++ b/src/ejabberd.app @@ -2,7 +2,7 @@ {application, ejabberd, [{description, "ejabberd"}, - {vsn, "2.1.x"}, + {vsn, "2.2.x"}, {modules, [acl, adhoc, configure, From 893c47a2e0891547f36be018511a64c67982da1c Mon Sep 17 00:00:00 2001 From: Christophe Romain Date: Fri, 17 Sep 2010 07:28:28 +0200 Subject: [PATCH 57/85] add ability to retreive only node names --- src/mod_pubsub/pubsub_debug.erl | 1 + 1 file changed, 1 insertion(+) diff --git a/src/mod_pubsub/pubsub_debug.erl b/src/mod_pubsub/pubsub_debug.erl index 2fe1a5b42..97ca8275f 100644 --- a/src/mod_pubsub/pubsub_debug.erl +++ b/src/mod_pubsub/pubsub_debug.erl @@ -16,6 +16,7 @@ nodeids_by_type(Type) -> [nodeid(N) || N <- mnesia:dirty_match_object(#pubsub_no nodeids_by_option(Key, Value) -> [nodeid(N) || N <- mnesia:dirty_match_object(#pubsub_node{_='_'}), lists:member({Key, Value}, N#pubsub_node.options)]. nodeids_by_owner(JID) -> [nodeid(N) || N <- mnesia:dirty_match_object(#pubsub_node{_='_'}), lists:member(JID, N#pubsub_node.owners)]. nodes_by_id(I) -> mnesia:dirty_match_object(#pubsub_node{id=I, _='_'}). +nodes() -> [element(2, element(2, N)) || N <- mnesia:dirty_match_object(#pubsub_node{_='_'})]. state(JID, NodeId) -> case mnesia:dirty_read({pubsub_state, {JID, NodeId}}) of From 100b821c1a8ba625195220613ee487a0fc969a3e Mon Sep 17 00:00:00 2001 From: Christophe Romain Date: Fri, 17 Sep 2010 09:11:03 +0200 Subject: [PATCH 58/85] added customer related tools --- tools/joincluster | 136 ++++++++++++++++++++++++++++++++++++++++++++ tools/leavecluster | 93 ++++++++++++++++++++++++++++++ tools/tcp-tuning.sh | 38 +++++++++++++ 3 files changed, 267 insertions(+) create mode 100755 tools/joincluster create mode 100755 tools/leavecluster create mode 100755 tools/tcp-tuning.sh diff --git a/tools/joincluster b/tools/joincluster new file mode 100755 index 000000000..03fee9e9f --- /dev/null +++ b/tools/joincluster @@ -0,0 +1,136 @@ +#!/bin/bash + +# Add the current ejabberd node in a cluster + +# copyright (c) 2010 ProcessOne +# +# This script is proprietary software and cannot be published or redistribute. + +# Return Code: +# 0 : groovy baby +# 11 : erl not found +# 12 : erlc not found +# 20 : database dir doesn't exist +# 21 : database dir not writable +# 21 : database dir variable not set +# 30 : network issue +# 31 : node names incompatibility + +function error +{ + echo "Error: $1" >&2 + exit $2 +} + +echo "--------------------------------------------------------------------" +echo "" +echo "ejabberd cluster configuration" +echo "" +echo "This ejabberd node will be configured for use in an ejabberd cluster." +echo "IMPORTANT: all local data from the database will be lost, and" +echo "cluster database will be initialized. All data from the master" +echo "node will be replicated to this one." +echo "" +echo "--------------------------------------------------------------------" +echo "Press any key to continue, or Ctrl+C to stop now" +read foo +echo "" + +echo "Make sure you have a running remote master ejabberd node" +echo "Before continuing, you must copy the ~/.erlang.cookie file from" +echo "remote master node and check ejabberd.cfg compatibility." +echo "e.g. hosts definition must match on all nodes" +echo "" +echo "The remote master node name is defined as ERLANG_NODE into" +echo "ejabberdctl.cfg on that remote node." +echo "" +echo -n "Remote master node name: " +read REMOTE +echo "" + +cont=Y +ping -q -c 1 ${REMOTE#*@} 2>/dev/null >/dev/null +[ $? -eq 0 ] || { + echo "Cannot ping ${REMOTE#*@}. Are you sure network setup is correct ?" + echo -n "Should we continue anyway ? (Y/n) " + read cont +} +cont=`echo $cont | tr a-z A-Z` +[ "$cont" == "Y" ] || error "Check your network configuration (dns, firewall, etc...)" 30 + +HERE=`which "$0"` +BASE=`dirname $HERE`/.. +ROOTDIR=`cd $BASE; pwd` +. $ROOTDIR/bin/ejabberdctl stop 2>/dev/null >/dev/null +NAME=-name +[ "$ERLANG_NODE" = "${ERLANG_NODE%.*}" ] && NAME=-sname +PA=/tmp/clustersetup_$$ +CLUSTERSETUP=clustersetup +CLUSTERSETUP_ERL=$PA/$CLUSTERSETUP.erl + +REMOTENAME=-name +[ "$REMOTE" = "${REMOTE%.*}" ] && REMOTENAME=-sname +[ "$REMOTENAME" = "$NAME" ] || { + echo "IMPORTANT!: node names are incompatible" + echo "Remote node name is $REMOTE" + echo "Local node name is $ERLANG_NODE" + echo "" + echo "Both node names must be short or fqdn names." + echo "Using short and fqdn names is impossible." + echo "" + error "incompatible node names" 31 +} + +set -o errexit +set -o nounset + +echo "Using commands:" +which erl || error "can't find erl" 11 +which erlc || error "can't find erlc" 12 +echo "" + +[ -d $EJABBERD_DB ] && rm -Rf $EJABBERD_DB +mkdir $EJABBERD_DB || error "$EJABBERD_DB cannot be created" 20 +[ -w $EJABBERD_DB ] || error "$EJABBERD_DB directory is not writable" 21 + +cd $ROOTDIR +mkdir -p $PA +cat < $CLUSTERSETUP_ERL +-module($CLUSTERSETUP). + +-export([start/0]). + +set_table_copy(Table, _Node, {badrpc, Reason}) -> + io:format("Error: cannot get storage type for table ~p on node $REMOTE:~n ~p~n",[Table, Reason]); +set_table_copy(Table, Node, Type) -> + io:format("setting table ~p to mode ~p~n",[Table, Type]), + case mnesia:add_table_copy(Table, Node, Type) of + {aborted, _} -> + mnesia:change_table_copy_type(Table, Node, Type); + _ -> + ok + end. + +set_tables({badrpc, Reason}) -> + io:format("ERROR: cannot get tables list on $REMOTE : ~p~n",[Reason]); +set_tables([]) -> + ok; +set_tables([schema | Tables]) -> + set_tables(Tables); +set_tables([Table | Tables]) -> + set_table_copy(Table, node(), + rpc:call('$REMOTE', mnesia, table_info, [Table, storage_type])), + set_tables(Tables). + +start() -> + io:format("~n",[]), + set_table_copy(schema, node(), disc_copies), + set_tables(rpc:call('$REMOTE', mnesia, system_info, [tables])), + halt(0). +EOF +erlc -o $PA $CLUSTERSETUP_ERL +erl $NAME $ERLANG_NODE -pa $PA $KERNEL_OPTS -mnesia extra_db_nodes "['$REMOTE']" dir "\"$EJABBERD_DB\"" -s mnesia -s $CLUSTERSETUP start +rm -Rf $PA + +echo "End." +echo "Check that there is no error in the above messages." diff --git a/tools/leavecluster b/tools/leavecluster new file mode 100755 index 000000000..f6b7b7ac8 --- /dev/null +++ b/tools/leavecluster @@ -0,0 +1,93 @@ +#!/bin/bash + +# Remove the current ejabberd node in a cluster + +# Return Code: +# 0 : groovy baby +# 11 : erl not found +# 12 : erlc not found +# 20 : database dir doesn't exist +# 21 : database dir not writable +# 21 : database dir variable not set + +function error +{ + echo "Error: $1" >&2 + exit $2 +} + +echo "--------------------------------------------------------------------" +echo "" +echo "ejabberd cluster configuration" +echo "" +echo "This ejabberd node will be removed from the cluster." +echo "IMPORTANT: this node will be stopped. At least one other clustered" +echo "node must be running." +echo "" +echo "--------------------------------------------------------------------" +echo "Press any key to continue, or Ctrl+C to stop now" +read foo +echo "" + +HERE=`which "$0"` +BASE=`dirname $HERE`/.. +ROOTDIR=`cd $BASE; pwd` +. $ROOTDIR/bin/ejabberdctl stop 2>/dev/null >/dev/null +$ROOTDIR/bin/ejabberdctl stopped +PA=/tmp/clustersetup_$$ +CLUSTERSETUP=clustersetup +CLUSTERSETUP_ERL=$PA/$CLUSTERSETUP.erl + +set -o errexit +set -o nounset + +echo "Using commands:" +which erl || error "can't find erl" 11 +which erlc || error "can't find erlc" 12 +echo "" + +cd $ROOTDIR +mkdir -p $PA +cat < $CLUSTERSETUP_ERL +-module($CLUSTERSETUP). + +-export([start/0]). + +del_table_copy(Table, Node) -> + case mnesia:del_table_copy(Table, Node) of + {aborted, Reason} -> io:format("Error: can not remove ~p table: ~p~n", [Table, Reason]); + _ -> io:format("table ~p removed from cluster~n", [Table]) + end. + +del_tables([],_) -> + ok; +del_tables([schema | Tables], Node) -> + del_tables(Tables, Node); +del_tables([Table | Tables], Node) -> + del_table_copy(Table, Node), + del_tables(Tables, Node). + +start() -> + io:format("~n",[]), + Removed = node(), + case mnesia:system_info(running_db_nodes)--[Removed] of + [] -> io:format("Error: no other node running in the cluster~n"); + Nodes -> + del_tables(mnesia:system_info(local_tables), Removed), + mnesia:stop(), + case rpc:call(hd(Nodes), mnesia, del_table_copy, [schema, Removed]) of + {badrpc,Reason} -> io:format("Error: can not unregister node ~p from cluster: ~p~n", [Removed, Reason]); + {aborted,Reason} -> io:format("Error: can not unregister node ~p from cluster: ~p~n", [Removed, Reason]); + {atomic, ok} -> + mnesia:delete_schema([Removed]), + io:format("node ~p removed from cluster~n", [Removed]) + end + end, + halt(0). +EOF +erlc -o $PA $CLUSTERSETUP_ERL +erl $NAME $ERLANG_NODE -pa $PA $KERNEL_OPTS -mnesia dir "\"$EJABBERD_DB\"" -s mnesia -s $CLUSTERSETUP start +rm -Rf $PA + +echo "End." +echo "Check that there is no error in the above messages." diff --git a/tools/tcp-tuning.sh b/tools/tcp-tuning.sh new file mode 100755 index 000000000..dcc2ef5ba --- /dev/null +++ b/tools/tcp-tuning.sh @@ -0,0 +1,38 @@ +#!/bin/sh +ulimit -n 562524 +# /etc/security/limits.conf +#@ejabberd soft nofile 562000 +#@ejabberd hard nofile 562000 +# 4KB send buffer, 20,480 connections max at worst case +#echo 83886080 > /proc/sys/net/core/wmem_max +#echo 83886080 > /proc/sys/net/core/wmem_default +echo 327680000 > /proc/sys/net/core/wmem_max +echo 327680000 > /proc/sys/net/core/wmem_default +# 16KB receive buffer, 20,480 connections max at worst case +#echo 335544320 > /proc/sys/net/core/rmem_max +#echo 335544320 > /proc/sys/net/core/rmem_default +echo 1310720000 > /proc/sys/net/core/rmem_max +echo 1310720000 > /proc/sys/net/core/rmem_default +# Max open files +echo 562524 > /proc/sys/fs/file-max +# Fast port recycling (TIME_WAIT) +echo 1 >/proc/sys/net/ipv4/tcp_tw_recycle +echo 1 >/proc/sys/net/ipv4/tcp_tw_reuse +# TIME_WAIT buckets increased +echo 360000 > /proc/sys/net/ipv4/tcp_max_tw_buckets +# FIN timeout decreased +echo 15 > /proc/sys/net/ipv4/tcp_fin_timeout +# SYN backlog increased +echo 65536 > /proc/sys/net/ipv4/tcp_max_syn_backlog +# SYN cookies enabled +echo 1 > /proc/sys/net/ipv4/tcp_syncookies +# Local port range maximized +echo "1024 65535" > /proc/sys/net/ipv4/ip_local_port_range +# Netdev backlog increased +echo 100000 > /proc/sys/net/core/netdev_max_backlog +# Do no save route metrics +echo 1 > /proc/sys/net/ipv4/route/flush +echo 30 > /proc/sys/net/ipv4/tcp_fin_timeout +# Interface transmit queuelen increased +ifconfig eth0 txqueuelen 10000 + From ff4f052bb169d479dd02f4fa268dbe15fdad329e Mon Sep 17 00:00:00 2001 From: Eric Cestari Date: Fri, 17 Sep 2010 14:23:34 +0200 Subject: [PATCH 59/85] [TECH-1151] Origin and Protocol parameters are configurable and set. --- src/web/ejabberd_http.erl | 28 +++++++++++++++++++++++++--- src/web/ejabberd_http.hrl | 4 +++- src/web/ejabberd_websocket.erl | 22 +++++++++++++++++++++- 3 files changed, 49 insertions(+), 5 deletions(-) diff --git a/src/web/ejabberd_http.erl b/src/web/ejabberd_http.erl index 9bfb3bd62..5e8b62c70 100644 --- a/src/web/ejabberd_http.erl +++ b/src/web/ejabberd_http.erl @@ -155,7 +155,7 @@ socket_type() -> raw. -send_text(State, none) -> +send_text(_State, none) -> exit(normal); send_text(State, Text) -> case catch (State#state.sockmod):send(State#state.socket, Text) of @@ -298,6 +298,11 @@ process_header(State, Data) -> add_header(Name, Value, State) -> [{Name, Value} | State#state.request_headers]. +-define(GETOPT(Param, Opts), + case lists:keysearch(Param, 1, Opts) of + {value, {Param, V}} -> V; + false -> undefined + end). %% @spec (SockMod, HostPort) -> {Host::string(), Port::integer(), TP} %% where %% SockMod = gen_tcp | tls @@ -322,17 +327,34 @@ get_transfer_protocol(SockMod, HostPort) -> %% XXX bard: search through request handlers looking for one that %% matches the requested URL path, and pass control to it. If none is %% found, answer with HTTP 404. + process([], _) -> ejabberd_web:error(not_found); process(Handlers, #ws{} = Ws)-> - [{HandlerPathPrefix, HandlerModule} | HandlersLeft] = Handlers, + [{HandlerPathPrefix, HandlerModule, HandlerOpts} | HandlersLeft] = Handlers, case (lists:prefix(HandlerPathPrefix, Ws#ws.path) or (HandlerPathPrefix==Ws#ws.path)) of true -> ?DEBUG("~p matches ~p", [Ws#ws.path, HandlerPathPrefix]), LocalPath = lists:nthtail(length(HandlerPathPrefix), Ws#ws.path), ejabberd_hooks:run(ws_debug, [{LocalPath, Ws}]), - ejabberd_websocket:connect(Ws#ws{local_path = LocalPath}, HandlerModule); + Protocol = case lists:keysearch(protocol, 1, HandlerOpts) of + {value, {protocol, P}} -> P; + false -> undefined + end, + Origins = case lists:keysearch(origins, 1, HandlerOpts) of + {value, {origins, O}} -> O; + false -> [] + end, + WS2 = Ws#ws{local_path = LocalPath, + protocol=Protocol, + acceptable_origins=Origins}, + case ejabberd_websocket:is_acceptable(WS2) of + true -> + ejabberd_websocket:connect(WS2, HandlerModule); + false -> + process(HandlersLeft, Ws) + end; false -> ?DEBUG("HandlersLeft : ~p ", [HandlersLeft]), process(HandlersLeft, Ws) diff --git a/src/web/ejabberd_http.hrl b/src/web/ejabberd_http.hrl index 5a163b799..c303ac8ae 100644 --- a/src/web/ejabberd_http.hrl +++ b/src/web/ejabberd_http.hrl @@ -48,5 +48,7 @@ port, path, % the websocket GET request path headers, % [{Tag, Val}] - local_path + local_path, + protocol, + acceptable_origins }). \ No newline at end of file diff --git a/src/web/ejabberd_websocket.erl b/src/web/ejabberd_websocket.erl index b579c057e..e7869508a 100644 --- a/src/web/ejabberd_websocket.erl +++ b/src/web/ejabberd_websocket.erl @@ -38,7 +38,7 @@ -module (ejabberd_websocket). -author('ecestari@process-one.net'). --compile(export_all). +-export([connect/2, check/2, is_acceptable/1]). -include("ejabberd.hrl"). -include("jlib.hrl"). -include("ejabberd_http.hrl"). @@ -49,6 +49,26 @@ check(_Path, Headers)-> % checks check_websockets(VsnSupported, Headers). +% Checks if websocket can be access by client +% If origins are set in configuration, check if it belongs +% If origins not set, access is open. +is_acceptable(#ws{origin=Origin, protocol=Protocol, + headers = Headers, acceptable_origins = Origins})-> + ClientProtocol = lists:keyfind("Sec-WebSocket-Protocol",1, Headers), + case {Origin == [] or lists:member(Origin, Origins), ClientProtocol, Protocol } of + {false, _, _} -> + ?DEBUG("client does not come from authorized origin", []), + false; + {_, false, _} -> + ?DEBUG("Client did not ask for protocol", []), + true; + {_, {_, P}, P} -> + ?DEBUG("Protocoles are matching", []), + true; + _ -> false + end. + + % Connect and handshake with Websocket. connect(#ws{vsn = Vsn, socket = Socket, origin=Origin, host=Host, port=Port, sockmod = SockMod, path = Path, headers = Headers, ws_autoexit = WsAutoExit} = Ws, WsLoop) -> % build handshake From 0987700a27bd3daa44596f0edbd7ff801d240179 Mon Sep 17 00:00:00 2001 From: Eric Cestari Date: Fri, 17 Sep 2010 14:24:24 +0200 Subject: [PATCH 60/85] Rename protocol version 76 to 00 (new official name) --- src/web/ejabberd_websocket.erl | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/web/ejabberd_websocket.erl b/src/web/ejabberd_websocket.erl index e7869508a..f1ce8d25f 100644 --- a/src/web/ejabberd_websocket.erl +++ b/src/web/ejabberd_websocket.erl @@ -45,7 +45,7 @@ check(_Path, Headers)-> % set supported websocket protocols, order does matter - VsnSupported = [{'draft-hixie', 76}, {'draft-hixie', 68}], + VsnSupported = [{'draft-hixie', 0}, {'draft-hixie', 68}], % checks check_websockets(VsnSupported, Headers). @@ -101,7 +101,7 @@ check_websockets([Vsn|T], Headers) -> % Function: {true, Vsn} | false % Description: Check if the incoming request is a websocket request. -check_websocket({'draft-hixie', 76} = Vsn, Headers) -> +check_websocket({'draft-hixie', 0} = Vsn, Headers) -> %?DEBUG("testing for websocket protocol ~p", [Vsn]), % set required headers RequiredHeaders = [ @@ -155,7 +155,7 @@ check_headers(Headers, RequiredHeaders) -> % Function: List % Description: Builds the server handshake response. -handshake({'draft-hixie', 76}, Sock,SocketMod, Headers, {Path, Origin, Host, Port}) -> +handshake({'draft-hixie', 0}, Sock,SocketMod, Headers, {Path, Origin, Host, Port}) -> % build data {_, Key1} = lists:keyfind("Sec-Websocket-Key1",1, Headers), {_, Key2} = lists:keyfind("Sec-Websocket-Key2",1, Headers), @@ -184,7 +184,7 @@ handshake({'draft-hixie', 76}, Sock,SocketMod, Headers, {Path, Origin, Host, Por "Sec-WebSocket-Location: ws://", string:join([Host, integer_to_list(Port)],":"), "/",string:join(Path,"/") , "\r\n\r\n", - build_challenge({'draft-hixie', 76}, {Key1, Key2, Body}) + build_challenge({'draft-hixie', 0}, {Key1, Key2, Body}) ]; handshake({'draft-hixie', 68}, _Sock,_SocketMod, _Headers, {Path, Origin, Host, Port}) -> % prepare handhsake response @@ -200,7 +200,7 @@ handshake({'draft-hixie', 68}, _Sock,_SocketMod, _Headers, {Path, Origin, Host, % Function: List % Description: Builds the challenge for a handshake response. % Code portions from Sergio Veiga -build_challenge({'draft-hixie', 76}, {Key1, Key2, Key3}) -> +build_challenge({'draft-hixie', 0}, {Key1, Key2, Key3}) -> Ikey1 = [D || D <- Key1, $0 =< D, D =< $9], Ikey2 = [D || D <- Key2, $0 =< D, D =< $9], Blank1 = length([D || D <- Key1, D =:= 32]), From b44c462b0e584be71041f15b5aeb0e93d7e9d13a Mon Sep 17 00:00:00 2001 From: Eric Cestari Date: Fri, 17 Sep 2010 14:49:04 +0200 Subject: [PATCH 61/85] [TECH-1151] IP now correctly stored --- src/web/ejabberd_http.erl | 1 + src/web/ejabberd_http.hrl | 4 +--- src/web/ejabberd_http_ws.erl | 19 ++++++++----------- src/web/ejabberd_websocket.erl | 2 +- src/web/ejabberd_ws.erl | 8 ++------ 5 files changed, 13 insertions(+), 21 deletions(-) diff --git a/src/web/ejabberd_http.erl b/src/web/ejabberd_http.erl index 5e8b62c70..f4ee13e20 100644 --- a/src/web/ejabberd_http.erl +++ b/src/web/ejabberd_http.erl @@ -420,6 +420,7 @@ process_request(#state{request_method = Method, Ws = #ws{socket = Socket, sockmod = SockMod, ws_autoexit = true, + ip = IP, path = LPath, vsn = VSN, host = Host, diff --git a/src/web/ejabberd_http.hrl b/src/web/ejabberd_http.hrl index c303ac8ae..89c2a55c4 100644 --- a/src/web/ejabberd_http.hrl +++ b/src/web/ejabberd_http.hrl @@ -39,9 +39,7 @@ socket, % the socket handling the request sockmod, % gen_tcp | tls ws_autoexit, % websocket process is automatically killed: true | false - peer_addr, % peer IP | undefined - peer_port, % peer port | undefined - peer_cert, % undefined | the DER encoded peer certificate that can be decoded with public_key:pkix_decode_cert/2 + ip, % peer IP | undefined vsn, % {Maj,Min} | {'draft-hixie', Ver} origin, % the originator host, % the host diff --git a/src/web/ejabberd_http_ws.erl b/src/web/ejabberd_http_ws.erl index a4838c6e0..6b180a34e 100644 --- a/src/web/ejabberd_http_ws.erl +++ b/src/web/ejabberd_http_ws.erl @@ -43,6 +43,7 @@ setopts/2, sockname/1, peername/1, controlling_process/2, + become_controller/2, close/1]). -include("ejabberd.hrl"). @@ -108,8 +109,6 @@ close({http_ws, FsmRef, _IP}) -> init([WS]) -> - ?INFO_MSG("started: ~p", [WS]), - %% Read c2s options from the first ejabberd_c2s configuration in %% the config file listen section %% TODO: We should have different access and shaper values for @@ -125,7 +124,8 @@ init([WS]) -> undefined -> ?WEBSOCKET_TIMEOUT end, - Socket = {http_ws, self(), {{127,0,0,1}, 5280}}, %FIXME + Socket = {http_ws, self(), WS:get(ip)}, + ?DEBUG("Client connected through websocket ~p", [Socket]), ejabberd_socket:start(ejabberd_c2s, ?MODULE, Socket, Opts), Timer = erlang:start_timer(WSTimeout, self(), []), {ok, loop, #state{ @@ -164,23 +164,20 @@ handle_sync_event(close, _From, _StateName, StateData) -> {stop, normal, Reply, StateData}. handle_info({browser, Packet}, StateName, StateData)-> - case StateData#state.waiting_input of + NewState = case StateData#state.waiting_input of false -> Input = [StateData#state.input|Packet], - Reply = ok, - {reply, Reply, StateName, StateData#state{input = Input}}; + StateData#state{input = Input}; {Receiver, _Tag} -> Receiver ! {tcp, StateData#state.socket, list_to_binary(Packet)}, cancel_timer(StateData#state.timer), Timer = erlang:start_timer(StateData#state.timeout, self(), []), - Reply = ok, - {reply, Reply, StateName, - StateData#state{waiting_input = false, + StateData#state{waiting_input = false, last_receiver = Receiver, - timer = Timer}} + timer = Timer} end, - {next_state, StateName, StateData}; + {next_state, StateName, NewState}; handle_info({timeout, Timer, _}, _StateName, diff --git a/src/web/ejabberd_websocket.erl b/src/web/ejabberd_websocket.erl index f1ce8d25f..5a617b955 100644 --- a/src/web/ejabberd_websocket.erl +++ b/src/web/ejabberd_websocket.erl @@ -55,7 +55,7 @@ check(_Path, Headers)-> is_acceptable(#ws{origin=Origin, protocol=Protocol, headers = Headers, acceptable_origins = Origins})-> ClientProtocol = lists:keyfind("Sec-WebSocket-Protocol",1, Headers), - case {Origin == [] or lists:member(Origin, Origins), ClientProtocol, Protocol } of + case {(Origin == []) or lists:member(Origin, Origins), ClientProtocol, Protocol } of {false, _, _} -> ?DEBUG("client does not come from authorized origin", []), false; diff --git a/src/web/ejabberd_ws.erl b/src/web/ejabberd_ws.erl index 2babb551f..5ccaadf34 100644 --- a/src/web/ejabberd_ws.erl +++ b/src/web/ejabberd_ws.erl @@ -54,12 +54,8 @@ get(socket) -> Ws#ws.socket; get(socket_mode) -> Ws#ws.sockmod; -get(peer_addr) -> - Ws#ws.peer_addr; -get(peer_port) -> - Ws#ws.peer_port; -get(peer_cert) -> - Ws#ws.peer_cert; +get(ip) -> + Ws#ws.ip; get(vsn) -> Ws#ws.vsn; get(origin) -> From 8ea523889bf45b55bc3b81a32a65c526eea3b4fe Mon Sep 17 00:00:00 2001 From: Eric Cestari Date: Fri, 17 Sep 2010 16:10:59 +0200 Subject: [PATCH 62/85] [TECH-1151] Websockets are now handled in pure binary --- src/web/ejabberd_http_ws.erl | 9 ++++----- src/web/ejabberd_websocket.erl | 23 +++++++++++------------ 2 files changed, 15 insertions(+), 17 deletions(-) diff --git a/src/web/ejabberd_http_ws.erl b/src/web/ejabberd_http_ws.erl index 6b180a34e..f8ffb3aef 100644 --- a/src/web/ejabberd_http_ws.erl +++ b/src/web/ejabberd_http_ws.erl @@ -151,12 +151,12 @@ handle_event({activate, From}, StateName, StateData) -> handle_sync_event({send, Packet}, _From, StateName, #state{ws = WS} = StateData) -> Packet2 = if is_binary(Packet) -> - binary_to_list(Packet); + Packet; true -> - Packet + list_to_binary(Packet) end, ?DEBUG("sending on websocket : ~p ", [Packet2]), - WS:send(lists:flatten(Packet2)), + WS:send(Packet2), {reply, ok, StateName, StateData}; handle_sync_event(close, _From, _StateName, StateData) -> @@ -169,8 +169,7 @@ handle_info({browser, Packet}, StateName, StateData)-> Input = [StateData#state.input|Packet], StateData#state{input = Input}; {Receiver, _Tag} -> - Receiver ! {tcp, StateData#state.socket, - list_to_binary(Packet)}, + Receiver ! {tcp, StateData#state.socket,Packet}, cancel_timer(StateData#state.timer), Timer = erlang:start_timer(StateData#state.timeout, self(), []), StateData#state{waiting_input = false, diff --git a/src/web/ejabberd_websocket.erl b/src/web/ejabberd_websocket.erl index 5a617b955..2b4d41292 100644 --- a/src/web/ejabberd_websocket.erl +++ b/src/web/ejabberd_websocket.erl @@ -212,10 +212,9 @@ build_challenge({'draft-hixie', 0}, {Key1, Key2, Key3}) -> ws_loop(Socket, Buffer, WsHandleLoopPid, SocketMode, WsAutoExit) -> - %?DEBUG("websocket loop", []), receive {tcp, Socket, Data} -> - handle_data(Buffer, binary_to_list(Data), Socket, WsHandleLoopPid, SocketMode, WsAutoExit); + handle_data(Buffer, Data, Socket, WsHandleLoopPid, SocketMode, WsAutoExit); {tcp_closed, Socket} -> ?DEBUG("tcp connection was closed, exit", []), % close websocket and custom controlling loop @@ -233,8 +232,8 @@ ws_loop(Socket, Buffer, WsHandleLoopPid, SocketMode, WsAutoExit) -> % close websocket and custom controlling loop websocket_close(Socket, WsHandleLoopPid, SocketMode, WsAutoExit); {send, Data} -> - %?DEBUG("sending data to websocket: ~p", [Data]), - SocketMode:send(Socket, [0, Data, 255]), + ?DEBUG("sending data to websocket: ~p", [Data]), + SocketMode:send(Socket, iolist_to_binary([0,Data,255])), ws_loop(Socket, Buffer, WsHandleLoopPid, SocketMode, WsAutoExit); shutdown -> ?DEBUG("shutdown request received, closing websocket with pid ~p", [self()]), @@ -246,20 +245,20 @@ ws_loop(Socket, Buffer, WsHandleLoopPid, SocketMode, WsAutoExit) -> end. % Buffering and data handling -handle_data(none, [0|T], Socket, WsHandleLoopPid, SocketMode, WsAutoExit) -> - handle_data([], T, Socket, WsHandleLoopPid, SocketMode, WsAutoExit); +handle_data(none,<<0,T/binary>>, Socket, WsHandleLoopPid, SocketMode, WsAutoExit) -> + handle_data(<<>>, T, Socket, WsHandleLoopPid, SocketMode, WsAutoExit); -handle_data(none, [], Socket, WsHandleLoopPid, SocketMode, WsAutoExit) -> +handle_data(none, <<>>, Socket, WsHandleLoopPid, SocketMode, WsAutoExit) -> ws_loop(Socket, none, WsHandleLoopPid, SocketMode, WsAutoExit); -handle_data(L, [255|T], Socket, WsHandleLoopPid, SocketMode, WsAutoExit) -> - WsHandleLoopPid ! {browser, lists:reverse(L)}, +handle_data(L, <<255,T/binary>>, Socket, WsHandleLoopPid, SocketMode, WsAutoExit) -> + WsHandleLoopPid ! {browser, iolist_to_binary(L)}, handle_data(none, T, Socket, WsHandleLoopPid, SocketMode, WsAutoExit); -handle_data(L, [H|T], Socket, WsHandleLoopPid, SocketMode, WsAutoExit) -> - handle_data([H|L], T, Socket, WsHandleLoopPid, SocketMode, WsAutoExit); +handle_data(L, <>, Socket, WsHandleLoopPid, SocketMode, WsAutoExit) -> + handle_data(iolist_to_binary([L, H]), T, Socket, WsHandleLoopPid, SocketMode, WsAutoExit); -handle_data([], L, Socket, WsHandleLoopPid, SocketMode, WsAutoExit) -> +handle_data(<<>>, L, Socket, WsHandleLoopPid, SocketMode, WsAutoExit) -> ws_loop(Socket, L, WsHandleLoopPid, SocketMode, WsAutoExit). % Close socket and custom handling loop dependency From e2c3925b7df6e52ee431d4224269c3ed17916f32 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20K=C3=B6hler?= Date: Fri, 17 Sep 2010 16:42:35 +0200 Subject: [PATCH 63/85] Discard unmatched INFO messages in ejabberd services. This patch will stop services terminating with function clause messages, but doesn't affect the message queue at all. --- src/ejabberd_service.erl | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/ejabberd_service.erl b/src/ejabberd_service.erl index bd07bfea8..942f0fa4d 100644 --- a/src/ejabberd_service.erl +++ b/src/ejabberd_service.erl @@ -353,6 +353,9 @@ handle_info({route, From, To, Packet}, StateName, StateData) -> Err = jlib:make_error_reply(Packet, ?ERR_NOT_ALLOWED), ejabberd_router:route_error(To, From, Err, Packet) end, + {next_state, StateName, StateData}; +handle_info(Info, StateName, StateData) -> + ?ERROR_MSG("Unexpected info: ~p", [Info]), {next_state, StateName, StateData}. From 3278f019cb91057b8981f133f7b707cb2246e26b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20K=C3=B6hler?= Date: Fri, 17 Sep 2010 16:44:48 +0200 Subject: [PATCH 64/85] Add missing needdb check in mod_privacy, to enable blocking by group and subscription again. --- src/mod_privacy.erl | 3 ++- src/mod_privacy_odbc.erl | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/mod_privacy.erl b/src/mod_privacy.erl index 0c9d089e0..d25bc9b7b 100644 --- a/src/mod_privacy.erl +++ b/src/mod_privacy.erl @@ -392,12 +392,13 @@ process_list_set(LUser, LServer, {value, Name}, Els) -> {atomic, {error, _} = Error} -> Error; {atomic, {result, _} = Res} -> + NeedDb = is_list_needdb(List), ejabberd_router:route( jlib:make_jid(LUser, LServer, ""), jlib:make_jid(LUser, LServer, ""), {xmlelement, "broadcast", [], [{privacy_list, - #userlist{name = Name, list = List}, + #userlist{name = Name, list = List, needdb = NeedDb}, Name}]}), Res; _ -> diff --git a/src/mod_privacy_odbc.erl b/src/mod_privacy_odbc.erl index 5ad2fb958..593e99140 100644 --- a/src/mod_privacy_odbc.erl +++ b/src/mod_privacy_odbc.erl @@ -392,12 +392,13 @@ process_list_set(LUser, LServer, {value, Name}, Els) -> {atomic, {error, _} = Error} -> Error; {atomic, {result, _} = Res} -> + NeedDb = is_list_needdb(List), ejabberd_router:route( jlib:make_jid(LUser, LServer, ""), jlib:make_jid(LUser, LServer, ""), {xmlelement, "broadcast", [], [{privacy_list, - #userlist{name = Name, list = List}, + #userlist{name = Name, list = List, needdb = NeedDb}, Name}]}), Res; _ -> From 191cd2af3c29bb7a82cb0a5ce87f5da0b1cfbc69 Mon Sep 17 00:00:00 2001 From: Evgeniy Khramtsov Date: Tue, 21 Sep 2010 03:17:52 +1000 Subject: [PATCH 65/85] different hooks should be called for session migration and session close --- src/ejabberd_auth_anonymous.erl | 7 +++++++ src/ejabberd_c2s.erl | 8 ++++---- src/ejabberd_sm.erl | 17 ++++++++++++++--- src/mod_ping.erl | 4 ++++ 4 files changed, 29 insertions(+), 7 deletions(-) diff --git a/src/ejabberd_auth_anonymous.erl b/src/ejabberd_auth_anonymous.erl index 1e6a81f22..07eafd7b5 100644 --- a/src/ejabberd_auth_anonymous.erl +++ b/src/ejabberd_auth_anonymous.erl @@ -34,6 +34,7 @@ anonymous_user_exist/2, allow_multiple_connections/1, register_connection/3, + unregister_migrated_connection/3, unregister_connection/3 ]). @@ -69,6 +70,8 @@ start(Host) -> %% The hooks are needed to add / remove users from the anonymous tables ejabberd_hooks:add(sm_register_connection_hook, Host, ?MODULE, register_connection, 100), + ejabberd_hooks:add(sm_remove_migrated_connection_hook, Host, + ?MODULE, unregister_migrated_connection, 100), ejabberd_hooks:add(sm_remove_connection_hook, Host, ?MODULE, unregister_connection, 100), ok. @@ -159,6 +162,10 @@ unregister_connection(SID, #jid{luser = LUser, lserver = LServer}, _) -> LUser, LServer), remove_connection(SID, LUser, LServer). +%% Remove an anonymous user from the anonymous users table +unregister_migrated_connection(SID, #jid{luser = LUser, lserver = LServer}, _) -> + remove_connection(SID, LUser, LServer). + %% Launch the hook to purge user data only for anonymous users purge_hook(false, _LUser, _LServer) -> ok; diff --git a/src/ejabberd_c2s.erl b/src/ejabberd_c2s.erl index da62f085b..69da0f6a5 100644 --- a/src/ejabberd_c2s.erl +++ b/src/ejabberd_c2s.erl @@ -1613,10 +1613,10 @@ terminate({migrated, ClonePid}, StateName, StateData) -> [StateData#state.socket, jlib:jid_to_string(StateData#state.jid), ClonePid, node(ClonePid)]), - ejabberd_sm:close_session(StateData#state.sid, - StateData#state.user, - StateData#state.server, - StateData#state.resource); + ejabberd_sm:close_migrated_session(StateData#state.sid, + StateData#state.user, + StateData#state.server, + StateData#state.resource); true -> ok end, diff --git a/src/ejabberd_sm.erl b/src/ejabberd_sm.erl index fc7d8802d..e98ccf338 100644 --- a/src/ejabberd_sm.erl +++ b/src/ejabberd_sm.erl @@ -36,6 +36,7 @@ open_session/5, open_session/6, close_session/4, + close_migrated_session/4, check_in_subscription/6, bounce_offline_message/3, disconnect_removed_user/2, @@ -106,6 +107,18 @@ open_session(SID, User, Server, Resource, Priority, Info) -> [SID, JID, Info]). close_session(SID, User, Server, Resource) -> + Info = do_close_session(SID, User, Server, Resource), + JID = jlib:make_jid(User, Server, Resource), + ejabberd_hooks:run(sm_remove_connection_hook, JID#jid.lserver, + [SID, JID, Info]). + +close_migrated_session(SID, User, Server, Resource) -> + Info = do_close_session(SID, User, Server, Resource), + JID = jlib:make_jid(User, Server, Resource), + ejabberd_hooks:run(sm_remove_migrated_connection_hook, JID#jid.lserver, + [SID, JID, Info]). + +do_close_session(SID, User, Server, Resource) -> Info = case mnesia:dirty_read({session, SID}) of [] -> []; [#session{info=I}] -> I @@ -114,9 +127,7 @@ close_session(SID, User, Server, Resource) -> mnesia:delete({session, SID}) end, mnesia:sync_dirty(F), - JID = jlib:make_jid(User, Server, Resource), - ejabberd_hooks:run(sm_remove_connection_hook, JID#jid.lserver, - [SID, JID, Info]). + Info. check_in_subscription(Acc, User, Server, _JID, _Type, _Reason) -> case ejabberd_auth:is_user_exists(User, Server) of diff --git a/src/mod_ping.erl b/src/mod_ping.erl index 37b06dc98..a650f983e 100644 --- a/src/mod_ping.erl +++ b/src/mod_ping.erl @@ -107,6 +107,8 @@ init([Host, Opts]) -> ?MODULE, user_online, 100), ejabberd_hooks:add(sm_remove_connection_hook, Host, ?MODULE, user_offline, 100), + ejabberd_hooks:add(sm_remove_migrated_connection_hook, Host, + ?MODULE, user_offline, 100), ejabberd_hooks:add(user_send_packet, Host, ?MODULE, user_send, 100); _ -> @@ -121,6 +123,8 @@ init([Host, Opts]) -> terminate(_Reason, #state{host = Host}) -> ejabberd_hooks:delete(sm_remove_connection_hook, Host, ?MODULE, user_offline, 100), + ejabberd_hooks:delete(sm_remove_migrated_connection_hook, Host, + ?MODULE, user_offline, 100), ejabberd_hooks:delete(sm_register_connection_hook, Host, ?MODULE, user_online, 100), ejabberd_hooks:delete(user_send_packet, Host, From 8e5297f4c3c372876270bd616c5ab03689bae456 Mon Sep 17 00:00:00 2001 From: Evgeniy Khramtsov Date: Tue, 21 Sep 2010 04:31:18 +1000 Subject: [PATCH 66/85] fixes default value for cache_life_time --- src/mod_caps.erl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/mod_caps.erl b/src/mod_caps.erl index 01056fbe5..319e37e6c 100644 --- a/src/mod_caps.erl +++ b/src/mod_caps.erl @@ -212,7 +212,7 @@ init([Host, Opts]) -> {attributes, record_info(fields, caps_features)}]), mnesia:add_table_copy(caps_features, node(), disc_only_copies), MaxSize = gen_mod:get_opt(cache_size, Opts, 1000), - LifeTime = gen_mod:get_opt(cache_life_time, Opts, timer:hours(24)), + LifeTime = gen_mod:get_opt(cache_life_time, Opts, timer:hours(24) div 1000), cache_tab:new(caps_features, [{max_size, MaxSize}, {life_time, LifeTime}]), ejabberd_hooks:add(user_send_packet, Host, ?MODULE, user_send_packet, 75), From a5813b798fab13d90a9058ab20aa384e9cb4f663 Mon Sep 17 00:00:00 2001 From: Alexey Shchepin Date: Tue, 14 Sep 2010 18:00:01 +0300 Subject: [PATCH 67/85] Fixed "sender" log field --- src/mod_applepush.erl | 5 ++++- src/mod_applepush_service.erl | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/mod_applepush.erl b/src/mod_applepush.erl index 18b8dd2b0..5e97f6165 100644 --- a/src/mod_applepush.erl +++ b/src/mod_applepush.erl @@ -215,6 +215,7 @@ receive_offline_packet(From, To, Packet) -> end, Badge = integer_to_list(Offline + 1), DeviceID = erlang:integer_to_list(ID, 16), + STo = jlib:jid_to_string(To), Packet1 = {xmlelement, "message", [], [{xmlelement, "push", [{"xmlns", ?NS_P1_PUSH}], @@ -227,7 +228,9 @@ receive_offline_packet(From, To, Packet) -> {xmlelement, "sound", [], [{xmlcdata, SSound}]}, {xmlelement, "from", [], - [{xmlcdata, SFrom}]}]}]}, + [{xmlcdata, SFrom}]}, + {xmlelement, "to", [], + [{xmlcdata, STo}]}]}]}, ejabberd_router:route(To, ServiceJID, Packet1) end end; diff --git a/src/mod_applepush_service.erl b/src/mod_applepush_service.erl index b2d3251ac..425da7aac 100644 --- a/src/mod_applepush_service.erl +++ b/src/mod_applepush_service.erl @@ -370,7 +370,7 @@ handle_message(From, To, Packet, State) -> "Device ID: ~s~n", [State#state.host, erlang:integer_to_list(ID, 16), Notification, Payload, - jlib:jid_to_string(From), + Sender, Receiver, DeviceID]), case ssl:send(State#state.socket, Notification) of ok -> From cac23c39c9db20e6421cf8903198aab48f104b3b Mon Sep 17 00:00:00 2001 From: Alexey Shchepin Date: Mon, 20 Sep 2010 13:35:42 +0300 Subject: [PATCH 68/85] Disable notifications for a user on "Invalid token" error --- src/mod_applepush_service.erl | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/src/mod_applepush_service.erl b/src/mod_applepush_service.erl index 425da7aac..7c5ab711f 100644 --- a/src/mod_applepush_service.erl +++ b/src/mod_applepush_service.erl @@ -199,14 +199,19 @@ handle_info({ssl, Socket, Packet}, State) case dict:find(CmdID, State#state.cmd_cache) of {ok, {JID, _DeviceID}} -> ?ERROR_MSG("PUSH ERROR for ~p: ~p", [JID, Status]), - %From = jlib:make_jid("", State#state.host, ""), - %ejabberd_router:route( - % From, JID, - % {xmlelement, "message", [], - % [{xmlelement, "disable", - % [{"xmlns", ?NS_P1_PUSH}, - % {"status", integer_to_list(Status)}], - % []}]}); + if + Status == 8 -> + From = jlib:make_jid("", State#state.host, ""), + ejabberd_router:route( + From, JID, + {xmlelement, "message", [], + [{xmlelement, "disable", + [{"xmlns", ?NS_P1_PUSH}, + {"status", integer_to_list(Status)}], + []}]}); + true -> + ok + end, ok; error -> ?ERROR_MSG("Unknown cmd ID ~p~n", [CmdID]), From a894d25b1f838d058c62d489f70abc2e781f2f8a Mon Sep 17 00:00:00 2001 From: Christophe Romain Date: Fri, 24 Sep 2010 16:11:12 +0200 Subject: [PATCH 69/85] s2s and session are no longer part of replication init of joincluster --- tools/joincluster | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tools/joincluster b/tools/joincluster index 03fee9e9f..b6c610231 100755 --- a/tools/joincluster +++ b/tools/joincluster @@ -117,6 +117,10 @@ set_tables([]) -> ok; set_tables([schema | Tables]) -> set_tables(Tables); +set_tables([s2s | Tables]) -> + set_tables(Tables); +set_tables([session | Tables]) -> + set_tables(Tables); set_tables([Table | Tables]) -> set_table_copy(Table, node(), rpc:call('$REMOTE', mnesia, table_info, [Table, storage_type])), From db2baa8f840c67b4f4d10cc1054a8cda62f2cdab Mon Sep 17 00:00:00 2001 From: Christophe Romain Date: Fri, 24 Sep 2010 16:11:39 +0200 Subject: [PATCH 70/85] pubsub clean now cluster aware --- src/mod_pubsub/pubsub_clean.erl | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/mod_pubsub/pubsub_clean.erl b/src/mod_pubsub/pubsub_clean.erl index 579ccc0f1..814cee0fb 100644 --- a/src/mod_pubsub/pubsub_clean.erl +++ b/src/mod_pubsub/pubsub_clean.erl @@ -2,7 +2,7 @@ -define(TIMEOUT, 1000*600). % 1 minute --export([start/0, loop/0, offline/1]). +-export([start/0, loop/0, purge/0, offline/1]). start() -> Pid = spawn(?MODULE, loop, []), @@ -17,7 +17,8 @@ loop() -> loop(). purge() -> - {Sessions, Subscriptions} = {mnesia:table_info(session,size),mnesia:table_info(pubsub_state,size)}, + Sessions = lists:sum([mnesia:table_info(session,size)|[rpc:call(N,mnesia,table_info,[session,size]) || N <- nodes()]]), + Subscriptions = mnesia:table_info(pubsub_state,size), if Subscriptions > Sessions + 500 -> lists:foreach(fun(K) -> [N]=mnesia:dirty_read({pubsub_node, K}), @@ -34,3 +35,4 @@ offline(Jids) -> lists:filter(fun({U,S,""}) -> ejabberd_sm:get_user_resources(U,S) == []; ({U,S,R}) -> not lists:member(R,ejabberd_sm:get_user_resources(U,S)) end, Jids). +%%ejabberd_cluster:get_node({LUser, LServer}) From b6dcd41225ed8cf44bf52ef9cee46e9f597e4cf3 Mon Sep 17 00:00:00 2001 From: Christophe Romain Date: Fri, 24 Sep 2010 16:11:59 +0200 Subject: [PATCH 71/85] added antiflood and filter modules from TeamLeader --- src/floodcheck.erl | 205 +++++++++++++++++++++++++ src/mod_antiflood.erl | 186 ++++++++++++++++++++++ src/mod_filter.erl | 350 ++++++++++++++++++++++++++++++++++++++++++ src/mod_support.erl | 261 +++++++++++++++++++++++++++++++ 4 files changed, 1002 insertions(+) create mode 100644 src/floodcheck.erl create mode 100644 src/mod_antiflood.erl create mode 100644 src/mod_filter.erl create mode 100644 src/mod_support.erl diff --git a/src/floodcheck.erl b/src/floodcheck.erl new file mode 100644 index 000000000..f2a20e46a --- /dev/null +++ b/src/floodcheck.erl @@ -0,0 +1,205 @@ +%%%------------------------------------------------------------------- +%%% File : floodcheck.erl +%%% Author : Christophe Romain +%%% Description : +%%% +%%% Created : 11 Sep 2008 by Christophe Romain +%%%------------------------------------------------------------------- +-module(floodcheck). + +-behaviour(gen_server). + +%% API +-export([start_link/0, stop/0]). +-export([monitor/5, demonitor/1, interval/1, check/0]). + +%% gen_server callbacks +-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). + +-define(DEFAULT_INTERVAL, 300). %% check every 5mn +-define(SERVER, ?MODULE). + +-record(state, {timer, interval, monitors}). +-record(monitor, {id, pid, ref, info, rule, value, handler}). + +%%==================================================================== +%% API +%%==================================================================== +%%-------------------------------------------------------------------- +%% Function: start_link() -> {ok,Pid} | ignore | {error,Error} +%% Description: Starts the server +%%-------------------------------------------------------------------- +start_link() -> + case whereis(?SERVER) of + undefined -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []); + Pid -> {ok, Pid} + end. + +stop() -> + gen_server:call(?SERVER, stop). + +monitor(Id, Pid, Info, Spec, {Mod, Fun}) -> + gen_server:cast(?SERVER, {monitor, Id, Pid, Info, Spec, {Mod, Fun}}). + +demonitor(Id) -> + gen_server:cast(?SERVER, {demonitor, Id}). + +interval(Value) -> + gen_server:cast(?SERVER, {interval, Value}). + +check() -> + gen_server:call(?SERVER, check). + +%%==================================================================== +%% gen_server callbacks +%%==================================================================== + +%%-------------------------------------------------------------------- +%% Function: init(Args) -> {ok, State} | +%% {ok, State, Timeout} | +%% ignore | +%% {stop, Reason} +%% Description: Initiates the server +%%-------------------------------------------------------------------- +init([]) -> + Timer = erlang:send_after(?DEFAULT_INTERVAL*1000, ?SERVER, monitor), + {ok, #state{timer=Timer, interval=?DEFAULT_INTERVAL, monitors=[]}}. + +%%-------------------------------------------------------------------- +%% 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(check, _From, State) -> + Reply = lists:map(fun(#monitor{id=Id}=M) -> + {Id, check(M)} + end, State#state.monitors), + {reply, Reply, State}; +handle_call(stop, _From, State) -> + erlang:cancel_timer(State#state.timer), + {stop, normal, ok, State}. + +%%-------------------------------------------------------------------- +%% Function: handle_cast(Msg, State) -> {noreply, State} | +%% {noreply, State, Timeout} | +%% {stop, Reason, State} +%% Description: Handling cast messages +%%-------------------------------------------------------------------- +handle_cast({monitor, Id, Pid, Info, Spec, Handler}, State) -> + Monitors = State#state.monitors, + Ref = erlang:monitor(process, Pid), + {Rule, Value} = case Spec of + {Op, V} -> {Op, V}; + V -> {'>', V} + end, + Monitor = #monitor{id=Id, pid=Pid, ref=Ref, info=Info, rule=Rule, value=Value, handler=Handler}, + New = case lists:keysearch(Id, #monitor.id, Monitors) of + {value, #monitor{ref=OldRef}} -> + erlang:demonitor(OldRef), + lists:keyreplace(Id, #monitor.id, Monitors, Monitor); + _ -> + [Monitor|Monitors] + end, + {noreply, State#state{monitors=New}}; +handle_cast({demonitor, Id}, State) -> + Monitors = State#state.monitors, + New = case lists:keysearch(Id, #monitor.id, Monitors) of + {value, #monitor{ref=Ref}} -> + erlang:demonitor(Ref), + lists:keydelete(Id, #monitor.id, Monitors); + _ -> + Monitors + end, + {noreply, State#state{monitors=New}}; +handle_cast({interval, Value}, State) -> + erlang:cancel_timer(State#state.timer), + Timer = erlang:send_after(Value*1000, ?SERVER, monitor), + {noreply, State#state{timer=Timer, interval=Value}}; +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({'DOWN', Ref, _Type, _Pid, _Info}, State) -> + Monitors = State#state.monitors, + New = lists:keydelete(Ref, #monitor.ref, Monitors), + {noreply, State#state{monitors=New}}; +handle_info(monitor, State) -> + lists:foreach(fun(#monitor{id=Id, pid=Pid, info=Info, handler={Mod, Fun}}=M) -> + case check(M) of + ok -> ok; + Value -> spawn(Mod, Fun, [Id, Pid, Info, Value]) + end + end, State#state.monitors), + Timer = erlang:send_after(State#state.interval*1000, ?SERVER, monitor), + {noreply, State#state{timer=Timer}}; +handle_info(_Info, State) -> + {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) -> + 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 +%%-------------------------------------------------------------------- + +check(#monitor{pid=Pid, info=Info, rule=Rule, value=Value}) -> + case catch process_info(Pid, Info) of + {Info, Actual} -> + Check = case Info of + messages -> byte_size(term_to_binary(Actual)); + dictionary -> byte_size(term_to_binary(Actual)); + _ -> Actual + end, + case Rule of + '>' -> + if Check > Value -> Value; + true -> ok + end; + '<' -> + if Check < Value -> Value; + true -> ok + end; + '=' -> + if Check == Value -> Value; + true -> ok + end; + _ -> + ok + end; + _ -> + ok + end. + +%%% Documentation +%%% authorized Info +%%% message_queue_len: number of messages +%%% messages: messages queue size in bytes +%%% dictionary: dictionary size in bytes +%%% total_heap_size: total size in words of all heap fragments +%%% heap_size: size in words of youngest heap generation +%%% stack_size: stack size in words +%%% reductions: number of reductions executed by the process +%%% memory: process size in bytes diff --git a/src/mod_antiflood.erl b/src/mod_antiflood.erl new file mode 100644 index 000000000..a80d93636 --- /dev/null +++ b/src/mod_antiflood.erl @@ -0,0 +1,186 @@ +%%%------------------------------------------------------------------- +%%% File : mod_antiflood.erl +%%% Author : Christophe Romain +%%% Description : +%%% Created : 12 Sep 2008 by Christophe Romain +%%% +%%% ejabberd, Copyright (C) 2002-2009 ProcessOne +%%% +%%% This program is free software; you can redistribute it and/or +%%% modify it under the terms of the GNU General Public License as +%%% published by the Free Software Foundation; either version 2 of the +%%% License, or (at your option) any later version. +%%% +%%% This program is distributed in the hope that it will be useful, +%%% but WITHOUT ANY WARRANTY; without even the implied warranty of +%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +%%% General Public License for more details. +%%% +%%% You should have received a copy of the GNU General Public License +%%% along with this program; if not, write to the Free Software +%%% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA +%%% 02111-1307 USA +%%% +%%%------------------------------------------------------------------- +-module(mod_antiflood). +-author('cromain@process-one.net'). + +-behaviour(gen_mod). + +%% API +-export([start/2, stop/1]). +-export([handler/4]). + +-include("ejabberd.hrl"). + +%%==================================================================== +%% API +%%==================================================================== +start(Host, Opts) -> + floodcheck:start_link(), + lists:foreach(fun + ({listeners, Info, Op, Val}) -> + lists:foreach(fun({Name, Pid}) -> + Id = {Name, Info}, + floodcheck:monitor(Id, Pid, Info, {Op, Val}, {?MODULE, handler}) + end, supervised_processes(listeners)); + ({Module, Info, Op, Val}) -> + case module_pid(Host, Module) of + Pid when is_pid(Pid) -> + Id = {Host, Module, Info}, + floodcheck:monitor(Id, Pid, Info, {Op, Val}, {?MODULE, handler}); + Error -> + ?INFO_MSG("can not monitor ~s (~p)", [Module, Error]) + end; + (Arg) -> + ?INFO_MSG("invalid argument: ~p", [Arg]) + end, Opts). + +stop(Host) -> + MList = gen_mod:loaded_modules_with_opts(Host), + case lists:keysearch(?MODULE, 1, MList) of + {value, {?MODULE, Opts}} -> + lists:foreach(fun + ({Type, Info, _, _}) -> + case supervised_processes(Type) of + [] -> + Id = {Host, Type, Info}, + floodcheck:demonitor(Id); + Childs -> + lists:foreach(fun({Name, _}) -> + Id = {Name, Info}, + floodcheck:demonitor(Id) + end, Childs) + end; + (_) -> + ok + end, Opts); + false -> + ok + end, + case floodcheck:check() of + [] -> floodcheck:stop(), ok; + _ -> ok + end. + +handler({Host, Module, Info}, Pid, Info, Value) -> + ?WARNING_MSG("Flood alert on Process ~p (~s on ~s): ~s=~p", [Pid, Module, Host, Info, Value]), + restart_module(Host, Module), + remonitor({Host, Module, Info}); +handler({Name, Info}, Pid, Info, Value) -> + ?WARNING_MSG("Flood alert on Process ~p (~s): ~s=~p", [Pid, Name, Info, Value]), + kill_process(Name, Pid), + remonitor({Name, Info}); +handler(Id, Pid, Info, Value) -> + ?WARNING_MSG("Flood alert on Process ~p (~s): ~s=~p~nUnknown id, alert ignored", [Pid, Id, Info, Value]). + + +%%==================================================================== +%% Internal functions +%%==================================================================== + +process_pid(Name) -> whereis(Name). +server_pid(Host, Name) -> process_pid(gen_mod:get_module_proc(Host, Name)). + +module_pid(Host, mod_caps) -> server_pid(Host, ejabberd_mod_caps); +module_pid(Host, mod_ip_blacklist) -> server_pid(Host, mod_ip_blacklist); +module_pid(Host, mod_offline) -> server_pid(Host, ejabberd_offline); +module_pid(Host, mod_offline_odbc) -> server_pid(Host, ejabberd_offline); +module_pid(Host, mod_vcard) -> server_pid(Host, ejabberd_mod_vcard); +module_pid(Host, mod_vcard_odbc) -> server_pid(Host, ejabberd_mod_vcard); +module_pid(Host, mod_vcard_ldap) -> server_pid(Host, ejabberd_mod_vcard_ldap); +module_pid(Host, mod_irc) -> server_pid(Host, ejabberd_mod_irc); +module_pid(Host, mod_muc) -> server_pid(Host, ejabberd_mod_muc); +module_pid(Host, mod_muc_log) -> server_pid(Host, ejabberd_mod_muc_log); +module_pid(Host, mod_proxy65) -> server_pid(Host, ejabberd_mod_proxy65); +module_pid(Host, mod_proxy65_service) -> server_pid(Host, ejabberd_mod_proxy65_service); +module_pid(Host, mod_proxy65_sm) -> server_pid(Host, ejabberd_mod_proxy65_sm); +module_pid(Host, mod_pubsub) -> server_pid(Host, ejabberd_mod_pubsub); +module_pid(_, _) -> unsupported. + +supervised_processes(listeners) -> + {links, Links} = process_info(whereis(ejabberd_listeners), links), + lists:map(fun(Pid) -> + {dictionary, Dict} = process_info(Pid, dictionary), + {_, _, [Port|_]} = proplists:get_value('$initial_call', Dict), + Name = list_to_atom("listener_"++integer_to_list(Port)), + {Name, Pid} + end, Links); +supervised_processes(_) -> []. + +remonitor({Host, Module, Info}) -> + MList = gen_mod:loaded_modules_with_opts(Host), + case lists:keysearch(?MODULE, 1, MList) of + {value, {?MODULE, Opts}} -> + lists:foreach(fun + ({M, I, Op, Val}) when M =:= Module, I =:= Info -> + case module_pid(Host, Module) of + Pid when is_pid(Pid) -> + Id = {Host, Module, Info}, + floodcheck:monitor(Id, Pid, Info, {Op, Val}, {?MODULE, handler}); + Error -> + ?INFO_MSG("can not monitor ~s (~p)", [Module, Error]) + end; + (_) -> + ok + end, Opts); + _ -> + ok + end; +remonitor({Name, Info}) -> + [Host|_] = ejabberd_config:get_global_option(hosts), + MList = gen_mod:loaded_modules_with_opts(Host), + case lists:keysearch(?MODULE, 1, MList) of + {value, {?MODULE, Opts}} -> + lists:foreach(fun + ({Type, I, Op, Val}) when I =:= Info -> + lists:foreach(fun + ({N, Pid}) when N =:= Name -> + Id = {Name, Info}, + floodcheck:monitor(Id, Pid, Info, {Op, Val}, {?MODULE, handler}); + (_) -> + ok + end, supervised_processes(Type)); + (_) -> + ok + end, Opts); + _ -> + ok + end; +remonitor(Id) -> + ?INFO_MSG("can not monitor ~s", [Id]). + +restart_module(Host, Module) -> + MList = gen_mod:loaded_modules_with_opts(Host), + case lists:keysearch(Module, 1, MList) of + {value, {Module, Opts}} -> + ?WARNING_MSG("restarting module ~s on ~s", [Module, Host]), + gen_mod:stop_module(Host, Module), + gen_mod:start_module(Host, Module, Opts); + _ -> + not_running + end. + +kill_process(Name, Pid) -> + ?WARNING_MSG("killing process ~s(~p)", [Name, Pid]), + exit(Pid, kill). diff --git a/src/mod_filter.erl b/src/mod_filter.erl new file mode 100644 index 000000000..ad42564b3 --- /dev/null +++ b/src/mod_filter.erl @@ -0,0 +1,350 @@ +%%% ==================================================================== +%%% This software is copyright 2006-2009, ProcessOne. +%%% +%%% mod_filter +%%% allow message filtering using regexp on message body +%%% THIS MODULE NEEDS A PATCHED ERLANG VM AGAINST +%%% THE PCRE PATCH AND NEEDS LIBPCRE INSTALLED +%%% ejabberd MUST USE THAT PATCHED ERLANG VM +%%% BUT, if patch is not available, mod_filter uses re.beam module +%%% instead, with speed degradation. +%%% +%%% @copyright 2006-2009 ProcessOne +%%% @author Christophe Romain +%%% [http://www.process-one.net/] +%%% @version {@vsn}, {@date} {@time} +%%% @end +%%% ==================================================================== + +-module(mod_filter). +-author('christophe.romain@process-one.net'). +-vsn('$Id: mod_filter.erl 767 2009-04-20 16:31:40Z cromain $'). + +-behaviour(gen_mod). + +% module functions +-export([start/2,stop/1,init/2,update/2,is_loaded/0,loop/5]). +-export([add_regexp/4,add_regexp/3,del_regexp/3,del_regexp/2]). +-export([purge_logs/0,purge_regexps/1,reload/1]). +-export([logged/0,logged/1,rules/0]). +-export([process_local_iq/3]). + +% handled ejabberd hooks +-export([filter_packet/1]). + +-include("ejabberd.hrl"). +-include("jlib.hrl"). +-include("licence.hrl"). + +-record(filter_rule, {id, type="filter", regexp, binre}). +-record(filter_log, {date, from, to, message}). + +-define(TIMEOUT, 5000). % deliver message anyway if filter does not respond after 5s +-define(PROCNAME(VH), list_to_atom(VH++"_message_filter")). +-define(NS_FILTER, "p1:iq:filter"). + +-define(ALLHOSTS, "all hosts"). %% must be sync with filter.erl + +start(Host, Opts) -> + case ?IS_VALID of + true -> + mnesia:create_table(filter_rule, [ + {disc_copies, [node()]}, {type, set}, + {attributes, record_info(fields, filter_rule)} ]), + mnesia:create_table(filter_log, [ + {disc_only_copies, [node()]}, {type, bag}, + {attributes, record_info(fields, filter_log)} ]), + %% this force the last code to be used + case whereis(?PROCNAME(Host)) of + undefined -> + ok; + _ -> + ejabberd_hooks:delete(filter_packet, ?MODULE, filter_packet, 10), + gen_iq_handler:remove_iq_handler(ejabberd_local, Host, ?NS_FILTER), + ?PROCNAME(Host) ! quit + end, + ejabberd_hooks:add(filter_packet, ?MODULE, filter_packet, 10), + gen_iq_handler:add_iq_handler(ejabberd_local, Host, ?NS_FILTER, + ?MODULE, process_local_iq, one_queue), + case whereis(?PROCNAME(Host)) of + undefined -> register(?PROCNAME(Host), spawn(?MODULE, init, [Host, Opts])); + _ -> ok + end, + %% start the all_alias handler + case whereis(?PROCNAME(?ALLHOSTS)) of + undefined -> init_all_hosts_handler(); + _ -> ok + end, + start; + false -> + not_started + end. + +stop(Host) -> + ejabberd_hooks:delete(filter_packet, ?MODULE, filter_packet, 10), + gen_iq_handler:remove_iq_handler(ejabberd_local, Host, ?NS_FILTER), + exit(whereis(?PROCNAME(Host)), kill), + {wait, ?PROCNAME(Host)}. + +% this is used by team_leader to check code presence +is_loaded() -> + ok. + +% this loads rules and return {Types, BinRegExps} +% RegExps are text regexp list +% Types are regexp type list +% both list share the same ordered +load_rules(Host) -> + Rules = mnesia:dirty_match_object(#filter_rule{id={'_', Host}, _ = '_'}) + ++ mnesia:dirty_match_object(#filter_rule{id={'_', ?ALLHOSTS}, _ = '_'}), + lists:map(fun({filter_rule, _, Type, _, BinRegExp}) -> {Type, BinRegExp} end, Rules). + %lists:unzip(Config). + +% this call init or reset local rules reading database +init(Host, Opts) -> + Rules = load_rules(Host), + Scope = gen_mod:get_opt(scope, Opts, message), + Pattern = gen_mod:get_opt(pattern, Opts, ""), + ?MODULE:loop(Host, Opts, Rules, Scope, Pattern). + +init_all_hosts_handler() -> + register(?PROCNAME(?ALLHOSTS), spawn(?MODULE, loop, [?ALLHOSTS, [], [], none, []])). + +% this call reset local rules reading database +% and tell other nodes to reset rules as well +update(?ALLHOSTS, _Opts) -> + lists:foreach(fun(Host) -> + lists:foreach(fun(Node) -> + catch rpc:call(Node,mod_filter,reload,[Host]) + end, mnesia:system_info(running_db_nodes)) + end, ejabberd_config:get_global_option(hosts)), + ?MODULE:loop(?ALLHOSTS, [], [], none, []); +update(Host, Opts) -> + % tell other nodes to update filter + lists:foreach(fun(Node) -> + catch rpc:call(Node,mod_filter,reload,[Host]) + end, mnesia:system_info(running_db_nodes)--[node()]), + % update rules + init(Host, Opts). + +loop(Host, Opts, Rules, Scope, Pattern) -> + receive + {add, Id, RegExp} -> + [BinRegExp] = tlre:compile([RegExp]), + mnesia:dirty_write(#filter_rule{id={Id, Host}, regexp=RegExp, binre=BinRegExp}), + ?MODULE:update(Host, Opts); + {add, Id, RegExp, Type} -> + [BinRegExp] = tlre:compile([RegExp]), + mnesia:dirty_write(#filter_rule{id={Id, Host}, regexp=RegExp, binre=BinRegExp, type=Type}), + ?MODULE:update(Host, Opts); + {del, Id} -> + mnesia:dirty_delete_object(#filter_rule{id={Id, Host}, _='_'}), + ?MODULE:update(Host, Opts); + {del, Id, RegExp} -> + mnesia:dirty_delete_object(#filter_rule{id={Id, Host}, regexp=RegExp, _='_'}), + ?MODULE:update(Host, Opts); + {match, From, String} -> + From ! {match, string_filter(String, Rules, Scope, Pattern)}, + ?MODULE:loop(Host, Opts, Rules, Scope, Pattern); + reload -> + ?MODULE:init(Host, Opts); + quit -> + unregister(?PROCNAME(Host)), + ok + end. + +string_filter(String, Rules, Scope, Pattern) -> + lists:foldl(fun + (_, {Pass, []}) -> {Pass, []}; + ({Type, RegExp}, {Pass, NewString}) -> string_filter(NewString, Pass, RegExp, Type, Scope, Pattern) + end, {"pass", String}, Rules). +string_filter(String, Pass, RegExp, Type, Scope, Pattern) -> + case tlre:grep(String, [RegExp]) of + [no_match] -> + {Pass, String}; + [{S1, S2, _}] -> + case Scope of + word -> + Start = string:sub_string(String, 1, S1), + StringTail = string:sub_string(String, S2+1, length(String)), + NewPass = pass_rule(Pass, Type), + {LastPass, End} = string_filter(StringTail, NewPass, RegExp, Type, Scope, Pattern), + NewString = case Type of + "log" -> lists:append([string:sub_string(String, 1, S2), End]); + _ -> lists:append([Start, Pattern, End]) + end, + {LastPass, NewString}; + _ -> + NewString = case Type of + "log" -> String; + _ -> [] + end, + {pass_rule(Pass, Type), NewString} + end + end. + +pass_rule("pass", New) -> New; +pass_rule("log", "log") -> "log"; +pass_rule("log", "log and filter") -> "log and filter"; +pass_rule("log", "filter") -> "log and filter"; +pass_rule("filter", "log") -> "log and filter"; +pass_rule("filter", "log and filter") -> "log and filter"; +pass_rule("filter", "filter") -> "filter"; +pass_rule("log and filter", _) -> "log and filter". + +add_regexp(VH, Id, RegExp) -> + ?PROCNAME(VH) ! {add, Id, RegExp}, + ok. + +add_regexp(VH, Id, RegExp, Type) -> + ?PROCNAME(VH) ! {add, Id, RegExp, Type}, + ok. + +del_regexp(VH, Id) -> + ?PROCNAME(VH) ! {del, Id}, + ok. + +del_regexp(VH, Id, RegExp) -> + ?PROCNAME(VH) ! {del, Id, RegExp}, + ok. + +reload(VH) -> + ?PROCNAME(VH) ! reload, + ok. + +purge_logs() -> + mnesia:dirty_delete_object(#filter_log{_='_'}). + +%purge_regexps() -> +% mnesia:dirty_delete_object(#filter_rule{_='_'}), +% reload(). + +purge_regexps(VH) -> + mnesia:dirty_delete_object(#filter_rule{id={'_', VH}, _='_'}), + reload(VH). + +rules() -> + lists:map(fun(#filter_rule{id={Label, VH}, type=Type, regexp=Regexp}) -> + {VH, Label, Type, Regexp} + end, mnesia:dirty_match_object(#filter_rule{_='_'})). + +logged() -> + lists:reverse(lists:map(fun(#filter_log{date=Date, from=From, to=To, message=Msg}) -> + {Date, jlib:jid_to_string(From), jlib:jid_to_string(To), Msg} + end, mnesia:dirty_match_object(#filter_log{_='_'}))). + +logged(Limit) -> + List = mnesia:dirty_match_object(#filter_log{_='_'}), + Len = length(List), + FinalList = if + Len < Limit -> List; + true -> lists:nthtail(Len-Limit, List) + end, + lists:reverse(lists:map(fun(#filter_log{date=Date, from=From, to=To, message=Msg}) -> + {Date, jlib:jid_to_string(From), jlib:jid_to_string(To), Msg} + end, FinalList)). + +%% filter_packet can receive drop if a previous filter already dropped +%% the packet +filter_packet(drop) -> drop; +filter_packet({From, To, Packet}) -> + case Packet of + {xmlelement, "message", MsgAttrs, Els} -> + case lists:keysearch("body", 2, Els) of + {value, {xmlelement, "body", BodyAttrs, Data}} -> + NewData = lists:foldl(fun + ({xmlcdata, CData}, DataAcc) when is_binary(CData) -> + #jid{lserver = Host} = To, + case lists:member(Host, ejabberd_config:get_global_option(hosts)) of + true -> + Msg = binary_to_list(CData), + ?PROCNAME(Host) ! {match, self(), Msg}, + receive + {match, {"pass", _}} -> + [{xmlcdata, CData}|DataAcc]; + {match, {"log", FinalString}} -> + mnesia:dirty_write(#filter_log{ + date=erlang:localtime(), + from=From, to=To, message=Msg}), + [{xmlcdata, CData}|DataAcc]; + {match, {"log and filter", FinalString}} -> + mnesia:dirty_write(#filter_log{ + date=erlang:localtime(), + from=From, to=To, message=Msg}), + case FinalString of + [] -> % entire message is dropped + DataAcc; + S -> % message must be regenerated + [{xmlcdata, list_to_binary(S)}|DataAcc] + end; + {match, {"filter", FinalString}} -> + case FinalString of + [] -> % entire message is dropped + DataAcc; + S -> % message must be regenerated + [{xmlcdata, list_to_binary(S)}|DataAcc] + end + after ?TIMEOUT -> + [{xmlcdata, CData}|DataAcc] + end; + false -> + [{xmlcdata, CData}|DataAcc] + end; + (Item, DataAcc) -> %% to not filter internal messages + [Item|DataAcc] + end, [], Data), + case NewData of + [] -> + drop; + D -> + NewEls = lists:keyreplace("body", 2, Els, {xmlelement, "body", BodyAttrs, lists:reverse(D)}), + {From, To, {xmlelement, "message", MsgAttrs, NewEls}} + end; + _ -> + {From, To, Packet} + end; + _ -> + {From, To, Packet} + end. + +process_local_iq(From, #jid{lserver=VH} = _To, #iq{type = Type, sub_el = SubEl} = IQ) -> + case Type of + get -> + IQ#iq{type = error, sub_el = [SubEl, ?ERR_NOT_ALLOWED]}; + set -> + #jid{luser = User, lserver = Server, lresource = Resource} = From, + case acl:match_rule(global, configure, {User, Server, Resource}) of + allow -> + case xml:get_subtag(SubEl, "add") of + {xmlelement, "add", AddAttrs, _} -> + AID = xml:get_attr_s("id", AddAttrs), + ARE = xml:get_attr_s("re", AddAttrs), + case xml:get_attr_s("type", AddAttrs) of + "" -> add_regexp(VH, AID, ARE); + ATP -> add_regexp(VH, AID, ARE, ATP) + end; + _ -> ok + end, + case xml:get_subtag(SubEl, "del") of + {xmlelement, "del", DelAttrs, _} -> + DID = xml:get_attr_s("id", DelAttrs), + case xml:get_attr_s("re", DelAttrs) of + "" -> del_regexp(VH, DID); + DRE -> del_regexp(VH, DID, DRE) + end; + _ -> ok + end, + case xml:get_subtag(SubEl, "dellogs") of + {xmlelement, "dellogs", _, _} -> purge_logs(); + _ -> ok + end, + case xml:get_subtag(SubEl, "delrules") of + {xmlelement, "delrules", _, _} -> purge_regexps(VH); + _ -> ok + end, + IQ#iq{type = result, sub_el = []}; + _ -> + IQ#iq{type = error, sub_el = [SubEl, ?ERR_NOT_ALLOWED]} + end + end. + diff --git a/src/mod_support.erl b/src/mod_support.erl new file mode 100644 index 000000000..de1c7ba65 --- /dev/null +++ b/src/mod_support.erl @@ -0,0 +1,261 @@ +%%% ==================================================================== +%%% This software is copyright 2006-2009, ProcessOne. +%%% +%%% mod_support +%%% allow automatic build of support archive to be sent to Process-One +%%% +%%% @copyright 2006-2009 ProcessOne +%%% @author Christophe Romain +%%% [http://www.process-one.net/] +%%% @version {@vsn}, {@date} {@time} +%%% @end +%%% ==================================================================== + + +-module(mod_support). +-author('christophe.romain@process-one.net'). +-vsn('$Id: mod_support.erl 856 2009-09-21 18:46:38Z jpcarlino $'). + +-behaviour(gen_mod). +%-behaviour(gen_server). + +% module functions +-export([start/2,stop/1,is_loaded/0,loop/1,dump/0]). +-compile(export_all). + +-include("ejabberd.hrl"). +-include("jlib.hrl"). +-include("licence.hrl"). + +-include_lib("kernel/include/file.hrl"). + +-define(LOG_FETCH_SIZE, 1000000). +-define(RPC_TIMEOUT, 10000). % 10 +-define(MAX_FILE_SIZE, 2147483648). %%2Gb + +start(Host, Opts) -> + case ?IS_VALID of + true -> + case gen_mod:get_opt(dump_freq, Opts, 0) of + 0 -> no_dump; + Freq -> spawn(?MODULE, loop, [Freq*60000]) + end, + ok; + false -> + not_started + end. + +stop(Host) -> + ok. + +is_loaded() -> + ok. + +loop(Timeout) -> + receive + quit -> ok + after Timeout -> + Dump = dump(), + BaseName = get_base_name(), + %%{Data,EjabberdLog,SaslLog,ECrash} = Dump, + write_logs(tuple_to_list(Dump),BaseName,["_memory.bin", + "_ejabberd.log.gz", + "_sasl.log.gz", + "_erlang_crash_dump.log.gz"]), + loop(Timeout) + end. + +get_base_name() -> + {{Y,M,D},{Hr,Mn,_Sc}} = calendar:local_time(), + case os:getenv("EJABBERD_LOG_PATH") of + false -> + filename:join(filename:dirname(filename:absname("")), + lists:flatten(io_lib:format("~b~b~b~b~b",[Y,M,D,Hr,Mn]))); + Path -> + filename:join(filename:dirname(Path), + lists:flatten(io_lib:format("~b~b~b~b~b",[Y,M,D,Hr,Mn]))) + end. + +write_logs([BinaryData|T],BaseName,[Filename|Filenames]) -> + Log = BaseName++Filename, + file:write_file(Log, BinaryData), + write_logs(T,BaseName,Filenames); + +write_logs([],BaseName,_)-> ok. + +dump() -> + Dump = lists:map(fun(LogFile) -> + Content = case file:open(LogFile,[read,raw]) of + {ok, IO} -> + Size = case file:read_file_info(LogFile) of + {ok, FileInfo} -> FileInfo#file_info.size; + _ -> ?LOG_FETCH_SIZE + end, + case Size>?MAX_FILE_SIZE of + true -> io_lib:format("File ~s is too big: ~p bytes.",[LogFile, Size]); + false -> + if Size>?LOG_FETCH_SIZE -> + file:position(IO, Size-?LOG_FETCH_SIZE), + case file:read(IO, ?LOG_FETCH_SIZE) of + {ok, Data1} -> Data1; + Error1 -> io_lib:format("can not read log file (~s): ~p",[LogFile, Error1]) + end; + true -> + case file:read(IO, Size) of + {ok, Data2} -> Data2; + Error2 -> io_lib:format("can not read log file (~s): ~p",[LogFile, Error2]) + end + end + end; + {error, Reason} -> + io_lib:format("can not open log file (~s): ~p",[LogFile, Reason]) + end, + zlib:gzip(list_to_binary(Content)) + end, [ejabberd_logs(), sasl_logs(), erl_crash()]), + NodeState = get_node_state(), + list_to_tuple([NodeState|Dump]). + +ejabberd_logs() -> + LogPath = case application:get_env(log_path) of + {ok, Path} -> + Path; + undefined -> + case os:getenv("EJABBERD_LOG_PATH") of + false -> ?LOG_PATH; + Path -> Path + end + end. + +sasl_logs() -> + case os:getenv("SASL_LOG_PATH") of + false -> filename:join([filename:dirname(ejabberd_logs()),"sasl.log"]); + Path -> Path + end. + +erl_crash() -> + LogsDir = filename:dirname(ejabberd_logs()), + CrashDumpWildcard = filename:join([LogsDir,"erl_crash*dump"]), + FileName = case filelib:wildcard(CrashDumpWildcard) of + [Files] -> [LastFile|T] = lists:reverse([Files]), + LastFile; + _ -> case os:getenv("ERL_CRASH_DUMP") of + false -> "erl_crash.dump"; + Path -> Path + end + end. + + +proc_info(Pid) -> + Info = process_info(Pid), + lists:map(fun(Elem) -> + List = proplists:get_value(Elem, Info), + {Elem, size(term_to_binary(List))} + end, [messages, dictionary]) + ++ [X || X <- Info, + lists:member(element(1,X), + [heap_size,stack_size,reductions,links,status,initial_call,current_function])]. + +environment() -> + {ok, KE} = application:get_key(kernel,env), + {ok, EE} = application:get_key(ejabberd,env), + Env = [{inetrc, os:getenv("ERL_INETRC")}, + {sopath, os:getenv("EJABBERD_SO_PATH")}, + {maxports, os:getenv("ERL_MAX_PORTS")}, + {maxtables, os:getenv("ERL_MAX_ETS_TABLES")}, + {crashdump, os:getenv("ERL_CRASH_DUMP")}, + {archdir, os:getenv("ARCHDIR")}, + {mnesia, mnesia:system_info(all)}], + Args = [{args, init:get_arguments()}, {plain, init:get_plain_arguments()}], + KE++EE++Env++Args. + +memtop(N) -> + E = lists:sublist(lists:reverse(lists:keysort(2,lists:map(fun(Tab) -> {Tab, ets:info(Tab,memory)} end, ets:all()))),N), + M = lists:sublist(lists:reverse(lists:keysort(2,lists:map(fun(Tab) -> {Tab, mnesia:table_info(Tab,memory)} end, mnesia:system_info(tables)))),N), + E++M. + +maxmsgqueue() -> + lists:max(lists:map(fun(Pid) -> proplists:get_value(message_queue_len,process_info(Pid)) end, erlang:processes())). + +msgqueue(N) -> + lists:filter(fun(L) -> proplists:get_value(message_queue_len, L) > N + end, lists:map(fun(Pid) -> process_info(Pid) end, erlang:processes())). + +%lists:sublist(lists:reverse(lists:keysort(2,lists:map(fun(Pid) -> {E,L} = process_info(Pid, dictionary), {E,length(L)} end, erlang:processes()))), 10) + +%%Entry point to invoke mod_support via command line. +%%Example: erl -sname debug@localhost -s mod_support report ejabberd@localhost +%%See issue #TECH-286. +report(Node) -> + [NodeId|T]=Node, + UploadResult = force_load_code_into_node(NodeId, ?MODULE), + case UploadResult of + ok -> NodeState = rpc:call(NodeId,mod_support,get_node_state,[],?RPC_TIMEOUT), + Dump = rpc:call(NodeId,mod_support,dump,[],?RPC_TIMEOUT), + BaseName = get_base_name(), + %%{Data,EjabberdLog,SaslLog,ECrash} = Dump, + write_logs(tuple_to_list(Dump),BaseName,["_memory.bin", + "_ejabberd.log.gz", + "_sasl.log.gz", + "_erlang_crash_dump.log.gz"]), + error_logger:info_msg("State in node ~p was written to log~n",[NodeId]), + error_logger:info_msg("Unloading module ~s from node ~p. ",[?MODULE,NodeId]), + force_unload_code_from_node(NodeId, ?MODULE); + _ -> error_logger:info_msg("Error uploading module ~s from node ~p~n",[?MODULE,NodeId]) + end. + +%%Load Module into the ejabberd Node specified. +force_load_code_into_node(Node, Module) -> + CodeFile = code:where_is_file(atom_to_list(Module)++".beam"), + case file:read_file(CodeFile) of + {ok, Code} -> + rpc:call(Node, code, purge, [Module], ?RPC_TIMEOUT), + rpc:call(Node, code, delete, [Module], ?RPC_TIMEOUT), + case rpc:call(Node, code, load_binary, [Module, CodeFile, Code], ?RPC_TIMEOUT) of + {module, _} -> + error_logger:info_msg("Loading ~s module into ~p : success ~n", [Module,Node]), + rpc:block_call(Node, Module, is_loaded, [], ?RPC_TIMEOUT); + {error, badfile} -> + error_logger:info_msg("Loading ~s module into ~p : incorrect format ~n", [Module,Node]), + {error, badfile}; + {error, not_purged} -> + % this should never happen anyway.. + error_logger:info_msg("Loading ~s module into ~p : old code already exists ~n", [Module,Node]), + {error, not_purged}; + {badrpc, Reason} -> + error_logger:info_msg("Loading ~s module into ~p: badrpc ~p ~n", [Module,Node,Reason]), + {badrpc, Reason} + end; + Error -> + error_logger:error_msg("Cannot read module file ~s ~p : ~p ~n", [Module, CodeFile, Error]), + Error + end. + +%%Unload erlang Module from the Node specified. Used to ensure cleanup after rpc calls. +force_unload_code_from_node(Node, Module) -> + rpc:call(Node, code, purge, [Module], ?RPC_TIMEOUT), + rpc:call(Node, code, delete, [Module], ?RPC_TIMEOUT). + +%%Retrieve system state and pack it into Data +%%TODO enhance state info. See #TECH-286. +get_node_state() -> + Mem = erlang:memory(), + Ets = lists:map(fun(Tab) -> ets:info(Tab) end, ets:all()), + Mnesia = lists:map(fun(Tab) -> mnesia:table_info(Tab,all) end, mnesia:system_info(tables)), + Procs = lists:map(fun(Pid) -> proc_info(Pid) end, erlang:processes()), + Data = term_to_binary({Mem, Ets, Mnesia, Procs}). + +crash_dump() -> + SystemInfo = [erlang:system_info(X) || X<-[info,loaded,procs]], + [zlib:gzip(list_to_binary(lists:flatten(SystemInfo)))]. + +crash_dump(Node) -> + [NodeId|T]=Node, + UploadResult = force_load_code_into_node(NodeId, ?MODULE), + case UploadResult of + ok -> Dump = rpc:call(NodeId,mod_support,crash_dump,[],?RPC_TIMEOUT), + BaseName = get_base_name(), + write_logs(Dump,BaseName,["_realtime_crash_dump.gz"]), + error_logger:info_msg("Unloading module ~s from node ~p. ",[?MODULE,NodeId]), + force_unload_code_from_node(NodeId, ?MODULE); + _ -> error_logger:info_msg("Error uploading module ~s from node ~p~n",[?MODULE,NodeId]) + end. From 1f2c9b7971a046925013efe1ca1343a8669157a4 Mon Sep 17 00:00:00 2001 From: Evgeniy Khramtsov Date: Tue, 28 Sep 2010 14:20:02 +1000 Subject: [PATCH 72/85] fixes typo in stop_connection/1 --- src/ejabberd_s2s_out.erl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ejabberd_s2s_out.erl b/src/ejabberd_s2s_out.erl index a1c641280..7cfb68d7a 100644 --- a/src/ejabberd_s2s_out.erl +++ b/src/ejabberd_s2s_out.erl @@ -136,7 +136,7 @@ start_connection(Pid) -> p1_fsm:send_event(Pid, init). stop_connection(Pid) -> - p1_fsm:send_event(Pid, stop). + p1_fsm:send_event(Pid, closed). %%%---------------------------------------------------------------------- %%% Callback functions from p1_fsm From f81473fc65b4caed47c34afecd52350b9a2ae471 Mon Sep 17 00:00:00 2001 From: Christophe Romain Date: Tue, 28 Sep 2010 13:36:16 +0200 Subject: [PATCH 73/85] fix licence issue and (c) to 2010 --- src/licence.hrl | 1 + src/mod_admin_p1.erl | 2 +- src/mod_antiflood.erl | 2 +- src/mod_autofilter.erl | 127 +++++++++++++++++++++++++++++++++++++++++ src/mod_filter.erl | 5 +- src/mod_support.erl | 5 +- 6 files changed, 134 insertions(+), 8 deletions(-) create mode 100644 src/licence.hrl create mode 100644 src/mod_autofilter.erl diff --git a/src/licence.hrl b/src/licence.hrl new file mode 100644 index 000000000..a82dab15e --- /dev/null +++ b/src/licence.hrl @@ -0,0 +1 @@ +-define(IS_VALID, true). diff --git a/src/mod_admin_p1.erl b/src/mod_admin_p1.erl index bcfc8232c..18e391027 100644 --- a/src/mod_admin_p1.erl +++ b/src/mod_admin_p1.erl @@ -5,7 +5,7 @@ %%% Created : 21 May 2008 by Badlop %%% %%% -%%% ejabberd, Copyright (C) 2002-2008 ProcessOne +%%% ejabberd, Copyright (C) 2002-2010 ProcessOne %%% %%% This program is free software; you can redistribute it and/or %%% modify it under the terms of the GNU General Public License as diff --git a/src/mod_antiflood.erl b/src/mod_antiflood.erl index a80d93636..aca0737eb 100644 --- a/src/mod_antiflood.erl +++ b/src/mod_antiflood.erl @@ -4,7 +4,7 @@ %%% Description : %%% Created : 12 Sep 2008 by Christophe Romain %%% -%%% ejabberd, Copyright (C) 2002-2009 ProcessOne +%%% ejabberd, Copyright (C) 2002-2010 ProcessOne %%% %%% This program is free software; you can redistribute it and/or %%% modify it under the terms of the GNU General Public License as diff --git a/src/mod_autofilter.erl b/src/mod_autofilter.erl new file mode 100644 index 000000000..97b374b6b --- /dev/null +++ b/src/mod_autofilter.erl @@ -0,0 +1,127 @@ +%%% ==================================================================== +%%% This software is copyright 2006-2010, ProcessOne. +%%% +%%% mod_autofilter +%%% +%%% @copyright 2006-2010 ProcessOne +%%% @author Christophe Romain +%%% [http://www.process-one.net/] +%%% @version {@vsn}, {@date} {@time} +%%% @end +%%% ==================================================================== + + +-module(mod_autofilter). +-author('christophe.romain@process-one.net'). + +-behaviour(gen_mod). + +% module functions +-export([start/2,stop/1,is_loaded/0]). +-export([offline_message/3,filter_packet/1,close_session/2,close_session/3]). +-export([deny/2,allow/2,denied/0,listed/0,purge/1]). + +-include("ejabberd.hrl"). +-include("jlib.hrl"). +-include("licence.hrl"). + +-record(autofilter, {key, timestamp=0, count=1, drop=false, reason}). + +start(Host, Opts) -> + case ?IS_VALID of + true -> + mnesia:create_table(autofilter, [ + {disc_copies, [node()]}, {type, set}, + {attributes, record_info(fields, autofilter)} ]), + ejabberd_hooks:add(offline_message_hook, Host, ?MODULE, offline_message, 10), + ejabberd_hooks:add(filter_packet, ?MODULE, filter_packet, 10), + ejabberd_hooks:add(sm_remove_connection_hook, Host, ?MODULE, close_session, 10), + case gen_mod:get_opt(purge_freq, Opts, 0) of %% purge_freq in minutes + 0 -> + no_purge; + Freq -> + Keep = gen_mod:get_opt(keep, Opts, 10), %% keep in minutes + timer:apply_interval(Freq*60000, ?MODULE, purge, [Keep*60]) + end, + start; + false -> + not_started + end. + +stop(Host) -> + ejabberd_hooks:delete(offline_message_hook, Host, ?MODULE, offline_message, 10), + ejabberd_hooks:delete(filter_packet, ?MODULE, filter_packet, 10), + ejabberd_hooks:delete(sm_remove_connection_hook, Host, ?MODULE, close_session, 10), + stop. + +is_loaded() -> + ok. + +purge(Keep) -> + ?INFO_MSG("autofilter purge",[]), + {T1, T2, _} = now(), + Older = T1*1000000+T2-Keep, + lists:foreach(fun(Key) -> + mnesia:dirty_delete({autofilter, Key}) + end, mnesia:dirty_select(autofilter, [{#autofilter{key = '$1', drop = false, timestamp = '$2', _ = '_'}, [{'<', '$2', Older}], ['$1']}])), + ok. + +deny(User, Server) -> + Key = {User, Server}, + Record = case mnesia:dirty_read({autofilter, Key}) of + [R] -> R; + _ -> #autofilter{key=Key} + end, + ?INFO_MSG("autofilter: messages from ~s@~s will be droped~n", [User, Server]), + mnesia:dirty_write(Record#autofilter{drop=true}). + +allow(User, Server) -> + Key = {User, Server}, + ?INFO_MSG("autofilter: messages from ~s@~s are accepted~n", [User, Server]), + mnesia:dirty_delete({autofilter, Key}). + +denied() -> + mnesia:dirty_select(autofilter, [{#autofilter{key = '$1', drop = true, reason = '$2', _ = '_'}, [], [['$1','$2']]}]). +listed() -> + mnesia:dirty_select(autofilter, [{#autofilter{key = '$1', drop = false, reason = '$2', _ = '_'}, [], [['$1','$2']]}]). + +offline_message({jid, [], _, [], [], _, []}, _To, _Packet) -> + ok; +offline_message(From, To, Packet) -> + {User, Server, _} = jlib:jid_tolower(From), + Key = {User, Server}, + {T1, T2, _} = now(), + T = T1*1000000+T2, + Record = case mnesia:dirty_read({autofilter, Key}) of + [#autofilter{timestamp=O, count=C}=R] -> + D = T-O, + if + D > 3600 -> % this is usefull only of purge_freq is not set + R#autofilter{timestamp=T, count=1}; + ((C/D) > 1/10) and (C > 90) -> + ?INFO_MSG("autofilter: messages from ~s@~s will be droped~n", [User, Server]), + R#autofilter{drop=true, reason=offline_flood}; + true -> + R#autofilter{count=C+1} + end; + _ -> + #autofilter{key=Key, timestamp=T, count=1, drop=false, reason=offline_flood} + end, + mnesia:dirty_write(Record), + ok. + +filter_packet({From, To, Packet}) -> + {User, Server, _} = jlib:jid_tolower(From), + case mnesia:dirty_read({autofilter, {User, Server}}) of + [#autofilter{drop=true}] -> drop; + _ -> {From, To, Packet} + end. + +close_session(SID, JID) -> + close_session(SID, JID, []). +close_session(_SID, {jid, _, _, _, User, Server, _}, _Info) -> + % this allows user, except for blocked ones + lists:foreach(fun(#autofilter{key=Key}) -> + mnesia:dirty_delete({autofilter, Key}) + end, mnesia:dirty_match_object(#autofilter{key={User, Server}, drop = false, _ = '_'})), + ok. diff --git a/src/mod_filter.erl b/src/mod_filter.erl index ad42564b3..1debb6323 100644 --- a/src/mod_filter.erl +++ b/src/mod_filter.erl @@ -1,5 +1,5 @@ %%% ==================================================================== -%%% This software is copyright 2006-2009, ProcessOne. +%%% This software is copyright 2006-2010, ProcessOne. %%% %%% mod_filter %%% allow message filtering using regexp on message body @@ -9,7 +9,7 @@ %%% BUT, if patch is not available, mod_filter uses re.beam module %%% instead, with speed degradation. %%% -%%% @copyright 2006-2009 ProcessOne +%%% @copyright 2006-2010 ProcessOne %%% @author Christophe Romain %%% [http://www.process-one.net/] %%% @version {@vsn}, {@date} {@time} @@ -18,7 +18,6 @@ -module(mod_filter). -author('christophe.romain@process-one.net'). --vsn('$Id: mod_filter.erl 767 2009-04-20 16:31:40Z cromain $'). -behaviour(gen_mod). diff --git a/src/mod_support.erl b/src/mod_support.erl index de1c7ba65..bd3b8a01b 100644 --- a/src/mod_support.erl +++ b/src/mod_support.erl @@ -1,10 +1,10 @@ %%% ==================================================================== -%%% This software is copyright 2006-2009, ProcessOne. +%%% This software is copyright 2006-2010, ProcessOne. %%% %%% mod_support %%% allow automatic build of support archive to be sent to Process-One %%% -%%% @copyright 2006-2009 ProcessOne +%%% @copyright 2006-2010 ProcessOne %%% @author Christophe Romain %%% [http://www.process-one.net/] %%% @version {@vsn}, {@date} {@time} @@ -14,7 +14,6 @@ -module(mod_support). -author('christophe.romain@process-one.net'). --vsn('$Id: mod_support.erl 856 2009-09-21 18:46:38Z jpcarlino $'). -behaviour(gen_mod). %-behaviour(gen_server). From 50b747041fe5505be8f0beddea1f56e35e901e3e Mon Sep 17 00:00:00 2001 From: Evgeniy Khramtsov Date: Tue, 5 Oct 2010 21:28:45 +1000 Subject: [PATCH 74/85] use one_queue IQ discipline by default --- src/mod_vcard_ldap.erl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/mod_vcard_ldap.erl b/src/mod_vcard_ldap.erl index ed52a0593..53f8b58dc 100644 --- a/src/mod_vcard_ldap.erl +++ b/src/mod_vcard_ldap.erl @@ -169,7 +169,7 @@ start_link(Host, Opts) -> init([Host, Opts]) -> State = parse_options(Host, Opts), - IQDisc = gen_mod:get_opt(iqdisc, Opts, parallel), + IQDisc = gen_mod:get_opt(iqdisc, Opts, one_queue), gen_iq_handler:add_iq_handler(ejabberd_local, Host, ?NS_VCARD, ?MODULE, process_local_iq, IQDisc), gen_iq_handler:add_iq_handler(ejabberd_sm, Host, ?NS_VCARD, From 350af319bfa9a0dc1eae2cee63458b20364103dc Mon Sep 17 00:00:00 2001 From: Evgeniy Khramtsov Date: Fri, 8 Oct 2010 19:26:49 +1000 Subject: [PATCH 75/85] fixes annoying crash with controller change --- src/ejabberd_receiver.erl | 14 ++++++++++++-- src/web/ejabberd_http_bind.erl | 9 +++++++-- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/src/ejabberd_receiver.erl b/src/ejabberd_receiver.erl index eef82018a..0482a27dc 100644 --- a/src/ejabberd_receiver.erl +++ b/src/ejabberd_receiver.erl @@ -104,12 +104,22 @@ become_controller(Pid, C2SPid) -> gen_server:call(Pid, {become_controller, C2SPid}). change_controller(Pid, C2SPid) -> - gen_server:call(Pid, {change_controller, C2SPid}). + case catch gen_server:call(Pid, {change_controller, C2SPid}) of + {'EXIT', _} -> + {error, einval}; + Res -> + Res + end. setopts(Pid, Opts) -> case lists:member({active, false}, Opts) of true -> - gen_server:call(Pid, deactivate_socket); + case catch gen_server:call(Pid, deactivate_socket) of + {'EXIT', _} -> + {error, einval}; + Res -> + Res + end; false -> ok end. diff --git a/src/web/ejabberd_http_bind.erl b/src/web/ejabberd_http_bind.erl index a1dbc570a..98f8ea520 100644 --- a/src/web/ejabberd_http_bind.erl +++ b/src/web/ejabberd_http_bind.erl @@ -153,8 +153,13 @@ setopts({http_bind, FsmRef, _IP}, Opts) -> _ -> case lists:member({active, false}, Opts) of true -> - gen_fsm:sync_send_all_state_event( - FsmRef, deactivate_socket); + case catch gen_fsm:sync_send_all_state_event( + FsmRef, deactivate_socket) of + {'EXIT', _} -> + {error, einval}; + Res -> + Res + end; _ -> ok end From 3a7d02dbd33ecbcf4e9490969302a284c8250f42 Mon Sep 17 00:00:00 2001 From: Evgeniy Khramtsov Date: Sat, 9 Oct 2010 00:44:23 +1000 Subject: [PATCH 76/85] fixes anonymous sessions lookup --- src/ejabberd_auth_anonymous.erl | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/ejabberd_auth_anonymous.erl b/src/ejabberd_auth_anonymous.erl index 07eafd7b5..94f46eb79 100644 --- a/src/ejabberd_auth_anonymous.erl +++ b/src/ejabberd_auth_anonymous.erl @@ -128,11 +128,18 @@ anonymous_user_exist(User, Server) -> LUser = jlib:nodeprep(User), LServer = jlib:nameprep(Server), US = {LUser, LServer}, - case catch mnesia:dirty_read({anonymous, US}) of - [] -> - false; + Ss = case ejabberd_cluster:get_node(US) of + Node when Node == node() -> + catch mnesia:dirty_read({anonymous, US}); + Node -> + catch rpc:call(Node, mnesia, dirty_read, + [{anonymous, US}], 5000) + end, + case Ss of [_H|_T] -> - true + true; + _ -> + false end. %% Remove connection from Mnesia tables From ac87749d557a3230481f44841678164f1e32ce1a Mon Sep 17 00:00:00 2001 From: Evgeniy Khramtsov Date: Mon, 11 Oct 2010 18:40:57 +1000 Subject: [PATCH 77/85] add find_s2s_bridge hook --- src/ejabberd_s2s_out.erl | 39 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/src/ejabberd_s2s_out.erl b/src/ejabberd_s2s_out.erl index 7cfb68d7a..907bdd65a 100644 --- a/src/ejabberd_s2s_out.erl +++ b/src/ejabberd_s2s_out.erl @@ -44,6 +44,7 @@ wait_for_features/2, wait_for_auth_result/2, wait_for_starttls_proceed/2, + relay_to_bridge/2, reopen_socket/2, wait_before_retry/2, stream_established/2, @@ -72,6 +73,7 @@ myname, server, queue, delay_to_retry = undefined_delay, new = false, verify = false, + bridge, timer}). %%-define(DBGFSM, true). @@ -228,8 +230,19 @@ open_socket(init, StateData) -> {error, _Reason} -> ?INFO_MSG("s2s connection: ~s -> ~s (remote server not found)", [StateData#state.myname, StateData#state.server]), - wait_before_reconnect(StateData) - %%{stop, normal, StateData} + case ejabberd_hooks:run_fold(find_s2s_bridge, + undefined, + [StateData#state.myname, + StateData#state.server]) of + {Mod, Fun, Type} -> + ?INFO_MSG("found a bridge to ~s for: ~s -> ~s", + [Type, StateData#state.myname, + StateData#state.server]), + NewStateData = StateData#state{bridge={Mod, Fun}}, + {next_state, relay_to_bridge, NewStateData}; + _ -> + wait_before_reconnect(StateData) + end end; open_socket(stop, StateData) -> ?INFO_MSG("s2s connection: ~s -> ~s (stopped in open socket)", @@ -677,6 +690,15 @@ reopen_socket(closed, StateData) -> wait_before_retry(_Event, StateData) -> {next_state, wait_before_retry, StateData, ?FSMTIMEOUT}. +relay_to_bridge(stop, StateData) -> + wait_before_reconnect(StateData); +relay_to_bridge(closed, StateData) -> + ?INFO_MSG("relay to bridge: ~s -> ~s (closed)", + [StateData#state.myname, StateData#state.server]), + {stop, normal, StateData}; +relay_to_bridge(_Event, StateData) -> + {next_state, relay_to_bridge, StateData}. + stream_established({xmlstreamelement, El}, StateData) -> ?DEBUG("s2S stream established", []), case is_verify_res(El) of @@ -827,6 +849,19 @@ handle_info({send_element, El}, StateName, StateData) -> wait_before_retry -> bounce_element(El, ?ERR_REMOTE_SERVER_NOT_FOUND), {next_state, StateName, StateData}; + relay_to_bridge -> + %% In this state we relay all outbound messages + %% to a foreign protocol bridge such as SMTP, SIP, etc. + {Mod, Fun} = StateData#state.bridge, + ?DEBUG("relaying stanza via ~p:~p/1", [Mod, Fun]), + case catch Mod:Fun(El) of + {'EXIT', Reason} -> + ?ERROR_MSG("Error while relaying to bridge: ~p", [Reason]), + bounce_element(El, ?ERR_INTERNAL_SERVER_ERROR), + wait_before_reconnect(StateData); + _ -> + {next_state, StateName, StateData} + end; _ -> Q = queue:in(El, StateData#state.queue), {next_state, StateName, StateData#state{queue = Q}, From a93f4f77505e78f88bbee46e215197460e358b55 Mon Sep 17 00:00:00 2001 From: Christophe Romain Date: Wed, 13 Oct 2010 10:54:12 +0200 Subject: [PATCH 78/85] =?UTF-8?q?make=20http-bind=20restartable=20(thanks?= =?UTF-8?q?=20to=20Andreas=20K=C3=B6hler)(EJAB-1318)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/web/mod_http_bind.erl | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/web/mod_http_bind.erl b/src/web/mod_http_bind.erl index 25e964f93..8e750acfd 100644 --- a/src/web/mod_http_bind.erl +++ b/src/web/mod_http_bind.erl @@ -117,7 +117,7 @@ start(_Host, _Opts) -> % mod_http_bind is already started so it will not be started again ok; {error, Error} -> - {'EXIT', {start_child_error, Error}} + exit({start_child_error, Error}) end. stop(_Host) -> @@ -125,7 +125,13 @@ stop(_Host) -> ok -> ok; {error, Error} -> - {'EXIT', {terminate_child_error, Error}} + exit({terminate_child_error, Error}) + end, + case supervisor:delete_child(ejabberd_sup, ejabberd_http_bind_sup) of + ok -> + ok; + {error, Error2} -> + exit({delete_child_error, Error2}) end. setup_database() -> From bde3bce1e72acff9db0d1a7644adbd39473af97a Mon Sep 17 00:00:00 2001 From: Christophe Romain Date: Wed, 13 Oct 2010 15:26:38 +0200 Subject: [PATCH 79/85] remove non generic comment --- src/mod_xmlrpc.erl | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/mod_xmlrpc.erl b/src/mod_xmlrpc.erl index 8266d9727..d01838a0d 100644 --- a/src/mod_xmlrpc.erl +++ b/src/mod_xmlrpc.erl @@ -67,7 +67,8 @@ -export([start/2, handler/2, - link_contacts/5, unlink_contacts/3, %% used by Nimbuzz + link_contacts/5, + unlink_contacts/3, loop/1, stop/1]). From 4a6fc4671389ed40c81f6261b6ea12a49d9d1371 Mon Sep 17 00:00:00 2001 From: Evgeniy Khramtsov Date: Wed, 13 Oct 2010 15:44:18 +1000 Subject: [PATCH 80/85] increase rehash timeout to 30 seconds; increase hashing points --- src/ejabberd_cluster.erl | 4 ++-- src/p1_fsm.erl | 28 ++++++++++++++++++++++++---- 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/src/ejabberd_cluster.erl b/src/ejabberd_cluster.erl index 3db8dd29d..190e35202 100644 --- a/src/ejabberd_cluster.erl +++ b/src/ejabberd_cluster.erl @@ -21,8 +21,8 @@ -define(HASHTBL, nodes_hash). -define(HASHTBL_NEW, nodes_hash_new). --define(POINTS, 16). --define(REHASH_TIMEOUT, 5000). +-define(POINTS, 64). +-define(REHASH_TIMEOUT, 30000). -record(state, {}). diff --git a/src/p1_fsm.erl b/src/p1_fsm.erl index 9ca924112..0d9d7f134 100644 --- a/src/p1_fsm.erl +++ b/src/p1_fsm.erl @@ -555,7 +555,15 @@ handle_msg(Msg, Parent, Name, StateName, StateData, Mod, _Time, loop(Parent, Name, NStateName, NStateData, Mod, Time1, [], Limits, Queue, QueueLen); {migrate, NStateData, {Node, M, F, A}, Time1} -> - Reason = case catch rpc:call(Node, M, F, A, 5000) of + RPCTimeout = if Time1 == 0 -> + %% We don't care about a delay, + %% so we set it one minute + 60000; + true -> + Time1 + end, + Now = now(), + Reason = case catch rpc:call(Node, M, F, A, RPCTimeout) of {badrpc, _} = Err -> {migration_error, Err}; {'EXIT', _} = Err -> @@ -565,7 +573,9 @@ handle_msg(Msg, Parent, Name, StateName, StateData, Mod, _Time, {ok, Clone} -> process_flag(trap_exit, true), MRef = erlang:monitor(process, Clone), - TRef = erlang:start_timer(Time1, self(), timeout), + NowDiff = timer:now_diff(now(), Now), + TimeLeft = lists:max([Time1 - NowDiff, 0]) div 1000, + TRef = erlang:start_timer(TimeLeft, self(), timeout), relay_messages(MRef, TRef, Clone, Queue); Reply -> {migration_error, {bad_reply, Reply}} @@ -608,7 +618,15 @@ handle_msg(Msg, Parent, Name, StateName, StateData, loop(Parent, Name, NStateName, NStateData, Mod, Time1, Debug1, Limits, Queue, QueueLen); {migrate, NStateData, {Node, M, F, A}, Time1} -> - Reason = case catch rpc:call(Node, M, F, A, Time1) of + RPCTimeout = if Time1 == 0 -> + %% We don't care about a delay, + %% so we set it one minute + 60000; + true -> + Time1 + end, + Now = now(), + Reason = case catch rpc:call(Node, M, F, A, RPCTimeout) of {badrpc, R} -> {migration_error, R}; {'EXIT', R} -> @@ -618,7 +636,9 @@ handle_msg(Msg, Parent, Name, StateName, StateData, {ok, Clone} -> process_flag(trap_exit, true), MRef = erlang:monitor(process, Clone), - TRef = erlang:start_timer(Time1, self(), timeout), + NowDiff = timer:now_diff(now(), Now), + TimeLeft = lists:max([Time1 - NowDiff, 0]) div 1000, + TRef = erlang:start_timer(TimeLeft, self(), timeout), relay_messages(MRef, TRef, Clone, Queue); Reply -> {migration_error, {bad_reply, Reply}} From 254686ab4642c362a9263ab2ece50d12981d2b98 Mon Sep 17 00:00:00 2001 From: Evgeniy Khramtsov Date: Thu, 14 Oct 2010 20:11:44 +1000 Subject: [PATCH 81/85] fixes timeout calculation --- src/p1_fsm.erl | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/p1_fsm.erl b/src/p1_fsm.erl index 0d9d7f134..6446d01f1 100644 --- a/src/p1_fsm.erl +++ b/src/p1_fsm.erl @@ -573,8 +573,8 @@ handle_msg(Msg, Parent, Name, StateName, StateData, Mod, _Time, {ok, Clone} -> process_flag(trap_exit, true), MRef = erlang:monitor(process, Clone), - NowDiff = timer:now_diff(now(), Now), - TimeLeft = lists:max([Time1 - NowDiff, 0]) div 1000, + NowDiff = timer:now_diff(now(), Now) div 1000, + TimeLeft = lists:max([Time1 - NowDiff, 0]), TRef = erlang:start_timer(TimeLeft, self(), timeout), relay_messages(MRef, TRef, Clone, Queue); Reply -> @@ -636,8 +636,8 @@ handle_msg(Msg, Parent, Name, StateName, StateData, {ok, Clone} -> process_flag(trap_exit, true), MRef = erlang:monitor(process, Clone), - NowDiff = timer:now_diff(now(), Now), - TimeLeft = lists:max([Time1 - NowDiff, 0]) div 1000, + NowDiff = timer:now_diff(now(), Now) div 1000, + TimeLeft = lists:max([Time1 - NowDiff, 0]), TRef = erlang:start_timer(TimeLeft, self(), timeout), relay_messages(MRef, TRef, Clone, Queue); Reply -> From eeffc77a1a82261b027a327de52f9ea2946c96ec Mon Sep 17 00:00:00 2001 From: Evgeniy Khramtsov Date: Thu, 14 Oct 2010 20:28:41 +1000 Subject: [PATCH 82/85] ignore RPC timeout during migration --- src/p1_fsm.erl | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/p1_fsm.erl b/src/p1_fsm.erl index 6446d01f1..bc47e9c67 100644 --- a/src/p1_fsm.erl +++ b/src/p1_fsm.erl @@ -564,6 +564,8 @@ handle_msg(Msg, Parent, Name, StateName, StateData, Mod, _Time, end, Now = now(), Reason = case catch rpc:call(Node, M, F, A, RPCTimeout) of + {badrpc, timeout} -> + normal; {badrpc, _} = Err -> {migration_error, Err}; {'EXIT', _} = Err -> @@ -627,6 +629,8 @@ handle_msg(Msg, Parent, Name, StateName, StateData, end, Now = now(), Reason = case catch rpc:call(Node, M, F, A, RPCTimeout) of + {badrpc, timeout} -> + normal; {badrpc, R} -> {migration_error, R}; {'EXIT', R} -> From 11b00b92e92c09ad3549f54437ce78dab31177de Mon Sep 17 00:00:00 2001 From: Juan Pablo Carlino Date: Thu, 14 Oct 2010 19:00:19 -0300 Subject: [PATCH 83/85] merge from Team Leader 2.2 (r973) --- src/mod_filter.erl | 39 ++++++++++++++++++++++++++++++--------- 1 file changed, 30 insertions(+), 9 deletions(-) diff --git a/src/mod_filter.erl b/src/mod_filter.erl index 1debb6323..ecc3446d6 100644 --- a/src/mod_filter.erl +++ b/src/mod_filter.erl @@ -18,6 +18,7 @@ -module(mod_filter). -author('christophe.romain@process-one.net'). +-vsn('$Id: mod_filter.erl 972 2010-10-14 21:53:56Z jpcarlino $'). -behaviour(gen_mod). @@ -129,18 +130,38 @@ update(Host, Opts) -> loop(Host, Opts, Rules, Scope, Pattern) -> receive {add, Id, RegExp} -> - [BinRegExp] = tlre:compile([RegExp]), - mnesia:dirty_write(#filter_rule{id={Id, Host}, regexp=RegExp, binre=BinRegExp}), - ?MODULE:update(Host, Opts); + try + [BinRegExp] = tlre:compile([RegExp]), + ?INFO_MSG("Adding new filter rule with regexp=~p", [RegExp]), + mnesia:dirty_write(#filter_rule{id={Id, Host}, regexp=RegExp, binre=BinRegExp}), + ?MODULE:update(Host, Opts) + catch + Class:Reason -> + ?INFO_MSG("~p can't add filter rule with regexp=~p for id=~p. Reason: ~p", [Class, RegExp, Id, Reason]), + loop(Host, Opts, Rules, Scope, Pattern) + end; {add, Id, RegExp, Type} -> - [BinRegExp] = tlre:compile([RegExp]), - mnesia:dirty_write(#filter_rule{id={Id, Host}, regexp=RegExp, binre=BinRegExp, type=Type}), - ?MODULE:update(Host, Opts); + try + [BinRegExp] = tlre:compile([RegExp]), + ?INFO_MSG("Adding new filter rule with regexp=~p", [RegExp]), + mnesia:dirty_write(#filter_rule{id={Id, Host}, regexp=RegExp, binre=BinRegExp, type=Type}), + ?MODULE:update(Host, Opts) + catch + Class:Reason -> + ?INFO_MSG("~p can't add filter rule with regexp=~p for id=~p with type=~p. Reason: ~p", [Class, RegExp, Id, Type, Reason]), + loop(Host, Opts, Rules, Scope, Pattern) + end; {del, Id} -> - mnesia:dirty_delete_object(#filter_rule{id={Id, Host}, _='_'}), + RulesToRemove = mnesia:dirty_match_object(#filter_rule{id={Id, Host}, _='_'}), + lists:foreach(fun(Rule) -> + mnesia:dirty_delete_object(Rule) + end, RulesToRemove), ?MODULE:update(Host, Opts); {del, Id, RegExp} -> - mnesia:dirty_delete_object(#filter_rule{id={Id, Host}, regexp=RegExp, _='_'}), + RulesToRemove = mnesia:dirty_match_object(#filter_rule{id={Id, Host}, regexp=RegExp, _='_'}), + lists:foreach(fun(Rule) -> + mnesia:dirty_delete_object(Rule) + end, RulesToRemove), ?MODULE:update(Host, Opts); {match, From, String} -> From ! {match, string_filter(String, Rules, Scope, Pattern)}, @@ -261,7 +282,7 @@ filter_packet({From, To, Packet}) -> receive {match, {"pass", _}} -> [{xmlcdata, CData}|DataAcc]; - {match, {"log", FinalString}} -> + {match, {"log", _}} -> mnesia:dirty_write(#filter_log{ date=erlang:localtime(), from=From, to=To, message=Msg}), From 70fe2948b99491d654a5f0cc6964667fc5d40051 Mon Sep 17 00:00:00 2001 From: Badlop Date: Mon, 18 Oct 2010 23:17:12 +0200 Subject: [PATCH 84/85] Revert "Remove some compiled files" That removal was only intended for ejabberd master, as it requires also changes in gitignore, Makefile.in and aclocal.m4 This reverts commit 179a0cf255e59cdcbeb2562c756d070cb3522d03. --- doc/dev.html | 413 +++ doc/features.html | 132 + doc/guide.html | 4121 +++++++++++++++++++++++++++++ src/configure | 6310 +++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 10976 insertions(+) create mode 100644 doc/dev.html create mode 100644 doc/features.html create mode 100644 doc/guide.html create mode 100755 src/configure diff --git a/doc/dev.html b/doc/dev.html new file mode 100644 index 000000000..b7fea526a --- /dev/null +++ b/doc/dev.html @@ -0,0 +1,413 @@ + + + +Ejabberd 2.1.x Developers Guide + + + + + + + + +

    + +

    +

    Ejabberd 2.1.x Developers Guide

    Alexey Shchepin
    + mailto:alexey@sevcom.net
    + xmpp:aleksey@jabber.ru

    + +logo.png + + +
    I can thoroughly recommend ejabberd for ease of setup – +Kevin Smith, Current maintainer of the Psi project
    +

    Contents

    Introduction +

    ejabberd is a free and open source instant messaging server written in Erlang/OTP.

    ejabberd is cross-platform, distributed, fault-tolerant, and based on open standards to achieve real-time communication.

    ejabberd is designed to be a rock-solid and feature rich XMPP server.

    ejabberd is suitable for small deployments, whether they need to be scalable or not, as well as extremely big deployments.

    +

    1  Key Features

    + +

    ejabberd is: +

    • +Cross-platform: ejabberd runs under Microsoft Windows and Unix derived systems such as Linux, FreeBSD and NetBSD.
    • Distributed: You can run ejabberd on a cluster of machines and all of them will serve the same Jabber domain(s). When you need more capacity you can simply add a new cheap node to your cluster. Accordingly, you do not need to buy an expensive high-end machine to support tens of thousands concurrent users.
    • Fault-tolerant: You can deploy an ejabberd cluster so that all the information required for a properly working service will be replicated permanently on all nodes. This means that if one of the nodes crashes, the others will continue working without disruption. In addition, nodes also can be added or replaced ‘on the fly’.
    • Administrator Friendly: ejabberd is built on top of the Open Source Erlang. As a result you do not need to install an external database, an external web server, amongst others because everything is already included, and ready to run out of the box. Other administrator benefits include: +
      • +Comprehensive documentation. +
      • Straightforward installers for Linux, Mac OS X, and Windows.
      • Web Administration. +
      • Shared Roster Groups. +
      • Command line administration tool.
      • Can integrate with existing authentication mechanisms. +
      • Capability to send announce messages. +
    • Internationalized: ejabberd leads in internationalization. Hence it is very well suited in a globalized world. Related features are: +
      • +Translated to 25 languages.
      • Support for IDNA. +
    • Open Standards: ejabberd is the first Open Source Jabber server claiming to fully comply to the XMPP standard. +
    +

    2  Additional Features

    + +

    Moreover, ejabberd comes with a wide range of other state-of-the-art features: +

    • +Modular +
      • +Load only the modules you want. +
      • Extend ejabberd with your own custom modules. +
      +
    • Security +
      • +SASL and STARTTLS for c2s and s2s connections. +
      • STARTTLS and Dialback s2s connections. +
      • Web Admin accessible via HTTPS secure access. +
      +
    • Databases +
      • +Internal database for fast deployment (Mnesia). +
      • Native MySQL support. +
      • Native PostgreSQL support. +
      • ODBC data storage support. +
      • Microsoft SQL Server support.
      +
    • Authentication +
      • +Internal Authentication. +
      • PAM, LDAP and ODBC.
      • External Authentication script. +
      +
    • Others +
      • +Support for virtual hosting. +
      • Compressing XML streams with Stream Compression (XEP-0138). +
      • Statistics via Statistics Gathering (XEP-0039). +
      • IPv6 support both for c2s and s2s connections. +
      • Multi-User Chat module with support for clustering and HTML logging.
      • Users Directory based on users vCards. +
      • Publish-Subscribe component with support for Personal Eventing via Pubsub. +
      • Support for web clients: HTTP Polling and HTTP Binding (BOSH) services. +
      • IRC transport. +
      • Component support: interface with networks such as AIM, ICQ and MSN installing special tranports. +
      +
    +

    3  How it Works

    +

    A XMPP domain is served by one or more ejabberd nodes. These nodes can +be run on different machines that are connected via a network. They all must +have the ability to connect to port 4369 of all another nodes, and must have +the same magic cookie (see Erlang/OTP documentation, in other words the file +~ejabberd/.erlang.cookie must be the same on all nodes). This is +needed because all nodes exchange information about connected users, S2S +connections, registered services, etc…

    Each ejabberd node have following modules: +

    • +router; +
    • local router. +
    • session manager; +
    • S2S manager; +
    +

    3.1  Router

    This module is the main router of XMPP packets on each node. It routes +them based on their destinations domains. It has two tables: local and global +routes. First, domain of packet destination searched in local table, and if it +found, then the packet is routed to appropriate process. If no, then it +searches in global table, and is routed to the appropriate ejabberd node or +process. If it does not exists in either tables, then it sent to the S2S +manager.

    +

    3.2  Local Router

    This module routes packets which have a destination domain equal to this server +name. If destination JID has a non-empty user part, then it routed to the +session manager, else it is processed depending on it’s content.

    +

    3.3  Session Manager

    This module routes packets to local users. It searches for what user resource +packet must be sended via presence table. If this resource is connected to +this node, it is routed to C2S process, if it connected via another node, then +the packet is sent to session manager on that node.

    +

    3.4  S2S Manager

    This module routes packets to other XMPP servers. First, it checks if an +open S2S connection from the domain of the packet source to the domain of +packet destination already exists. If it is open on another node, then it +routes the packet to S2S manager on that node, if it is open on this node, then +it is routed to the process that serves this connection, and if a connection +does not exist, then it is opened and registered.

    +

    4  Authentication

    +

    4.0.1  External

    + +

    The external authentication script follows +the erlang port driver API.

    That script is supposed to do theses actions, in an infinite loop: +

    • +read from stdin: AABBBBBBBBB..... +
      • +A: 2 bytes of length data (a short in network byte order) +
      • B: a string of length found in A that contains operation in plain text +operation are as follows: +
        • +auth:User:Server:Password (check if a username/password pair is correct) +
        • isuser:User:Server (check if it’s a valid user) +
        • setpass:User:Server:Password (set user’s password) +
        • tryregister:User:Server:Password (try to register an account) +
        • removeuser:User:Server (remove this account) +
        • removeuser3:User:Server:Password (remove this account if the password is correct) +
        +
      +
    • write to stdout: AABB +
      • +A: the number 2 (coded as a short, which is bytes length of following result) +
      • B: the result code (coded as a short), should be 1 for success/valid, or 0 for failure/invalid +
      +

    Example python script +

    #!/usr/bin/python
    +
    +import sys
    +from struct import *
    +
    +def from_ejabberd():
    +    input_length = sys.stdin.read(2)
    +    (size,) = unpack('>h', input_length)
    +    return sys.stdin.read(size).split(':')
    +
    +def to_ejabberd(bool):
    +    answer = 0
    +    if bool:
    +        answer = 1
    +    token = pack('>hh', 2, answer)
    +    sys.stdout.write(token)
    +    sys.stdout.flush()
    +
    +def auth(username, server, password):
    +    return True
    +
    +def isuser(username, server):
    +    return True
    +
    +def setpass(username, server, password):
    +    return True
    +
    +while True:
    +    data = from_ejabberd()
    +    success = False
    +    if data[0] == "auth":
    +        success = auth(data[1], data[2], data[3])
    +    elif data[0] == "isuser":
    +        success = isuser(data[1], data[2])
    +    elif data[0] == "setpass":
    +        success = setpass(data[1], data[2], data[3])
    +    to_ejabberd(success)
    +
    +

    5  XML Representation

    +

    Each XML stanza is represented as the following tuple: +

    XMLElement = {xmlelement, Name, Attrs, [ElementOrCDATA]}
    +        Name = string()
    +        Attrs = [Attr]
    +        Attr = {Key, Val}
    +        Key = string()
    +        Val = string()
    +        ElementOrCDATA = XMLElement | CDATA
    +        CDATA = {xmlcdata, string()}
    +

    E. g. this stanza: +

    <message to='test@conference.example.org' type='groupchat'>
    +  <body>test</body>
    +</message>
    +

    is represented as the following structure: +

    {xmlelement, "message",
    +    [{"to", "test@conference.example.org"},
    +     {"type", "groupchat"}],
    +    [{xmlelement, "body",
    +         [],
    +         [{xmlcdata, "test"}]}]}}
    +
    +

    6  Module xml

    +

    +
    element_to_string(El) -> string() +
    El = XMLElement
    +
    Returns string representation of XML stanza El.
    crypt(S) -> string() +
    S = string()
    +
    Returns string which correspond to S with encoded XML special +characters.
    remove_cdata(ECList) -> EList +
    ECList = [ElementOrCDATA]
    +EList = [XMLElement]
    +
    EList is a list of all non-CDATA elements of ECList.
    get_path_s(El, Path) -> Res +
    El = XMLElement
    +Path = [PathItem]
    +PathItem = PathElem | PathAttr | PathCDATA
    +PathElem = {elem, Name}
    +PathAttr = {attr, Name}
    +PathCDATA = cdata
    +Name = string()
    +Res = string() | XMLElement
    +
    If Path is empty, then returns El. Else sequentially +consider elements of Path. Each element is one of: +
    +
    {elem, Name} Name is name of subelement of +El, if such element exists, then this element considered in +following steps, else returns empty string. +
    {attr, Name} If El have attribute Name, then +returns value of this attribute, else returns empty string. +
    cdata Returns CDATA of El. +
    TODO: +
             get_cdata/1, get_tag_cdata/1
    +         get_attr/2, get_attr_s/2
    +         get_tag_attr/2, get_tag_attr_s/2
    +         get_subtag/2
    +
    +

    7  Module xml_stream

    +

    +
    parse_element(Str) -> XMLElement | {error, Err} +
    Str = string()
    +Err = term()
    +
    Parses Str using XML parser, returns either parsed element or error +tuple. +
    +

    8  Modules

    +

    +

    8.1  Module gen_iq_handler

    +

    The module gen_iq_handler allows to easily write handlers for IQ packets +of particular XML namespaces that addressed to server or to users bare JIDs.

    In this module the following functions are defined: +

    +
    add_iq_handler(Component, Host, NS, Module, Function, Type) +
    Component = Module = Function = atom()
    +Host = NS = string()
    +Type = no_queue | one_queue | parallel
    +
    Registers function Module:Function as handler for IQ packets on +virtual host Host that contain child of namespace NS in +Component. Queueing discipline is Type. There are at least +two components defined: +
    +
    ejabberd_local Handles packets that addressed to server JID; +
    ejabberd_sm Handles packets that addressed to users bare JIDs. +
    +
    remove_iq_handler(Component, Host, NS) +
    Component = atom()
    +Host = NS = string()
    +
    Removes IQ handler on virtual host Host for namespace NS from +Component. +

    Handler function must have the following type: +

    +
    Module:Function(From, To, IQ) +
    From = To = jid()
    +
    -module(mod_cputime).
    +
    +-behaviour(gen_mod).
    +
    +-export([start/2,
    +         stop/1,
    +         process_local_iq/3]).
    +
    +-include("ejabberd.hrl").
    +-include("jlib.hrl").
    +
    +-define(NS_CPUTIME, "ejabberd:cputime").
    +
    +start(Host, Opts) ->
    +    IQDisc = gen_mod:get_opt(iqdisc, Opts, one_queue),
    +    gen_iq_handler:add_iq_handler(ejabberd_local, Host, ?NS_CPUTIME,
    +                                  ?MODULE, process_local_iq, IQDisc).
    +
    +stop(Host) ->
    +    gen_iq_handler:remove_iq_handler(ejabberd_local, Host, ?NS_CPUTIME).
    +
    +process_local_iq(From, To, {iq, ID, Type, XMLNS, SubEl}) ->
    +    case Type of
    +        set ->
    +            {iq, ID, error, XMLNS,
    +             [SubEl, ?ERR_NOT_ALLOWED]};
    +        get ->
    +            CPUTime = element(1, erlang:statistics(runtime))/1000,
    +            SCPUTime = lists:flatten(io_lib:format("~.3f", CPUTime)),
    +            {iq, ID, result, XMLNS,
    +             [{xmlelement, "query",
    +               [{"xmlns", ?NS_CPUTIME}],
    +               [{xmlelement, "cputime", [], [{xmlcdata, SCPUTime}]}]}]}
    +    end.
    +
    +

    8.2  Services

    +

    -module(mod_echo).
    +
    +-behaviour(gen_mod).
    +
    +-export([start/2, init/1, stop/1]).
    +
    +-include("ejabberd.hrl").
    +-include("jlib.hrl").
    +
    +start(Host, Opts) ->
    +    MyHost = gen_mod:get_opt(host, Opts, "echo." ++ Host),
    +    register(gen_mod:get_module_proc(Host, ?PROCNAME),
    +             spawn(?MODULE, init, [MyHost])).
    +
    +init(Host) ->
    +    ejabberd_router:register_local_route(Host),
    +    loop(Host).
    +
    +loop(Host) ->
    +    receive
    +        {route, From, To, Packet} ->
    +            ejabberd_router:route(To, From, Packet),
    +            loop(Host);
    +        stop ->
    +            ejabberd_router:unregister_route(Host),
    +            ok;
    +        _ ->
    +            loop(Host)
    +    end.
    +
    +stop(Host) ->
    +    Proc = gen_mod:get_module_proc(Host, ?PROCNAME),
    +    Proc ! stop,
    +    {wait, Proc}.
    +
    + + + +
    This document was translated from LATEX by +HEVEA.
    + diff --git a/doc/features.html b/doc/features.html new file mode 100644 index 000000000..503ac0d3f --- /dev/null +++ b/doc/features.html @@ -0,0 +1,132 @@ + + + +Ejabberd 2.1.x Feature Sheet + + + + + + + + +

    + +

    +

    Ejabberd 2.1.x Feature Sheet

    Sander Devrieze
    + mailto:s.devrieze@pandora.be
    + xmpp:sander@devrieze.dyndns.org

    + +logo.png + + +
    I can thoroughly recommend ejabberd for ease of setup – +Kevin Smith, Current maintainer of the Psi project

    Introduction +

    I just tried out ejabberd and was impressed both by ejabberd itself and the language it is written in, Erlang. — +Joeri

    ejabberd is a free and open source instant messaging server written in Erlang/OTP.

    ejabberd is cross-platform, distributed, fault-tolerant, and based on open standards to achieve real-time communication.

    ejabberd is designed to be a rock-solid and feature rich XMPP server.

    ejabberd is suitable for small deployments, whether they need to be scalable or not, as well as extremely big deployments.

    +

    Key Features

    + +

    Erlang seems to be tailor-made for writing stable, robust servers. — +Peter Saint-André, Executive Director of the Jabber Software Foundation

    ejabberd is: +

    • +Cross-platform: ejabberd runs under Microsoft Windows and Unix derived systems such as Linux, FreeBSD and NetBSD.
    • Distributed: You can run ejabberd on a cluster of machines and all of them will serve the same Jabber domain(s). When you need more capacity you can simply add a new cheap node to your cluster. Accordingly, you do not need to buy an expensive high-end machine to support tens of thousands concurrent users.
    • Fault-tolerant: You can deploy an ejabberd cluster so that all the information required for a properly working service will be replicated permanently on all nodes. This means that if one of the nodes crashes, the others will continue working without disruption. In addition, nodes also can be added or replaced ‘on the fly’.
    • Administrator Friendly: ejabberd is built on top of the Open Source Erlang. As a result you do not need to install an external database, an external web server, amongst others because everything is already included, and ready to run out of the box. Other administrator benefits include: +
      • +Comprehensive documentation. +
      • Straightforward installers for Linux, Mac OS X, and Windows.
      • Web Administration. +
      • Shared Roster Groups. +
      • Command line administration tool.
      • Can integrate with existing authentication mechanisms. +
      • Capability to send announce messages. +
    • Internationalized: ejabberd leads in internationalization. Hence it is very well suited in a globalized world. Related features are: +
      • +Translated to 25 languages.
      • Support for IDNA. +
    • Open Standards: ejabberd is the first Open Source Jabber server claiming to fully comply to the XMPP standard. +
    +

    Additional Features

    + +

    ejabberd is making inroads to solving the "buggy incomplete server" problem — +Justin Karneges, Founder of the Psi and the Delta projects

    Moreover, ejabberd comes with a wide range of other state-of-the-art features: +

    • +Modular +
      • +Load only the modules you want. +
      • Extend ejabberd with your own custom modules. +
      +
    • Security +
      • +SASL and STARTTLS for c2s and s2s connections. +
      • STARTTLS and Dialback s2s connections. +
      • Web Admin accessible via HTTPS secure access. +
      +
    • Databases +
      • +Internal database for fast deployment (Mnesia). +
      • Native MySQL support. +
      • Native PostgreSQL support. +
      • ODBC data storage support. +
      • Microsoft SQL Server support.
      +
    • Authentication +
      • +Internal Authentication. +
      • PAM, LDAP and ODBC.
      • External Authentication script. +
      +
    • Others +
      • +Support for virtual hosting. +
      • Compressing XML streams with Stream Compression (XEP-0138). +
      • Statistics via Statistics Gathering (XEP-0039). +
      • IPv6 support both for c2s and s2s connections. +
      • Multi-User Chat module with support for clustering and HTML logging.
      • Users Directory based on users vCards. +
      • Publish-Subscribe component with support for Personal Eventing via Pubsub. +
      • Support for web clients: HTTP Polling and HTTP Binding (BOSH) services. +
      • IRC transport. +
      • Component support: interface with networks such as AIM, ICQ and MSN installing special tranports. +
      +
    + + + +
    This document was translated from LATEX by +HEVEA.
    + diff --git a/doc/guide.html b/doc/guide.html new file mode 100644 index 000000000..50cdca74a --- /dev/null +++ b/doc/guide.html @@ -0,0 +1,4121 @@ + + + + + + + + ejabberd 2.1.x + + Installation and Operation Guide + + + + + + + + + + + + + + +

    + +

    +

    +

    +
    + + + + +
    ejabberd 2.1.x
     
    Installation and Operation Guide

    +
    + +
    + +

    +

    +

    Contents

    +

    Chapter 1  Introduction

    +

    ejabberd is a free and open source instant messaging server written in Erlang/OTP.

    ejabberd is cross-platform, distributed, fault-tolerant, and based on open standards to achieve real-time communication.

    ejabberd is designed to be a rock-solid and feature rich XMPP server.

    ejabberd is suitable for small deployments, whether they need to be scalable or not, as well as extremely big deployments.

    +

    1.1  Key Features

    + +

    ejabberd is: +

    • +Cross-platform: ejabberd runs under Microsoft Windows and Unix derived systems such as Linux, FreeBSD and NetBSD.
    • Distributed: You can run ejabberd on a cluster of machines and all of them will serve the same Jabber domain(s). When you need more capacity you can simply add a new cheap node to your cluster. Accordingly, you do not need to buy an expensive high-end machine to support tens of thousands concurrent users.
    • Fault-tolerant: You can deploy an ejabberd cluster so that all the information required for a properly working service will be replicated permanently on all nodes. This means that if one of the nodes crashes, the others will continue working without disruption. In addition, nodes also can be added or replaced ‘on the fly’.
    • Administrator Friendly: ejabberd is built on top of the Open Source Erlang. As a result you do not need to install an external database, an external web server, amongst others because everything is already included, and ready to run out of the box. Other administrator benefits include: +
      • +Comprehensive documentation. +
      • Straightforward installers for Linux, Mac OS X, and Windows.
      • Web Administration. +
      • Shared Roster Groups. +
      • Command line administration tool.
      • Can integrate with existing authentication mechanisms. +
      • Capability to send announce messages. +
    • Internationalized: ejabberd leads in internationalization. Hence it is very well suited in a globalized world. Related features are: +
      • +Translated to 25 languages.
      • Support for IDNA. +
    • Open Standards: ejabberd is the first Open Source Jabber server claiming to fully comply to the XMPP standard. +
    +

    1.2  Additional Features

    + +

    Moreover, ejabberd comes with a wide range of other state-of-the-art features: +

    • +Modular +
      • +Load only the modules you want. +
      • Extend ejabberd with your own custom modules. +
      +
    • Security +
      • +SASL and STARTTLS for c2s and s2s connections. +
      • STARTTLS and Dialback s2s connections. +
      • Web Admin accessible via HTTPS secure access. +
      +
    • Databases +
      • +Internal database for fast deployment (Mnesia). +
      • Native MySQL support. +
      • Native PostgreSQL support. +
      • ODBC data storage support. +
      • Microsoft SQL Server support.
      +
    • Authentication +
      • +Internal Authentication. +
      • PAM, LDAP and ODBC.
      • External Authentication script. +
      +
    • Others +
      • +Support for virtual hosting. +
      • Compressing XML streams with Stream Compression (XEP-0138). +
      • Statistics via Statistics Gathering (XEP-0039). +
      • IPv6 support both for c2s and s2s connections. +
      • Multi-User Chat module with support for clustering and HTML logging.
      • Users Directory based on users vCards. +
      • Publish-Subscribe component with support for Personal Eventing via Pubsub. +
      • Support for web clients: HTTP Polling and HTTP Binding (BOSH) services. +
      • IRC transport. +
      • Component support: interface with networks such as AIM, ICQ and MSN installing special tranports. +
      +

    +

    Chapter 2  Installing ejabberd

    +

    2.1  Installing ejabberd with Binary Installer

    Probably the easiest way to install an ejabberd instant messaging server +is using the binary installer published by ProcessOne. +The binary installers of released ejabberd versions +are available in the ProcessOne ejabberd downloads page: +http://www.process-one.net/en/ejabberd/downloads

    The installer will deploy and configure a full featured ejabberd +server and does not require any extra dependencies.

    In *nix systems, remember to set executable the binary installer before starting it. For example: +

    chmod +x ejabberd-2.0.0_1-linux-x86-installer.bin
    +./ejabberd-2.0.0_1-linux-x86-installer.bin
    +

    ejabberd can be started manually at any time, +or automatically by the operating system at system boot time.

    To start and stop ejabberd manually, +use the desktop shortcuts created by the installer. +If the machine doesn’t have a graphical system, use the scripts ’start’ +and ’stop’ in the ’bin’ directory where ejabberd is installed.

    The Windows installer also adds ejabberd as a system service, +and a shortcut to a debug console for experienced administrators. +If you want ejabberd to be started automatically at boot time, +go to the Windows service settings and set ejabberd to be automatically started. +Note that the Windows service is a feature still in development, +and for example it doesn’t read the file ejabberdctl.cfg.

    On a *nix system, if you want ejabberd to be started as daemon at boot time, +copy ejabberd.init from the ’bin’ directory to something like /etc/init.d/ejabberd +(depending on your distribution). +Create a system user called ejabberd; +it will be used by the script to start the server. +Then you can call /etc/inid.d/ejabberd start as root to start the server.

    If ejabberd doesn’t start correctly in Windows, +try to start it using the shortcut in desktop or start menu. +If the window shows error 14001, the solution is to install: +"Microsoft Visual C++ 2005 SP1 Redistributable Package". +You can download it from +www.microsoft.com. +Then uninstall ejabberd and install it again.

    If ejabberd doesn’t start correctly and a crash dump is generated, +there was a severe problem. +You can try starting ejabberd with +the script bin/live.bat in Windows, +or with the command bin/ejabberdctl live in other Operating Systems. +This way you see the error message provided by Erlang +and can identify what is exactly the problem.

    The ejabberdctl administration script is included in the bin directory. +Please refer to the section 4.1 for details about ejabberdctl, +and configurable options to fine tune the Erlang runtime system.

    +

    2.2  Installing ejabberd with Operating System Specific Packages

    Some Operating Systems provide a specific ejabberd package adapted to +the system architecture and libraries. +It usually also checks dependencies +and performs basic configuration tasks like creating the initial +administrator account. Some examples are Debian and Gentoo. Consult the +resources provided by your Operating System for more information.

    Usually those packages create a script like /etc/init.d/ejabberd +to start and stop ejabberd as a service at boot time.

    +

    2.3  Installing ejabberd with CEAN

    CEAN +(Comprehensive Erlang Archive Network) is a repository that hosts binary +packages from many Erlang programs, including ejabberd and all its dependencies. +The binaries are available for many different system architectures, so this is an +alternative to the binary installer and Operating System’s ejabberd packages.

    You will have to create your own ejabberd start +script depending of how you handle your CEAN installation. +The default ejabberdctl script is located +into ejabberd’s priv directory and can be used as an example.

    +

    2.4  Installing ejabberd from Source Code

    +

    The canonical form for distribution of ejabberd stable releases is the source code package. +Compiling ejabberd from source code is quite easy in *nix systems, +as long as your system have all the dependencies.

    +

    2.4.1  Requirements

    +

    To compile ejabberd on a ‘Unix-like’ operating system, you need: +

    • +GNU Make +
    • GCC +
    • Libexpat 1.95 or higher +
    • Erlang/OTP R10B-9 or higher. The recommended versions are R12B-5 and R13B04. +
    • OpenSSL 0.9.8 or higher, for STARTTLS, SASL and SSL encryption. +
    • Zlib 1.2.3 or higher, for Stream Compression support (XEP-0138). Optional. +
    • Erlang mysql library. Optional. For MySQL authentication or storage. See section 3.2.1. +
    • Erlang pgsql library. Optional. For PostgreSQL authentication or storage. See section 3.2.3. +
    • PAM library. Optional. For Pluggable Authentication Modules (PAM). See section 3.1.4. +
    • GNU Iconv 1.8 or higher, for the IRC Transport (mod_irc). Optional. Not needed on systems with GNU Libc. See section 3.3.8. +
    • ImageMagick’s Convert program. Optional. For CAPTCHA challenges. See section 3.1.8. +
    • exmpp 0.9.2 or higher. Optional. For import/export user data with XEP-0227 XML files. +

    +

    2.4.2  Download Source Code

    +

    Released versions of ejabberd are available in the ProcessOne ejabberd downloads page: +http://www.process-one.net/en/ejabberd/downloads

    +Alternatively, the latest development source code can be retrieved from the Git repository using the commands: +

    git clone git://git.process-one.net/ejabberd/mainline.git ejabberd
    +cd ejabberd
    +git checkout -b 2.1.x origin/2.1.x
    +

    +

    2.4.3  Compile

    +

    To compile ejabberd execute the commands: +

    ./configure
    +make
    +

    The build configuration script allows several options. +To get the full list run the command: +

    ./configure --help
    +

    Some options that you may be interested in modifying: +

    + --prefix=/
    + Specify the path prefix where the files will be copied when running + the make install command.

    --enable-user[=USER]
    + Allow this normal system user to execute the ejabberdctl script + (see section 4.1), + read the configuration files, + read and write in the spool directory, + read and write in the log directory. + The account user and group must exist in the machine + before running make install. + This account doesn’t need an explicit HOME directory, because + /var/lib/ejabberd/ will be used by default.

    --enable-pam
    + Enable the PAM authentication method (see section 3.1.4).

    --enable-odbc or --enable-mssql
    + Required if you want to use an external database. + See section 3.2 for more information.

    --enable-full-xml
    + Enable the use of XML based optimisations. + It will for example use CDATA to escape characters in the XMPP stream. + Use this option only if you are sure your XMPP clients include a fully compliant XML parser.

    --disable-transient-supervisors
    + Disable the use of Erlang/OTP supervision for transient processes.

    --enable-nif
    +Replaces some critical Erlang functions with equivalents written in C to improve performance. +This feature requires Erlang/OTP R13B04 or higher. +

    +

    2.4.4  Install

    +

    To install ejabberd in the destination directories, run the command: +

    make install
    +

    Note that you probably need administrative privileges in the system +to install ejabberd.

    The files and directories created are, by default: +

    + /etc/ejabberd/
    Configuration directory: +
    + ejabberd.cfg
    ejabberd configuration file +
    ejabberdctl.cfg
    Configuration file of the administration script +
    inetrc
    Network DNS configuration file +
    +
    /lib/ejabberd/
    +
    + ebin/
    Erlang binary files (*.beam) +
    include/
    Erlang header files (*.hrl) +
    priv/
    Additional files required at runtime +
    + bin/
    Executable programs +
    lib/
    Binary system libraries (*.so) +
    msgs/
    Translation files (*.msgs) +
    +
    +
    /sbin/ejabberdctl
    Administration script (see section 4.1) +
    /share/doc/ejabberd/
    Documentation of ejabberd +
    /var/lib/ejabberd/
    Spool directory: +
    + .erlang.cookie
    Erlang cookie file (see section 5.3) +
    acl.DCD, ...
    Mnesia database spool files (*.DCD, *.DCL, *.DAT) +
    +
    /var/log/ejabberd/
    Log directory (see section 7.1): +
    + ejabberd.log
    ejabberd service log +
    erlang.log
    Erlang/OTP system log +
    +

    +

    2.4.5  Start

    +

    You can use the ejabberdctl command line administration script to start and stop ejabberd. +If you provided the configure option --enable-user=USER (see 2.4.3), +you can execute ejabberdctl with either that system account or root.

    Usage example: +

    ejabberdctl start
    +
    +ejabberdctl status
    +The node ejabberd@localhost is started with status: started
    +ejabberd is running in that node
    +
    +ejabberdctl stop
    +

    If ejabberd doesn’t start correctly and a crash dump is generated, +there was a severe problem. +You can try starting ejabberd with +the command ejabberdctl live +to see the error message provided by Erlang +and can identify what is exactly the problem.

    Please refer to the section 4.1 for details about ejabberdctl, +and configurable options to fine tune the Erlang runtime system.

    If you want ejabberd to be started as daemon at boot time, +copy ejabberd.init to something like /etc/init.d/ejabberd +(depending on your distribution). +Create a system user called ejabberd; +it will be used by the script to start the server. +Then you can call /etc/inid.d/ejabberd start as root to start the server.

    +

    2.4.6  Specific Notes for BSD

    +

    The command to compile ejabberd in BSD systems is: +

    gmake
    +

    +

    2.4.7  Specific Notes for Sun Solaris

    +

    You need to have GNU install, +but it isn’t included in Solaris. +It can be easily installed if your Solaris system +is set up for blastwave.org +package repository. +Make sure /opt/csw/bin is in your PATH and run: +

    pkg-get -i fileutils
    +

    If that program is called ginstall, +modify the ejabberd Makefile script to suit your system, +for example: +

    cat Makefile | sed s/install/ginstall/ > Makefile.gi
    +

    And finally install ejabberd with: +

    gmake -f Makefile.gi ginstall
    +

    +

    2.4.8  Specific Notes for Microsoft Windows

    +

    +

    Requirements

    To compile ejabberd on a Microsoft Windows system, you need: +

    +

    Compilation

    We assume that we will try to put as much library as possible into C:\sdk\ to make it easier to track what is install for ejabberd.

    1. +Install Erlang emulator (for example, into C:\sdk\erl5.5.5). +
    2. Install Expat library into C:\sdk\Expat-2.0.0 +directory.

      Copy file C:\sdk\Expat-2.0.0\Libs\libexpat.dll +to your Windows system directory (for example, C:\WINNT or +C:\WINNT\System32) +

    3. Build and install the Iconv library into the directory +C:\sdk\GnuWin32.

      Copy file C:\sdk\GnuWin32\bin\lib*.dll to your +Windows system directory (more installation instructions can be found in the +file README.woe32 in the iconv distribution).

      Note: instead of copying libexpat.dll and iconv.dll to the Windows +directory, you can add the directories +C:\sdk\Expat-2.0.0\Libs and +C:\sdk\GnuWin32\bin to the PATH environment +variable. +

    4. Install OpenSSL in C:\sdk\OpenSSL and add C:\sdk\OpenSSL\lib\VC to your path or copy the binaries to your system directory. +
    5. Install ZLib in C:\sdk\gnuWin32. Copy +C:\sdk\GnuWin32\bin\zlib1.dll to your system directory. If you change your path it should already be set after libiconv install. +
    6. Make sure the you can access Erlang binaries from your path. For example: set PATH=%PATH%;"C:\sdk\erl5.6.5\bin" +
    7. Depending on how you end up actually installing the library you might need to check and tweak the paths in the file configure.erl. +
    8. While in the directory ejabberd\src run: +
      configure.bat
      +nmake -f Makefile.win32
      +
    9. Edit the file ejabberd\src\ejabberd.cfg and run +
      werl -s ejabberd -name ejabberd
      +

    +

    2.5  Create a XMPP Account for Administration

    You need a XMPP account and grant him administrative privileges +to enter the ejabberd Web Admin: +

    1. +Register a XMPP account on your ejabberd server, for example admin1@example.org. +There are two ways to register a XMPP account: +
      1. +Using ejabberdctl (see section 4.1): +
        ejabberdctl register admin1 example.org FgT5bk3
        +
      2. Using a XMPP client and In-Band Registration (see section 3.3.18). +
      +
    2. Edit the ejabberd configuration file to give administration rights to the XMPP account you created: +
      {acl, admins, {user, "admin1", "example.org"}}.
      +{access, configure, [{allow, admins}]}.
      +
      You can grant administrative privileges to many XMPP accounts, +and also to accounts in other XMPP servers. +
    3. Restart ejabberd to load the new configuration. +
    4. Open the Web Admin (http://server:port/admin/) in your +favourite browser. Make sure to enter the full JID as username (in this +example: admin1@example.org. The reason that you also need to enter the +suffix, is because ejabberd’s virtual hosting support. +

    +

    2.6  Upgrading ejabberd

    To upgrade an ejabberd installation to a new version, +simply uninstall the old version, and then install the new one. +Of course, it is important that the configuration file +and Mnesia database spool directory are not removed.

    ejabberd automatically updates the Mnesia table definitions at startup when needed. +If you also use an external database for storage of some modules, +check if the release notes of the new ejabberd version +indicates you need to also update those tables.

    +

    Chapter 3  Configuring ejabberd

    +

    +

    3.1  Basic Configuration

    The configuration file will be loaded the first time you start ejabberd. The +content from this file will be parsed and stored in the internal ejabberd database. Subsequently the +configuration will be loaded from the database and any commands in the +configuration file are appended to the entries in the database.

    Note that ejabberd never edits the configuration file. +So, the configuration changes done using the Web Admin +are stored in the database, but are not reflected in the configuration file. +If you want those changes to be use after ejabberd restart, you can either +edit the configuration file, or remove all its content.

    The configuration file contains a sequence of Erlang terms. Lines beginning with a +‘%’ sign are ignored. Each term is a tuple of which the first element is +the name of an option, and any further elements are that option’s values. If the +configuration file do not contain for instance the ‘hosts’ option, the old +host name(s) stored in the database will be used.

    You can override the old values stored in the database by adding next lines to +the beginning of the configuration file: +

    override_global.
    +override_local.
    +override_acls.
    +

    With these lines the old global options (shared between all ejabberd nodes in a +cluster), local options (which are specific for this particular ejabberd node) +and ACLs will be removed before new ones are added.

    +

    3.1.1  Host Names

    +

    The option hosts defines a list containing one or more domains that +ejabberd will serve.

    The syntax is: +

    {hosts, [HostName, ...]}.

    Examples: +

    • +Serving one domain: +
      {hosts, ["example.org"]}.
      +
    • Serving three domains: +
      {hosts, ["example.net", "example.com", "jabber.somesite.org"]}.
      +

    +

    3.1.2  Virtual Hosting

    +

    Options can be defined separately for every virtual host using the +host_config option.

    The syntax is: +

    {host_config, HostName, [Option, ...]}

    Examples: +

    • +Domain example.net is using the internal authentication method while +domain example.com is using the LDAP server running on the +domain localhost to perform authentication: +
      {host_config, "example.net", [{auth_method,   internal}]}.
      +
      +{host_config, "example.com", [{auth_method,   ldap},
      +                              {ldap_servers,  ["localhost"]},
      +                              {ldap_uids,     [{"uid"}]},
      +                              {ldap_rootdn,   "dc=localdomain"},
      +                              {ldap_rootdn,   "dc=example,dc=com"},
      +                              {ldap_password, ""}]}.
      +
    • Domain example.net is using ODBC to perform authentication +while domain example.com is using the LDAP servers running on the domains +localhost and otherhost: +
      {host_config, "example.net", [{auth_method, odbc},
      +                              {odbc_server, "DSN=ejabberd;UID=ejabberd;PWD=ejabberd"}]}.
      +
      +{host_config, "example.com", [{auth_method,   ldap},
      +                              {ldap_servers,  ["localhost", "otherhost"]},
      +                              {ldap_uids,     [{"uid"}]},
      +                              {ldap_rootdn,   "dc=localdomain"},
      +                              {ldap_rootdn,   "dc=example,dc=com"},
      +                              {ldap_password, ""}]}.
      +

    To define specific ejabberd modules in a virtual host, +you can define the global modules option with the common modules, +and later add specific modules to certain virtual hosts. +To accomplish that, instead of defining each option in host_config with the general syntax +

    {OptionName, OptionValue}

    +use this syntax: +

    {{add, OptionName}, OptionValue}

    In this example three virtual hosts have some similar modules, but there are also +other different modules for some specific virtual hosts: +

    %% This ejabberd server has three vhosts:
    +{hosts, ["one.example.org", "two.example.org", "three.example.org"]}.
    +
    +%% Configuration of modules that are common to all vhosts
    +{modules,
    + [
    +  {mod_roster,     []},
    +  {mod_configure,  []},
    +  {mod_disco,      []},
    +  {mod_private,    []},
    +  {mod_time,       []},
    +  {mod_last,       []},
    +  {mod_version,    []}
    + ]}.
    +
    +%% Add some modules to vhost one:
    +{host_config, "one.example.org",
    + [{{add, modules}, [
    +                    {mod_echo,       [{host, "echo-service.one.example.org"}]}
    +                    {mod_http_bind,  []},
    +                    {mod_logxml,     []}
    +                   ]
    +  }
    + ]}.
    +
    +%% Add a module just to vhost two:
    +{host_config, "two.example.org",
    + [{{add, modules}, [
    +                    {mod_echo,       [{host, "mirror.two.example.org"}]}
    +                   ]
    +  }
    + ]}.
    +

    +

    3.1.3  Listening Ports

    +

    The option listen defines for which ports, addresses and network protocols ejabberd +will listen and what services will be run on them. Each element of the list is a +tuple with the following elements: +

    • +Port number. Optionally also the IP address and/or a transport protocol. +
    • Listening module that serves this port. +
    • Options for the TCP socket and for the listening module. +

    The option syntax is: +

    {listen, [Listener, ...]}.

    To define a listener there are several syntax. +

    {PortNumber, Module, [Option, ...]}
    {{PortNumber, IPaddress}, Module, [Option, ...]}
    {{PortNumber, TransportProtocol}, Module, [Option, ...]}
    {{PortNumber, IPaddress, TransportProtocol}, Module, [Option, ...]}

    +

    Port Number, IP Address and Transport Protocol

    The port number defines which port to listen for incoming connections. +It can be a Jabber/XMPP standard port +(see section 5.1) or any other valid port number.

    The IP address can be represented with a string +or an Erlang tuple with decimal or hexadecimal numbers. +The socket will listen only in that network interface. +It is possible to specify a generic address, +so ejabberd will listen in all addresses. +Depending in the type of the IP address, IPv4 or IPv6 will be used. +When not specified the IP address, it will listen on all IPv4 network addresses.

    Some example values for IP address: +

    • +"0.0.0.0" to listen in all IPv4 network interfaces. This is the default value when no IP is specified. +
    • "::" to listen in all IPv6 network interfaces +
    • "10.11.12.13" is the IPv4 address 10.11.12.13 +
    • "::FFFF:127.0.0.1" is the IPv6 address ::FFFF:127.0.0.1/128 +
    • {10, 11, 12, 13} is the IPv4 address 10.11.12.13 +
    • {0, 0, 0, 0, 0, 65535, 32512, 1} is the IPv6 address ::FFFF:127.0.0.1/128 +
    • {16#fdca, 16#8ab6, 16#a243, 16#75ef, 0, 0, 0, 1} is the IPv6 address FDCA:8AB6:A243:75EF::1/128 +

    The transport protocol can be tcp or udp. +Default is tcp.

    +

    Listening Module

    +The available modules, their purpose and the options allowed by each one are: +

    +ejabberd_c2s
    +Handles c2s connections.
    + Options: access, certfile, max_fsm_queue, +max_stanza_size, shaper, +starttls, starttls_required, tls, +zlib +
    ejabberd_s2s_in
    +Handles incoming s2s connections.
    + Options: max_stanza_size, shaper +
    ejabberd_service
    +Interacts with an external component +(as defined in the Jabber Component Protocol (XEP-0114).
    + Options: access, hosts, max_fsm_queue, +service_check_from, shaper +
    ejabberd_stun
    +Handles STUN Binding requests as defined in +RFC 5389.
    + Options: certfile +
    ejabberd_http
    +Handles incoming HTTP connections.
    + Options: captcha, certfile, http_bind, http_poll, +request_handlers, tls, web_admin
    +

    +

    Options

    This is a detailed description of each option allowed by the listening modules: +

    +{access, AccessName}
    This option defines +access to the port. The default value is all. +
    {backlog, Value}
    The backlog value +defines the maximum length that the queue of pending connections may +grow to. This should be increased if the server is going to handle +lots of new incoming connections as they may be dropped if there is +no space in the queue (and ejabberd was not able to accept them +immediately). Default value is 5. +
    captcha
    +Simple web page that allows a user to fill a CAPTCHA challenge (see section 3.1.8). +
    {certfile, Path}
    Full path to a file containing the default SSL certificate. +To define a certificate file specific for a given domain, use the global option domain_certfile. +
    {hosts, [Hostname, ...], [HostOption, ...]}
    +The external Jabber component that connects to this ejabberd_service +can serve one or more hostnames. +As HostOption you can define options for the component; +currently the only allowed option is the password required to the component +when attempt to connect to ejabberd: {password, Secret}. +Note that you cannot define in a single ejabberd_service components of +different services: add an ejabberd_service for each service, +as seen in an example below. +
    http_bind
    +This option enables HTTP Binding (XEP-0124 and XEP-0206) support. HTTP Bind +enables access via HTTP requests to ejabberd from behind firewalls which +do not allow outgoing sockets on port 5222.

    Remember that you must also install and enable the module mod_http_bind.

    If HTTP Bind is enabled, it will be available at +http://server:port/http-bind/. Be aware that support for HTTP Bind +is also needed in the XMPP client. Remark also that HTTP Bind can be +interesting to host a web-based XMPP client such as +JWChat +(check the tutorials to install JWChat with ejabberd and an +embedded local web server +or Apache). +

    http_poll
    +This option enables HTTP Polling (XEP-0025) support. HTTP Polling +enables access via HTTP requests to ejabberd from behind firewalls which +do not allow outgoing sockets on port 5222.

    If HTTP Polling is enabled, it will be available at +http://server:port/http-poll/. Be aware that support for HTTP Polling +is also needed in the XMPP client. Remark also that HTTP Polling can be +interesting to host a web-based XMPP client such as +JWChat.

    The maximum period of time to keep a client session active without +an incoming POST request can be configured with the global option +http_poll_timeout. The default value is five minutes. +The option can be defined in ejabberd.cfg, expressing the time +in seconds: {http_poll_timeout, 300}. +

    {max_fsm_queue, Size}
    +This option specifies the maximum number of elements in the queue of the FSM +(Finite State Machine). +Roughly speaking, each message in such queues represents one XML +stanza queued to be sent into its relevant outgoing stream. If queue size +reaches the limit (because, for example, the receiver of stanzas is too slow), +the FSM and the corresponding connection (if any) will be terminated +and error message will be logged. +The reasonable value for this option depends on your hardware configuration. +However, there is no much sense to set the size above 1000 elements. +This option can be specified for ejabberd_service and +ejabberd_c2s listeners, +or also globally for ejabberd_s2s_out. +If the option is not specified for ejabberd_service or +ejabberd_c2s listeners, +the globally configured value is used. +The allowed values are integers and ’undefined’. +Default value: ’undefined’. +
    {max_stanza_size, Size}
    +This option specifies an +approximate maximum size in bytes of XML stanzas. Approximate, +because it is calculated with the precision of one block of read +data. For example {max_stanza_size, 65536}. The default +value is infinity. Recommended values are 65536 for c2s +connections and 131072 for s2s connections. s2s max stanza size +must always much higher than c2s limit. Change this value with +extreme care as it can cause unwanted disconnect if set too low. +
    {request_handlers, [ {Path, Module}, ...]}
    To define one or several handlers that will serve HTTP requests. +The Path is a list of strings; so the URIs that start with that Path will be served by Module. +For example, if you want mod_foo to serve the URIs that start with /a/b/, +and you also want mod_http_bind to serve the URIs /http-bind/, +use this option: {request_handlers, [{["a", "b"], mod_foo}, {["http-bind"], mod_http_bind}]} +
    {service_check_from, true|false}
    + +This option can be used with ejabberd_service only. +XEP-0114 requires that the domain must match the hostname of the component. +If this option is set to false, ejabberd will allow the component +to send stanzas with any arbitrary domain in the ’from’ attribute. +Only use this option if you are completely sure about it. +The default value is true, to be compliant with XEP-0114. +
    {shaper, none|ShaperName}
    This option defines a +shaper for the port (see section 3.1.6). The default value +is none. +
    starttls
    This option +specifies that STARTTLS encryption is available on connections to the port. +You should also set the certfile option. +You can define a certificate file for a specific domain using the global option domain_certfile. +
    starttls_required
    This option +specifies that STARTTLS encryption is required on connections to the port. +No unencrypted connections will be allowed. +You should also set the certfile option. +You can define a certificate file for a specific domain using the global option domain_certfile. +
    tls
    This option specifies that traffic on +the port will be encrypted using SSL immediately after connecting. +This was the traditional encryption method in the early Jabber software, +commonly on port 5223 for client-to-server communications. +But this method is nowadays deprecated and not recommended. +The preferable encryption method is STARTTLS on port 5222, as defined +RFC 3920: XMPP Core, +which can be enabled in ejabberd with the option starttls. +If this option is set, you should also set the certfile option. +The option tls can also be used in ejabberd_http to support HTTPS. +
    web_admin
    This option +enables the Web Admin for ejabberd administration which is available +at http://server:port/admin/. Login and password are the username and +password of one of the registered users who are granted access by the +‘configure’ access rule. +
    zlib
    This +option specifies that Zlib stream compression (as defined in XEP-0138) +is available on connections to the port. +

    There are some additional global options that can be specified in the ejabberd configuration file (outside listen): +

    +{s2s_use_starttls, true|false}
    +This option defines whether to +use STARTTLS for s2s connections. +
    {s2s_certfile, Path}
    Full path to a +file containing a SSL certificate. +
    {domain_certfile, Domain, Path}
    +Full path to the file containing the SSL certificate for a specific domain. +
    {outgoing_s2s_options, Methods, Timeout}
    +Specify which address families to try, in what order, and connect timeout in milliseconds. +By default it first tries connecting with IPv4, if that fails it tries using IPv6, +with a timeout of 10000 milliseconds. +
    {s2s_dns_options, [ {Property, Value}, ...]}
    +Define properties to use for DNS resolving. +Allowed Properties are: timeout in seconds which default value is 10 +and retries which default value is 2. +
    {s2s_default_policy, allow|deny}
    +The default policy for incoming and outgoing s2s connections to other XMPP servers. +The default value is allow. +
    {{s2s_host, Host}, allow|deny}
    +Defines if incoming and outgoing s2s connections with a specific remote host are allowed or denied. +This allows to restrict ejabberd to only establish s2s connections +with a small list of trusted servers, or to block some specific servers. +
    {s2s_max_retry_delay, Seconds}
    +The maximum allowed delay for retry to connect after a failed connection attempt. +Specified in seconds. The default value is 300 seconds (5 minutes). +
    {max_fsm_queue, Size}
    +This option specifies the maximum number of elements in the queue of the FSM +(Finite State Machine). +Roughly speaking, each message in such queues represents one XML +stanza queued to be sent into its relevant outgoing stream. If queue size +reaches the limit (because, for example, the receiver of stanzas is too slow), +the FSM and the corresponding connection (if any) will be terminated +and error message will be logged. +The reasonable value for this option depends on your hardware configuration. +However, there is no much sense to set the size above 1000 elements. +This option can be specified for ejabberd_service and +ejabberd_c2s listeners, +or also globally for ejabberd_s2s_out. +If the option is not specified for ejabberd_service or +ejabberd_c2s listeners, +the globally configured value is used. +The allowed values are integers and ’undefined’. +Default value: ’undefined’. +
    {route_subdomains, local|s2s}
    +Defines if ejabberd must route stanzas directed to subdomains locally (compliant with +RFC 3920: XMPP Core), +or to foreign server using S2S (compliant with +RFC 3920 bis). +

    +

    Examples

    For example, the following simple configuration defines: +

    • +There are three domains. The default certificate file is server.pem. +However, the c2s and s2s connections to the domain example.com use the file example_com.pem. +
    • Port 5222 listens for c2s connections with STARTTLS, +and also allows plain connections for old clients. +
    • Port 5223 listens for c2s connections with the old SSL. +
    • Port 5269 listens for s2s connections with STARTTLS. The socket is set for IPv6 instead of IPv4. +
    • Port 3478 listens for STUN requests over UDP. +
    • Port 5280 listens for HTTP requests, and serves the HTTP Poll service. +
    • Port 5281 listens for HTTP requests, and serves the Web Admin using HTTPS as explained in +section 4.3. The socket only listens connections to the IP address 127.0.0.1. +
    {hosts, ["example.com", "example.org", "example.net"]}.
    +{listen,
    + [
    +  {5222, ejabberd_c2s, [
    +                        {access, c2s},
    +                        {shaper, c2s_shaper},
    +                        starttls, {certfile, "/etc/ejabberd/server.pem"},
    +                        {max_stanza_size, 65536}
    +                       ]},
    +  {5223, ejabberd_c2s, [
    +                        {access, c2s},
    +                        {shaper, c2s_shaper},
    +                        tls, {certfile, "/etc/ejabberd/server.pem"},
    +                        {max_stanza_size, 65536}
    +                       ]},
    +  {{5269, "::"}, ejabberd_s2s_in, [
    +                                   {shaper, s2s_shaper},
    +                                   {max_stanza_size, 131072}
    +                                  ]},
    +  {{3478, udp}, ejabberd_stun, []},
    +  {5280, ejabberd_http, [
    +                         http_poll
    +                        ]},
    +  {{5281, "127.0.0.1"}, ejabberd_http, [
    +                                        web_admin,
    +                                        tls, {certfile, "/etc/ejabberd/server.pem"},
    +                                       ]}
    + ]
    +}.
    +{s2s_use_starttls, true}.
    +{s2s_certfile, "/etc/ejabberd/server.pem"}.
    +{domain_certfile, "example.com", "/etc/ejabberd/example_com.pem"}.
    +

    In this example, the following configuration defines that: +

    • +c2s connections are listened for on port 5222 (all IPv4 addresses) and +on port 5223 (SSL, IP 192.168.0.1 and fdca:8ab6:a243:75ef::1) and denied +for the user called ‘bad’. +
    • s2s connections are listened for on port 5269 (all IPv4 addresses) +with STARTTLS for secured traffic enabled. +Incoming and outgoing connections of remote XMPP servers are denied, +only two servers can connect: "jabber.example.org" and "example.com". +
    • Port 5280 is serving the Web Admin and the HTTP Polling service +in all the IPv4 addresses. Note +that it is also possible to serve them on different ports. The second +example in section 4.3 shows how exactly this can be done. +
    • All users except for the administrators have a traffic of limit +1,000 Bytes/second +
    • The +AIM transport +aim.example.org is connected to port 5233 on localhost IP addresses +(127.0.0.1 and ::1) with password ‘aimsecret’. +
    • The ICQ transport JIT (icq.example.org and +sms.example.org) is connected to port 5234 with password +‘jitsecret’. +
    • The +MSN transport +msn.example.org is connected to port 5235 with password +‘msnsecret’. +
    • The +Yahoo! transport +yahoo.example.org is connected to port 5236 with password +‘yahoosecret’. +
    • The Gadu-Gadu transport gg.example.org is +connected to port 5237 with password ‘ggsecret’. +
    • The +Jabber Mail Component +jmc.example.org is connected to port 5238 with password +‘jmcsecret’. +
    • The service custom has enabled the special option to avoiding checking the from attribute in the packets send by this component. The component can send packets in behalf of any users from the server, or even on behalf of any server. +
    {acl, blocked, {user, "bad"}}.
    +{access, c2s, [{deny, blocked},
    +               {allow, all}]}.
    +{shaper, normal, {maxrate, 1000}}.
    +{access, c2s_shaper, [{none, admin},
    +                      {normal, all}]}.
    +{listen,
    + [{5222, ejabberd_c2s, [
    +                        {access, c2s},
    +                        {shaper, c2s_shaper}
    +                       ]},
    +  {{5223, {192, 168, 0, 1}}, ejabberd_c2s, [
    +                                            {access, c2s},
    +                                            ssl, {certfile, "/path/to/ssl.pem"}
    +                                           ]},
    +  {{5223, {16#fdca, 16#8ab6, 16#a243, 16#75ef, 0, 0, 0, 1}},
    +   ejabberd_c2s, [
    +                  {access, c2s},
    +                  ssl, {certfile, "/path/to/ssl.pem"}
    +                 ]},
    +  {5269, ejabberd_s2s_in, []},
    +  {{5280, {0, 0, 0, 0}}, ejabberd_http, [
    +                                         http_poll,
    +                                         web_admin
    +                                        ]},
    +  {{5233, {127, 0, 0, 1}}, ejabberd_service, [
    +                                              {hosts, ["aim.example.org"],
    +                                                 [{password, "aimsecret"}]}
    +                                             ]},
    +  {{5233, "::1"}, ejabberd_service, [
    +                                     {hosts, ["aim.example.org"],
    +                                        [{password, "aimsecret"}]}
    +                                    ]},
    +  {5234, ejabberd_service, [{hosts, ["icq.example.org", "sms.example.org"],
    +                             [{password, "jitsecret"}]}]},
    +  {5235, ejabberd_service, [{hosts, ["msn.example.org"],
    +                             [{password, "msnsecret"}]}]},
    +  {5236, ejabberd_service, [{hosts, ["yahoo.example.org"],
    +                             [{password, "yahoosecret"}]}]},
    +  {5237, ejabberd_service, [{hosts, ["gg.example.org"],
    +                             [{password, "ggsecret"}]}]},
    +  {5238, ejabberd_service, [{hosts, ["jmc.example.org"],
    +                             [{password, "jmcsecret"}]}]},
    +  {5239, ejabberd_service, [{hosts, ["custom.example.org"],
    +                             [{password, "customsecret"}]},
    +                            {service_check_from, false}]}
    + ]
    +}.
    +{s2s_use_starttls, true}.
    +{s2s_certfile, "/path/to/ssl.pem"}.
    +{s2s_default_policy, deny}.
    +{{s2s_host,"jabber.example.org"}, allow}.
    +{{s2s_host,"example.com"}, allow}.
    +

    Note, that for services based in jabberd14 or WPJabber +you have to make the transports log and do XDB by themselves: +

      <!--
    +     You have to add elogger and rlogger entries here when using ejabberd.
    +     In this case the transport will do the logging.
    +  -->
    +
    +  <log id='logger'>
    +    <host/>
    +    <logtype/>
    +    <format>%d: [%t] (%h): %s</format>
    +    <file>/var/log/jabber/service.log</file>
    +  </log>
    +
    +  <!--
    +     Some XMPP server implementations do not provide
    +     XDB services (for example, jabberd2 and ejabberd).
    +     xdb_file.so is loaded in to handle all XDB requests.
    +  -->
    +
    +  <xdb id="xdb">
    +    <host/>
    +    <load>
    +      <!-- this is a lib of wpjabber or jabberd14 -->
    +      <xdb_file>/usr/lib/jabber/xdb_file.so</xdb_file>
    +      </load>
    +    <xdb_file xmlns="jabber:config:xdb_file">
    +      <spool><jabberd:cmdline flag='s'>/var/spool/jabber</jabberd:cmdline></spool>
    +    </xdb_file>
    +  </xdb>
    +

    +

    3.1.4  Authentication

    +

    The option auth_method defines the authentication methods that are used +for user authentication. The syntax is: +

    {auth_method, [Method, ...]}.

    The following authentication methods are supported by ejabberd: +

    • +internal (default) — See section 3.1.4. +
    • external — See section 3.1.4. +
    • ldap — See section 3.2.5. +
    • odbc — See section 3.2.1, 3.2.3, +3.2.2 and 3.2.4. +
    • anonymous — See section 3.1.4. +
    • pam — See section 3.1.4. +

    Account creation is only supported by internal, external and odbc methods.

    +

    Internal

    +

    ejabberd uses its internal Mnesia database as the default authentication method. +The value internal will enable the internal authentication method.

    Examples: +

    • +To use internal authentication on example.org and LDAP +authentication on example.net: +
      {host_config, "example.org", [{auth_method, [internal]}]}.
      +{host_config, "example.net", [{auth_method, [ldap]}]}.
      +
    • To use internal authentication on all virtual hosts: +
      {auth_method, internal}.
      +

    +

    External Script

    +

    In this authentication method, when ejabberd starts, +it start a script, and calls it to perform authentication tasks.

    The server administrator can write the external authentication script +in any language. +The details on the interface between ejabberd and the script are described +in the ejabberd Developers Guide. +There are also several example authentication scripts.

    These are the specific options: +

    +{extauth_program, PathToScript}
    +Indicate in this option the full path to the external authentication script. +The script must be executable by ejabberd.
    {extauth_instances, Integer}
    +Indicate how many instances of the script to run simultaneously to serve authentication in the virtual host. +The default value is the minimum number: 1.
    {extauth_cache, false|CacheTimeInteger}
    +The value false disables the caching feature, this is the default. +The integer 0 (zero) enables caching for statistics, but doesn’t use that cached information to authenticate users. +If another integer value is set, caching is enabled both for statistics and for authentication: +the CacheTimeInteger indicates the number of seconds that ejabberd can reuse +the authentication information since the user last disconnected, +to verify again the user authentication without querying again the extauth script. +Note: caching should not be enabled in a host if internal auth is also enabled. +If caching is enabled, mod_last or mod_last_odbc must be enabled also in that vhost. +

    This example sets external authentication, the extauth script, enables caching for 10 minutes, +and starts three instances of the script for each virtual host defined in ejabberd: +

    {auth_method, [external]}.
    +{extauth_program, "/etc/ejabberd/JabberAuth.class.php"}.
    +{extauth_cache, 600}.
    +{extauth_instances, 3}. 
    +

    +

    SASL Anonymous and Anonymous Login

    +

    The value anonymous will enable the internal authentication method.

    The anonymous authentication method can be configured with the following +options. Remember that you can use the host_config option to set virtual +host specific options (see section 3.1.2). Note that there also +is a detailed tutorial regarding SASL +Anonymous and anonymous login configuration.

    +{allow_multiple_connections, false|true}
    This option is only used +when the anonymous mode is +enabled. Setting it to true means that the same username can be taken +multiple times in anonymous login mode if different resource are used to +connect. This option is only useful in very special occasions. The default +value is false. +
    {anonymous_protocol, sasl_anon | login_anon | both}
    +sasl_anon means +that the SASL Anonymous method will be used. login_anon means that the +anonymous login method will be used. both means that SASL Anonymous and +login anonymous are both enabled. +

    Those options are defined for each virtual host with the host_config +parameter (see section 3.1.2).

    Examples: +

    • +To enable anonymous login on all virtual hosts: +
      {auth_method, [anonymous]}.
      +{anonymous_protocol, login_anon}.
      +
    • Similar as previous example, but limited to public.example.org: +
      {host_config, "public.example.org", [{auth_method, [anonymous]},
      +                                     {anonymous_protocol, login_anon}]}.
      +
    • To enable anonymous login and internal authentication on a virtual host: +
      {host_config, "public.example.org", [{auth_method, [internal,anonymous]},
      +                                     {anonymous_protocol, login_anon}]}.
      +
    • To enable SASL Anonymous on a virtual host: +
      {host_config, "public.example.org", [{auth_method, [anonymous]},
      +                                     {anonymous_protocol, sasl_anon}]}.
      +
    • To enable SASL Anonymous and anonymous login on a virtual host: +
      {host_config, "public.example.org", [{auth_method, [anonymous]},
      +                                     {anonymous_protocol, both}]}.
      +
    • To enable SASL Anonymous, anonymous login, and internal authentication on +a virtual host: +
      {host_config, "public.example.org", [{auth_method, [internal,anonymous]},
      +                                     {anonymous_protocol, both}]}.
      +

    +

    PAM Authentication

    +

    ejabberd supports authentication via Pluggable Authentication Modules (PAM). +PAM is currently supported in AIX, FreeBSD, HP-UX, Linux, Mac OS X, NetBSD and Solaris. +PAM authentication is disabled by default, so you have to configure and compile +ejabberd with PAM support enabled: +

    ./configure --enable-pam && make install
    +

    Options: +

    +{pam_service, Name}
    This option defines the PAM service name. +Default is "ejabberd". Refer to the PAM documentation of your operation system +for more information. +
    {pam_userinfotype, username|jid}
    +This option defines what type of information about the user ejabberd +provides to the PAM service: only the username, or the user JID. +Default is username. +

    Example: +

    {auth_method, [pam]}.
    +{pam_service, "ejabberd"}.
    +

    Though it is quite easy to set up PAM support in ejabberd, PAM itself introduces some +security issues:

    • +To perform PAM authentication ejabberd uses external C-program called +epam. By default, it is located in /var/lib/ejabberd/priv/bin/ +directory. You have to set it root on execution in the case when your PAM module +requires root privileges (pam_unix.so for example). Also you have to grant access +for ejabberd to this file and remove all other permissions from it. +Execute with root privileges: +
      chown root:ejabberd /var/lib/ejabberd/priv/bin/epam
      +chmod 4750 /var/lib/ejabberd/priv/bin/epam
      +
    • Make sure you have the latest version of PAM installed on your system. +Some old versions of PAM modules cause memory leaks. If you are not able to use the latest +version, you can kill(1) epam process periodically to reduce its memory +consumption: ejabberd will restart this process immediately. +
    • epam program tries to turn off delays on authentication failures. +However, some PAM modules ignore this behavior and rely on their own configuration options. +You can create a configuration file ejabberd.pam. +This example shows how to turn off delays in pam_unix.so module: +
      #%PAM-1.0
      +auth        sufficient  pam_unix.so likeauth nullok nodelay
      +account     sufficient  pam_unix.so
      +
      That is not a ready to use configuration file: you must use it +as a hint when building your own PAM configuration instead. Note that if you want to disable +delays on authentication failures in the PAM configuration file, you have to restrict access +to this file, so a malicious user can’t use your configuration to perform brute-force +attacks. +
    • You may want to allow login access only for certain users. pam_listfile.so +module provides such functionality. +
    • If you use pam_winbind to authorise against a Windows Active Directory, +then /etc/nssswitch.conf must be configured to use winbind as well. +

    +

    3.1.5  Access Rules

    +

    +

    ACL Definition

    +

    Access control in ejabberd is performed via Access Control Lists (ACLs). The +declarations of ACLs in the configuration file have the following syntax: +

    {acl, ACLName, ACLValue}.

    ACLValue can be one of the following: +

    +all
    Matches all JIDs. Example: +
    {acl, all, all}.
    +
    {user, Username}
    Matches the user with the name +Username at the first virtual host. Example: +
    {acl, admin, {user, "yozhik"}}.
    +
    {user, Username, Server}
    Matches the user with the JID +Username@Server and any resource. Example: +
    {acl, admin, {user, "yozhik", "example.org"}}.
    +
    {server, Server}
    Matches any JID from server +Server. Example: +
    {acl, exampleorg, {server, "example.org"}}.
    +
    {resource, Resource}
    Matches any JID with a resource +Resource. Example: +
    {acl, mucklres, {resource, "muckl"}}.
    +
    {shared_group, Groupname}
    Matches any member of a Shared Roster Group with name Groupname in the virtual host. Example: +
    {acl, techgroupmembers, {shared_group, "techteam"}}.
    +
    {shared_group, Groupname, Server}
    Matches any member of a Shared Roster Group with name Groupname in the virtual host Server. Example: +
    {acl, techgroupmembers, {shared_group, "techteam", "example.org"}}.
    +
    {user_regexp, Regexp}
    Matches any local user with a name that +matches Regexp on local virtual hosts. Example: +
    {acl, tests, {user_regexp, "^test[0-9]*$"}}.
    +
    {user_regexp, UserRegexp, Server}
    Matches any user with a name +that matches Regexp at server Server. Example: +
    {acl, tests, {user_Userregexp, "^test", "example.org"}}.
    +
    {server_regexp, Regexp}
    Matches any JID from the server that +matches Regexp. Example: +
    {acl, icq, {server_regexp, "^icq\\."}}.
    +
    {resource_regexp, Regexp}
    Matches any JID with a resource that +matches Regexp. Example: +
    {acl, icq, {resource_regexp, "^laptop\\."}}.
    +
    {node_regexp, UserRegexp, ServerRegexp}
    Matches any user +with a name that matches UserRegexp at any server that matches +ServerRegexp. Example: +
    {acl, yohzik, {node_regexp, "^yohzik$", "^example.(com|org)$"}}.
    +
    {user_glob, Glob}
    +
    {user_glob, Glob, Server}
    +
    {server_glob, Glob}
    +
    {resource_glob, Glob}
    +
    {node_glob, UserGlob, ServerGlob}
    This is the same as +above. However, it uses shell glob patterns instead of regexp. These patterns +can have the following special characters: +
    +*
    matches any string including the null string. +
    ?
    matches any single character. +
    [...]
    matches any of the enclosed characters. Character +ranges are specified by a pair of characters separated by a ‘-’. +If the first character after ‘[’ is a ‘!’, any +character not enclosed is matched. +
    +

    The following ACLName are pre-defined: +

    +all
    Matches any JID. +
    none
    Matches no JID. +

    +

    Access Rights

    +

    An entry allowing or denying access to different services. +The syntax is: +

    {access, AccessName, [ {allow|deny, ACLName}, ...]}.

    When a JID is checked to have access to Accessname, the server +sequentially checks if that JID matches any of the ACLs that are named in the +second elements of the tuples in the list. If it matches, the first element of +the first matched tuple is returned, otherwise the value ‘deny’ is +returned.

    If you define specific Access rights in a virtual host, +remember that the globally defined Access rights have precedence over those. +This means that, in case of conflict, the Access granted or denied in the global server is used +and the Access of a virtual host doesn’t have effect.

    Example: +

    {access, configure, [{allow, admin}]}.
    +{access, something, [{deny, badmans},
    +                     {allow, all}]}.
    +

    The following AccessName are pre-defined: +

    +all
    Always returns the value ‘allow’. +
    none
    Always returns the value ‘deny’. +

    +

    Limiting Opened Sessions with ACL

    +

    The special access max_user_sessions specifies the maximum +number of sessions (authenticated connections) per user. If a user +tries to open more sessions by using different resources, the first +opened session will be disconnected. The error session replaced +will be sent to the disconnected session. The value for this option +can be either a number, or infinity. The default value is +infinity.

    The syntax is: +

    {access, max_user_sessions, [ {MaxNumber, ACLName}, ...]}.

    This example limits the number of sessions per user to 5 for all users, and to 10 for admins: +

    {access, max_user_sessions, [{10, admin}, {5, all}]}.
    +

    +

    Several connections to a remote XMPP server with ACL

    +

    The special access max_s2s_connections specifies how many +simultaneous S2S connections can be established to a specific remote XMPP server. +The default value is 1. +There’s also available the access max_s2s_connections_per_node.

    The syntax is: +

    {access, max_s2s_connections, [ {MaxNumber, ACLName}, ...]}.

    Examples: +

    • +Allow up to 3 connections with each remote server: +
      {access, max_s2s_connections, [{3, all}]}.
      +

    +

    3.1.6  Shapers

    +

    Shapers enable you to limit connection traffic. +The syntax is: +

    {shaper, ShaperName, Kind}.

    +Currently only one kind of shaper called maxrate is available. It has the +following syntax: +

    {maxrate, Rate}

    +where Rate stands for the maximum allowed incoming rate in bytes per +second. +When a connection exceeds this limit, ejabberd stops reading from the socket +until the average rate is again below the allowed maximum.

    Examples: +

    • +To define a shaper named ‘normal’ with traffic speed limited to +1,000 bytes/second: +
      {shaper, normal, {maxrate, 1000}}.
      +
    • To define a shaper named ‘fast’ with traffic speed limited to +50,000 bytes/second: +
      {shaper, fast, {maxrate, 50000}}.
      +

    +

    3.1.7  Default Language

    +

    The option language defines the default language of server strings that +can be seen by XMPP clients. If a XMPP client does not support +xml:lang, the specified language is used.

    The option syntax is: +

    {language, Language}.

    The default value is en. +In order to take effect there must be a translation file +Language.msg in ejabberd’s msgs directory.

    For example, to set Russian as default language: +

    {language, "ru"}.
    +

    Appendix A provides more details about internationalization and localization.

    +

    3.1.8  CAPTCHA

    +

    Some ejabberd modules can be configured to require a CAPTCHA challenge on certain actions. +If the client does not support CAPTCHA Forms (XEP-0158), +a web link is provided so the user can fill the challenge in a web browser.

    An example script is provided that generates the image +using ImageMagick’s Convert program.

    The configurable options are: +

    +{captcha_cmd, Path}
    +Full path to a script that generates the image. +The default value is an empty string: "" +
    {captcha_host, Host}
    +Host part of the URL sent to the user. +You can include the port number. +The URL sent to the user is formed by: http://Host/captcha/ +The default value is the first hostname configured. +

    Additionally, an ejabberd_http listener must be enabled with the captcha option. +See section 3.1.3.

    Example configuration: +

    {hosts, ["example.org"]}.
    +
    +{captcha_cmd, "/lib/ejabberd/priv/bin/captcha.sh"}.
    +{captcha_host, "example.org:5280"}.
    +
    +{listen,
    + [
    +  ...
    +  {5280, ejabberd_http, [
    +                         captcha,
    +                         ...
    +                        ]
    +  }
    +
    +]}.
    +

    +

    3.1.9  STUN

    +

    ejabberd is able to act as a stand-alone STUN server +(RFC 5389). Currently only Binding usage +is supported. In that role ejabberd helps clients with Jingle ICE (XEP-0176) support to discover their external addresses and ports.

    You should configure ejabberd_stun listening module as described in 3.1.3 section. +If certfile option is defined, ejabberd multiplexes TCP and +TLS over TCP connections on the same port. Obviously, certfile option +is defined for tcp only. Note however that TCP or TLS over TCP +support is not required for Binding usage and is reserved for +TURN +functionality. Feel free to configure udp transport only.

    Example configuration: +

    {listen,
    + [
    +  ...
    +  {{3478, udp}, ejabberd_stun, []},
    +  {3478, ejabberd_stun, []},
    +  {5349, ejabberd_stun, [{certfile, "/etc/ejabberd/server.pem"}]},
    +  ...
    + ]
    +}.
    +

    You also need to configure DNS SRV records properly so clients can easily discover a +STUN server serving your XMPP domain. Refer to section +DNS Discovery of a Server +of RFC 5389 for details.

    Example DNS SRV configuration: +

    _stun._udp   IN SRV  0 0 3478 stun.example.com.
    +_stun._tcp   IN SRV  0 0 3478 stun.example.com.
    +_stuns._tcp  IN SRV  0 0 5349 stun.example.com.
    +

    +

    3.1.10  Include Additional Configuration Files

    +

    The option include_config_file in a configuration file instructs ejabberd to include other configuration files immediately.

    The basic syntax is: +

    {include_config_file, Filename}.

    +It is possible to specify suboptions using the full syntax: +

    {include_config_file, Filename, [Suboption, ...]}.

    The filename can be indicated either as an absolute path, +or relative to the main ejabberd configuration file. +It isn’t possible to use wildcards. +The file must exist and be readable.

    The allowed suboptions are: +

    +{disallow, [Optionname, ...]}
    Disallows the usage of those options in the included configuration file. +The options that match this criteria are not accepted. +The default value is an empty list: [] +
    {allow_only, [Optionname, ...]}
    Allows only the usage of those options in the included configuration file. +The options that do not match this criteria are not accepted. +The default value is: all +

    This is a basic example: +

    {include_config_file, "/etc/ejabberd/additional.cfg"}.
    +

    In this example, the included file is not allowed to contain a listen option. +If such an option is present, the option will not be accepted. +The file is in a subdirectory from where the main configuration file is. +

    {include_config_file, "./example.org/additional_not_listen.cfg", [{disallow, [listen]}]}.
    +

    In this example, ejabberd.cfg defines some ACL and Access rules, +and later includes another file with additional rules: +

    {acl, admin, {user, "admin", "localhost"}}.
    +{access, announce, [{allow, admin}]}.
    +{include_config_file, "/etc/ejabberd/acl_and_access.cfg", [{allow_only, [acl, access]}]}.
    +

    and content of the file acl_and_access.cfg can be, for example: +

    {acl, admin, {user, "bob", "localhost"}}.
    +{acl, admin, {user, "jan", "localhost"}}.
    +

    +

    3.1.11  Option Macros in Configuration File

    +

    In the ejabberd configuration file, +it is possible to define a macro for a value +and later use this macro when defining an option.

    A macro is defined with this syntax: +

    {define_macro, ’MACRO’, Value}.

    +The MACRO must be surrounded by single quotation marks, +and all letters in uppercase; check the examples bellow. +The value can be any valid arbitrary Erlang term.

    The first definition of a macro is preserved, +and additional definitions of the same macro are forgotten.

    Macros are processed after +additional configuration files have been included, +so it is possible to use macros that +are defined in configuration files included before the usage.

    It isn’t possible to use a macro in the definition +of another macro.

    There are two ways to use a macro: +

    ’MACRO’
    +You can put this instead of a value in an ejabberd option, +and will be replaced with the value previously defined. +If the macro is not defined previously, +the program will crash and report an error.
    {use_macro, ’MACRO’, Defaultvalue}
    +Use a macro even if it may not be defined. +If the macro is not defined previously, +the provided defaultvalue is used. +This usage behaves as if it were defined and used this way: +
    {define_macro, 'MACRO', Defaultvalue}.
    +'MACRO'
    +

    This example shows the basic usage of a macro: +

    {define_macro, 'LOG_LEVEL_NUMBER', 5}.
    +{loglevel, 'LOG_LEVEL_NUMBER'}.
    +

    The resulting option interpreted by ejabberd is: {loglevel, 5}.

    This example shows that values can be any arbitrary Erlang term: +

    {define_macro, 'USERBOB', {user, "bob", "localhost"}}.
    +{acl, admin, 'USERBOB'}.
    +

    The resulting option interpreted by ejabberd is: {acl, admin, {user, "bob", "localhost"}}.

    This complex example: +

    {define_macro, 'NUMBER_PORT_C2S', 5222}.
    +{define_macro, 'PORT_S2S_IN', {5269, ejabberd_s2s_in, []}}.
    +{listen,
    + [
    +  {'NUMBER_PORT_C2S', ejabberd_c2s, []},
    +  'PORT_S2S_IN',
    +  {{use_macro, 'NUMBER_PORT_HTTP', 5280}, ejabberd_http, []}
    + ]
    +}.
    +

    produces this result after being interpreted: +

    {listen,
    + [
    +  {5222, ejabberd_c2s, []},
    +  {5269, ejabberd_s2s_in, []},
    +  {5280, ejabberd_http, []}
    + ]
    +}.
    +

    +

    3.2  Database and LDAP Configuration

    + +

    ejabberd uses its internal Mnesia database by default. However, it is +possible to use a relational database or an LDAP server to store persistent, +long-living data. ejabberd is very flexible: you can configure different +authentication methods for different virtual hosts, you can configure different +authentication mechanisms for the same virtual host (fallback), you can set +different storage systems for modules, and so forth.

    The following databases are supported by ejabberd: +

    The following LDAP servers are tested with ejabberd: +

    • +Active Directory +(see section 3.2.5) +
    • OpenLDAP +
    • Normally any LDAP compatible server should work; inform us about your +success with a not-listed server so that we can list it here. +

    Important note about virtual hosting: +if you define several domains in ejabberd.cfg (see section 3.1.1), +you probably want that each virtual host uses a different configuration of database, authentication and storage, +so that usernames do not conflict and mix between different virtual hosts. +For that purpose, the options described in the next sections +must be set inside a host_config for each vhost (see section 3.1.2). +For example: +

    {host_config, "public.example.org", [
    +  {odbc_server, {pgsql, "localhost", "database-public-example-org", "ejabberd", "password"}},
    +  {auth_method, [odbc]}
    +]}.
    +

    +

    3.2.1  MySQL

    +

    Although this section will describe ejabberd’s configuration when you want to +use the native MySQL driver, it does not describe MySQL’s installation and +database creation. Check the MySQL documentation and the tutorial Using ejabberd with MySQL native driver for information regarding these topics. +Note that the tutorial contains information about ejabberd’s configuration +which is duplicate to this section.

    Moreover, the file mysql.sql in the directory src/odbc might be interesting for +you. This file contains the ejabberd schema for MySQL. At the end of the file +you can find information to update your database schema.

    +

    Driver Compilation

    +

    You can skip this step if you installed ejabberd using a binary installer or +if the binary packages of ejabberd you are using include support for MySQL.

    1. +First, install the Erlang +MySQL library. Make sure the compiled files are in your Erlang path; you can +put them for example in the same directory as your ejabberd .beam files. +
    2. Then, configure and install ejabberd with ODBC support enabled (this is +also needed for native MySQL support!). This can be done, by using next +commands: +
      ./configure --enable-odbc && make install
      +

    +

    Database Connection

    +

    The actual database access is defined in the option odbc_server. Its +value is used to define if we want to use ODBC, or one of the two native +interface available, PostgreSQL or MySQL.

    To use the native MySQL interface, you can pass a tuple of the following form as +parameter: +

    {mysql, "Server", "Database", "Username", "Password"}

    mysql is a keyword that should be kept as is. For example: +

    {odbc_server, {mysql, "localhost", "test", "root", "password"}}.

    Optionally, it is possible to define the MySQL port to use. This +option is only useful, in very rare cases, when you are not running +MySQL with the default port setting. The mysql parameter +can thus take the following form: +

    {mysql, "Server", Port, "Database", "Username", "Password"}

    The Port value should be an integer, without quotes. For example: +

    {odbc_server, {mysql, "localhost", Port, "test", "root", "password"}}.

    By default ejabberd opens 10 connections to the database for each virtual host. +Use this option to modify the value: +

    {odbc_pool_size, 10}.
    +

    You can configure an interval to make a dummy SQL request +to keep alive the connections to the database. +The default value is ’undefined’, so no keepalive requests are made. +Specify in seconds: for example 28800 means 8 hours. +

    {odbc_keepalive_interval, undefined}.
    +

    If the connection to the database fails, ejabberd waits 30 seconds before retrying. +You can modify this interval with this option: +

    {odbc_start_interval, 30}.
    +

    +

    Authentication

    +

    The option value name may be misleading, as the auth_method name is used +for access to a relational database through ODBC, as well as through the native +MySQL interface. Anyway, the first configuration step is to define the odbc +auth_method. For example: +

    {auth_method, [odbc]}.
    +

    +

    Storage

    +

    MySQL also can be used to store information into from several ejabberd +modules. See section 3.3.1 to see which modules have a version +with the ‘_odbc’. This suffix indicates that the module can be used with +relational databases like MySQL. To enable storage to your database, just make +sure that your database is running well (see previous sections), and replace the +suffix-less or ldap module variant with the odbc module variant. Keep in mind +that you cannot have several variants of the same module loaded!

    +

    3.2.2  Microsoft SQL Server

    +

    Although this section will describe ejabberd’s configuration when you want to +use Microsoft SQL Server, it does not describe Microsoft SQL Server’s +installation and database creation. Check the MySQL documentation and the +tutorial Using ejabberd with MySQL native driver for information regarding these topics. +Note that the tutorial contains information about ejabberd’s configuration +which is duplicate to this section.

    Moreover, the file mssql.sql in the directory src/odbc might be interesting for +you. This file contains the ejabberd schema for Microsoft SQL Server. At the end +of the file you can find information to update your database schema.

    +

    Driver Compilation

    +

    You can skip this step if you installed ejabberd using a binary installer or +if the binary packages of ejabberd you are using include support for ODBC.

    If you want to use Microsoft SQL Server with ODBC, you need to configure, +compile and install ejabberd with support for ODBC and Microsoft SQL Server +enabled. This can be done, by using next commands: +

    ./configure --enable-odbc --enable-mssql && make install
    +

    +

    Database Connection

    +

    The configuration of Database Connection for a Microsoft SQL Server +is the same as the configuration for +ODBC compatible servers (see section 3.2.4).

    +

    Authentication

    +

    The configuration of Authentication for a Microsoft SQL Server +is the same as the configuration for +ODBC compatible servers (see section 3.2.4).

    +

    Storage

    +

    Microsoft SQL Server also can be used to store information into from several +ejabberd modules. See section 3.3.1 to see which modules have +a version with the ‘_odbc’. This suffix indicates that the module can be used +with relational databases like Microsoft SQL Server. To enable storage to your +database, just make sure that your database is running well (see previous +sections), and replace the suffix-less or ldap module variant with the odbc +module variant. Keep in mind that you cannot have several variants of the same +module loaded!

    +

    3.2.3  PostgreSQL

    +

    Although this section will describe ejabberd’s configuration when you want to +use the native PostgreSQL driver, it does not describe PostgreSQL’s installation +and database creation. Check the PostgreSQL documentation and the tutorial Using ejabberd with MySQL native driver for information regarding these topics. +Note that the tutorial contains information about ejabberd’s configuration +which is duplicate to this section.

    Also the file pg.sql in the directory src/odbc might be interesting for you. +This file contains the ejabberd schema for PostgreSQL. At the end of the file +you can find information to update your database schema.

    +

    Driver Compilation

    +

    You can skip this step if you installed ejabberd using a binary installer or +if the binary packages of ejabberd you are using include support for +PostgreSQL.

    1. +First, install the Erlang pgsql library from +ejabberd-modules SVN repository. +Make sure the compiled +files are in your Erlang path; you can put them for example in the same +directory as your ejabberd .beam files. +
    2. Then, configure, compile and install ejabberd with ODBC support enabled +(this is also needed for native PostgreSQL support!). This can be done, by +using next commands: +
      ./configure --enable-odbc && make install
      +

    +

    Database Connection

    +

    The actual database access is defined in the option odbc_server. Its +value is used to define if we want to use ODBC, or one of the two native +interface available, PostgreSQL or MySQL.

    To use the native PostgreSQL interface, you can pass a tuple of the following +form as parameter: +

    {pgsql, "Server", "Database", "Username", "Password"}

    pgsql is a keyword that should be kept as is. For example: +

    {odbc_server, {pgsql, "localhost", "database", "ejabberd", "password"}}.

    Optionally, it is possible to define the PostgreSQL port to use. This +option is only useful, in very rare cases, when you are not running +PostgreSQL with the default port setting. The pgsql parameter +can thus take the following form: +

    {pgsql, "Server", Port, "Database", "Username", "Password"}

    The Port value should be an integer, without quotes. For example: +

    {odbc_server, {pgsql, "localhost", 5432, "database", "ejabberd", "password"}}.

    By default ejabberd opens 10 connections to the database for each virtual host. +Use this option to modify the value: +

    {odbc_pool_size, 10}.
    +

    You can configure an interval to make a dummy SQL request +to keep alive the connections to the database. +The default value is ’undefined’, so no keepalive requests are made. +Specify in seconds: for example 28800 means 8 hours. +

    {odbc_keepalive_interval, undefined}.
    +

    +

    Authentication

    +

    The option value name may be misleading, as the auth_method name is used +for access to a relational database through ODBC, as well as through the native +PostgreSQL interface. Anyway, the first configuration step is to define the odbc +auth_method. For example: +

    {auth_method, [odbc]}.
    +

    +

    Storage

    +

    PostgreSQL also can be used to store information into from several ejabberd +modules. See section 3.3.1 to see which modules have a version +with the ‘_odbc’. This suffix indicates that the module can be used with +relational databases like PostgreSQL. To enable storage to your database, just +make sure that your database is running well (see previous sections), and +replace the suffix-less or ldap module variant with the odbc module variant. +Keep in mind that you cannot have several variants of the same module loaded!

    +

    3.2.4  ODBC Compatible

    +

    Although this section will describe ejabberd’s configuration when you want to +use the ODBC driver, it does not describe the installation and database creation +of your database. Check the documentation of your database. The tutorial Using ejabberd with MySQL native driver also can help you. Note that the tutorial +contains information about ejabberd’s configuration which is duplicate to +this section.

    +

    Driver Compilation

    You can skip this step if you installed ejabberd using a binary installer or +if the binary packages of ejabberd you are using include support for +ODBC.

    1. +First, install the Erlang +MySQL library. Make sure the compiled files are in your Erlang path; you can +put them for example in the same directory as your ejabberd .beam files. +
    2. Then, configure, compile and install ejabberd with ODBC support +enabled. This can be done, by using next commands: +
      ./configure --enable-odbc && make install
      +

    +

    Database Connection

    +

    The actual database access is defined in the option odbc_server. Its +value is used to defined if we want to use ODBC, or one of the two native +interface available, PostgreSQL or MySQL.

    To use a relational database through ODBC, you can pass the ODBC connection +string as odbc_server parameter. For example: +

    {odbc_server, "DSN=database;UID=ejabberd;PWD=password"}.
    +

    By default ejabberd opens 10 connections to the database for each virtual host. +Use this option to modify the value: +

    {odbc_pool_size, 10}.
    +

    You can configure an interval to make a dummy SQL request +to keep alive the connections to the database. +The default value is ’undefined’, so no keepalive requests are made. +Specify in seconds: for example 28800 means 8 hours. +

    {odbc_keepalive_interval, undefined}.
    +

    +

    Authentication

    +

    The first configuration step is to define the odbc auth_method. For +example: +

    {auth_method, [odbc]}.
    +

    +

    Storage

    +

    An ODBC compatible database also can be used to store information into from +several ejabberd modules. See section 3.3.1 to see which +modules have a version with the ‘_odbc’. This suffix indicates that the module +can be used with ODBC compatible relational databases. To enable storage to your +database, just make sure that your database is running well (see previous +sections), and replace the suffix-less or ldap module variant with the odbc +module variant. Keep in mind that you cannot have several variants of the same +module loaded!

    +

    3.2.5  LDAP

    +

    ejabberd has built-in LDAP support. You can authenticate users against LDAP +server and use LDAP directory as vCard storage. Shared rosters are not supported +yet.

    Usually ejabberd treats LDAP as a read-only storage: +it is possible to consult data, but not possible to +create accounts or edit vCard that is stored in LDAP. +However, it is possible to change passwords if mod_register module is enabled +and LDAP server supports +RFC 3062.

    +

    Connection

    Two connections are established to the LDAP server per vhost, +one for authentication and other for regular calls.

    Parameters: +

    +{ldap_servers, [Servers, ...]}
    List of IP addresses or DNS names of your +LDAP servers. This option is required. +
    {ldap_encrypt, none|tls}
    Type of connection encryption to the LDAP server. +Allowed values are: none, tls. +The value tls enables encryption by using LDAP over SSL. +Note that STARTTLS encryption is not supported. +The default value is: none. +
    {ldap_tls_verify, false|soft|hard}
    +This option specifies whether to verify LDAP server certificate or not when TLS is enabled. +When hard is enabled ejabberd doesn’t proceed if a certificate is invalid. +When soft is enabled ejabberd proceeds even if check fails. +The default is false which means no checks are performed. +
    {ldap_port, Number}
    Port to connect to your LDAP server. +The default port is 389 if encryption is disabled; and 636 if encryption is enabled. +If you configure a value, it is stored in ejabberd’s database. +Then, if you remove that value from the configuration file, +the value previously stored in the database will be used instead of the default port. +
    {ldap_rootdn, RootDN}
    Bind DN. The default value +is "" which means ‘anonymous connection’. +
    {ldap_password, Password}
    Bind password. The default +value is "". +

    Example: +

    {auth_method, ldap}.
    +{ldap_servers, ["ldap.example.org"]}.
    +{ldap_port, 389}.
    +{ldap_rootdn, "cn=Manager,dc=domain,dc=org"}.
    +{ldap_password, "secret"}.
    +

    +

    Authentication

    You can authenticate users against an LDAP directory. +Note that current LDAP implementation does not support SASL authentication.

    Available options are:

    +{ldap_base, Base}
    LDAP base directory which stores +users accounts. This option is required. +
    {ldap_uids, [ {ldap_uidattr} | {ldap_uidattr, ldap_uidattr_format}, ...]}
    +LDAP attribute which holds a list of attributes to use as alternatives for getting the JID. +The default attributes are [{"uid", "%u"}]. +The attributes are of the form: +[{ldap_uidattr}] or [{ldap_uidattr, ldap_uidattr_format}]. +You can use as many comma separated attributes as needed. +The values for ldap_uidattr and +ldap_uidattr_format are described as follow: +
    +ldap_uidattr
    LDAP attribute which holds +the user’s part of a JID. The default value is "uid". +
    ldap_uidattr_format
    Format of +the ldap_uidattr variable. The format must contain one and +only one pattern variable "%u" which will be replaced by the +user’s part of a JID. For example, "%u@example.org". The default +value is "%u". +
    +
    {ldap_filter, Filter}
    +RFC 4515 LDAP filter. The +default Filter value is: undefined. Example: +"(&(objectClass=shadowAccount)(memberOf=Jabber Users))". Please, do +not forget to close brackets and do not use superfluous whitespaces. Also you +must not use ldap_uidattr attribute in filter because this +attribute will be substituted in LDAP filter automatically. +
    {ldap_dn_filter, { Filter, FilterAttrs }}
    +This filter is applied on the results returned by the main filter. This filter +performs additional LDAP lookup to make the complete result. This is useful +when you are unable to define all filter rules in ldap_filter. You +can define "%u", "%d", "%s" and "%D" pattern +variables in Filter: "%u" is replaced by a user’s part of a JID, +"%d" is replaced by the corresponding domain (virtual host), +all "%s" variables are consecutively replaced by values of FilterAttrs +attributes and "%D" is replaced by Distinguished Name. By default +ldap_dn_filter is undefined. +Example: +
    {ldap_dn_filter, {"(&(name=%s)(owner=%D)(user=%u@%d))", ["sn"]}}.
    +
    Since this filter makes additional LDAP lookups, use it only in the +last resort: try to define all filter rules in ldap_filter if possible. +
    {ldap_local_filter, Filter}
    +If you can’t use ldap_filter due to performance reasons +(the LDAP server has many users registered), +you can use this local filter. +The local filter checks an attribute in ejabberd, +not in LDAP, so this limits the load on the LDAP directory. +The default filter is: undefined. +Example values: +
    {ldap_local_filter, {notequal, {"accountStatus",["disabled"]}}}.
    +{ldap_local_filter, {equal, {"accountStatus",["enabled"]}}}.
    +{ldap_local_filter, undefined}.
    +

    +

    Examples

    +
    Common example

    Let’s say ldap.example.org is the name of our LDAP server. We have +users with their passwords in "ou=Users,dc=example,dc=org" directory. +Also we have addressbook, which contains users emails and their additional +infos in "ou=AddressBook,dc=example,dc=org" directory. +The connection to the LDAP server is encrypted using TLS, +and using the custom port 6123. +Corresponding authentication section should looks like this:

    %% Authentication method
    +{auth_method, ldap}.
    +%% DNS name of our LDAP server
    +{ldap_servers, ["ldap.example.org"]}.
    +%% Bind to LDAP server as "cn=Manager,dc=example,dc=org" with password "secret"
    +{ldap_rootdn, "cn=Manager,dc=example,dc=org"}.
    +{ldap_password, "secret"}.
    +{ldap_encrypt, tls}.
    +{ldap_port, 6123}.
    +%% Define the user's base
    +{ldap_base, "ou=Users,dc=example,dc=org"}.
    +%% We want to authorize users from 'shadowAccount' object class only
    +{ldap_filter, "(objectClass=shadowAccount)"}.
    +

    Now we want to use users LDAP-info as their vCards. We have four attributes +defined in our LDAP schema: "mail" — email address, "givenName" +— first name, "sn" — second name, "birthDay" — birthday. +Also we want users to search each other. Let’s see how we can set it up:

    {modules,
    + [
    +  ...
    +  {mod_vcard_ldap,
    +   [
    +    %% We use the same server and port, but want to bind anonymously because
    +    %% our LDAP server accepts anonymous requests to
    +    %% "ou=AddressBook,dc=example,dc=org" subtree.
    +    {ldap_rootdn, ""},
    +    {ldap_password, ""},
    +    %% define the addressbook's base
    +    {ldap_base, "ou=AddressBook,dc=example,dc=org"},
    +    %% uidattr: user's part of JID is located in the "mail" attribute
    +    %% uidattr_format: common format for our emails
    +    {ldap_uids, [{"mail", "%u@mail.example.org"}]},
    +    %% We have to define empty filter here, because entries in addressbook does not
    +    %% belong to shadowAccount object class
    +    {ldap_filter, ""},
    +    %% Now we want to define vCard pattern
    +    {ldap_vcard_map,
    +     [{"NICKNAME", "%u", []}, % just use user's part of JID as his nickname
    +      {"GIVEN", "%s", ["givenName"]},
    +      {"FAMILY", "%s", ["sn"]},
    +      {"FN", "%s, %s", ["sn", "givenName"]}, % example: "Smith, John"
    +      {"EMAIL", "%s", ["mail"]},
    +      {"BDAY", "%s", ["birthDay"]}]},
    +    %% Search form
    +    {ldap_search_fields,
    +     [{"User", "%u"},
    +      {"Name", "givenName"},
    +      {"Family Name", "sn"},
    +      {"Email", "mail"},
    +      {"Birthday", "birthDay"}]},
    +    %% vCard fields to be reported
    +    %% Note that JID is always returned with search results
    +    {ldap_search_reported,
    +     [{"Full Name", "FN"},
    +      {"Nickname", "NICKNAME"},
    +      {"Birthday", "BDAY"}]}
    +  ]},
    +  ...
    + ]}.
    +

    Note that mod_vcard_ldap module checks for the existence of the user before +searching in his information in LDAP.

    +
    Active Directory

    +

    Active Directory is just an LDAP-server with predefined attributes. A sample +configuration is shown below:

    {auth_method, ldap}.
    +{ldap_servers, ["office.org"]}.    % List of LDAP servers
    +{ldap_base, "DC=office,DC=org"}. % Search base of LDAP directory
    +{ldap_rootdn, "CN=Administrator,CN=Users,DC=office,DC=org"}. % LDAP manager
    +{ldap_password, "*******"}. % Password to LDAP manager
    +{ldap_uids, [{"sAMAccountName"}]}.
    +{ldap_filter, "(memberOf=*)"}.
    +
    +{modules,
    + [
    +  ...
    +  {mod_vcard_ldap,
    +   [{ldap_vcard_map,
    +     [{"NICKNAME", "%u", []},
    +      {"GIVEN", "%s", ["givenName"]},
    +      {"MIDDLE", "%s", ["initials"]},
    +      {"FAMILY", "%s", ["sn"]},
    +      {"FN", "%s", ["displayName"]},
    +      {"EMAIL", "%s", ["mail"]},
    +      {"ORGNAME", "%s", ["company"]},
    +      {"ORGUNIT", "%s", ["department"]},
    +      {"CTRY", "%s", ["c"]},
    +      {"LOCALITY", "%s", ["l"]},
    +      {"STREET", "%s", ["streetAddress"]},
    +      {"REGION", "%s", ["st"]},
    +      {"PCODE", "%s", ["postalCode"]},
    +      {"TITLE", "%s", ["title"]},
    +      {"URL", "%s", ["wWWHomePage"]},
    +      {"DESC", "%s", ["description"]},
    +      {"TEL", "%s", ["telephoneNumber"]}]},
    +    {ldap_search_fields,
    +     [{"User", "%u"},
    +      {"Name", "givenName"},
    +      {"Family Name", "sn"},
    +      {"Email", "mail"},
    +      {"Company", "company"},
    +      {"Department", "department"},
    +      {"Role", "title"},
    +      {"Description", "description"},
    +      {"Phone", "telephoneNumber"}]},
    +    {ldap_search_reported,
    +     [{"Full Name", "FN"},
    +      {"Nickname", "NICKNAME"},
    +      {"Email", "EMAIL"}]}
    +  ]},
    +  ...
    + ]}.
    +

    +

    3.3  Modules Configuration

    +

    The option modules defines the list of modules that will be loaded after +ejabberd’s startup. Each entry in the list is a tuple in which the first +element is the name of a module and the second is a list of options for that +module.

    The syntax is: +

    {modules, [ {ModuleName, ModuleOptions}, ...]}.

    Examples: +

    • +In this example only the module mod_echo is loaded and no module +options are specified between the square brackets: +
      {modules,
      + [
      +  {mod_echo,      []}
      + ]}.
      +
    • In the second example the modules mod_echo, mod_time, and +mod_version are loaded without options. Remark that, besides the last entry, +all entries end with a comma: +
      {modules,
      + [
      +  {mod_echo,      []},
      +  {mod_time,      []},
      +  {mod_version,   []}
      + ]}.
      +

    +

    3.3.1  Modules Overview

    +

    The following table lists all modules included in ejabberd.


    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    ModuleFeatureDependencies
    mod_adhocAd-Hoc Commands (XEP-0050) 
    mod_announceManage announcementsrecommends mod_adhoc
    mod_capsEntity Capabilities (XEP-0115) 
    mod_configureServer configuration using Ad-Hocmod_adhoc
    mod_discoService Discovery (XEP-0030) 
    mod_echoEchoes XMPP stanzas 
    mod_http_bindXMPP over Bosh service (HTTP Binding) 
    mod_http_fileserverSmall HTTP file server 
    mod_ircIRC transport 
    mod_lastLast Activity (XEP-0012) 
    mod_last_odbcLast Activity (XEP-0012)supported DB (*)
    mod_mucMulti-User Chat (XEP-0045) 
    mod_muc_logMulti-User Chat room loggingmod_muc
    mod_offlineOffline message storage (XEP-0160) 
    mod_offline_odbcOffline message storage (XEP-0160)supported DB (*)
    mod_pingXMPP Ping and periodic keepalives (XEP-0199) 
    mod_privacyBlocking Communication (XMPP IM) 
    mod_privacy_odbcBlocking Communication (XMPP IM)supported DB (*)
    mod_privatePrivate XML Storage (XEP-0049) 
    mod_private_odbcPrivate XML Storage (XEP-0049)supported DB (*)
    mod_proxy65SOCKS5 Bytestreams (XEP-0065) 
    mod_pubsubPub-Sub (XEP-0060), PEP (XEP-0163)mod_caps
    mod_pubsub_odbcPub-Sub (XEP-0060), PEP (XEP-0163)supported DB (*) and mod_caps
    mod_registerIn-Band Registration (XEP-0077) 
    mod_rosterRoster management (XMPP IM) 
    mod_roster_odbcRoster management (XMPP IM)supported DB (*)
    mod_service_logCopy user messages to logger service 
    mod_shared_rosterShared roster managementmod_roster or
      mod_roster_odbc
    mod_sicServer IP Check (XEP-0279) 
    mod_statsStatistics Gathering (XEP-0039) 
    mod_timeEntity Time (XEP-0202) 
    mod_vcardvcard-temp (XEP-0054) 
    mod_vcard_ldapvcard-temp (XEP-0054)LDAP server
    mod_vcard_odbcvcard-temp (XEP-0054)supported DB (*)
    mod_vcard_xupdatevCard-Based Avatars (XEP-0153)mod_vcard or mod_vcard_odbc
    mod_versionSoftware Version (XEP-0092) 
    +

    • +(*) This module requires a supported database. For a list of supported databases, see section 3.2. +

    You can see which database backend each module needs by looking at the suffix: +

    • +No suffix, this means that the modules uses Erlang’s built-in database +Mnesia as backend. +
    • ‘_odbc’, this means that the module needs a supported database +(see 3.2) as backend. +
    • ‘_ldap’, this means that the module needs an LDAP server as backend. +

    If you want to, +it is possible to use a relational database to store the tables created by some ejabberd modules. +You can do this by changing the module name to a name with an +_odbc suffix in ejabberd config file. You can use a relational +database for the following data:

    • +Last connection date and time: Use mod_last_odbc instead of +mod_last. +
    • Offline messages: Use mod_offline_odbc instead of +mod_offline. +
    • Rosters: Use mod_roster_odbc instead of mod_roster. +
    • Users’ VCARD: Use mod_vcard_odbc instead of mod_vcard. +
    • Private XML storage: Use mod_private_odbc instead of mod_private. +
    • User rules for blocking communications: Use mod_privacy_odbc instead of mod_privacy. +
    • Pub-Sub nodes, items and subscriptions: Use mod_pubsub_odbc instead of mod_pubsub. +

    You can find more +contributed modules on the +ejabberd website. Please remember that these contributions might not work or +that they can contain severe bugs and security leaks. Therefore, use them at +your own risk!

    +

    3.3.2  Common Options

    The following options are used by many modules. Therefore, they are described in +this separate section.

    +

    iqdisc

    +

    Many modules define handlers for processing IQ queries of different namespaces +to this server or to a user (e. g. to example.org or to +user@example.org). This option defines processing discipline for +these queries.

    The syntax is: +

    {iqdisc, Value}

    Possible Value are: +

    +no_queue
    All queries of a namespace with this processing discipline are +processed immediately. This also means that no other packets can be processed +until this one has been completely processed. Hence this discipline is not +recommended if the processing of a query can take a relatively long time. +
    one_queue
    In this case a separate queue is created for the processing +of IQ queries of a namespace with this discipline. In addition, the processing +of this queue is done in parallel with that of other packets. This discipline +is most recommended. +
    {queues, N}
    N separate queues are created to process the +queries. The queries are thus process in parallel, but in a +controlled way. +
    parallel
    For every packet with this discipline a separate Erlang process +is spawned. Consequently, all these packets are processed in parallel. +Although spawning of Erlang process has a relatively low cost, this can break +the server’s normal work, because the Erlang emulator has a limit on the +number of processes (32000 by default). +

    Example: +

    {modules,
    + [
    +  ...
    +  {mod_time, [{iqdisc, no_queue}]},
    +  ...
    + ]}.
    +

    +

    host

    +

    This option defines the Jabber ID of a service provided by an ejabberd module.

    The syntax is: +

    {host, HostName}

    If you include the keyword "@HOST@" in the HostName, +it is replaced at start time with the real virtual host string.

    This example configures +the echo module to provide its echoing service +in the Jabber ID mirror.example.org: +

    {modules,
    + [
    +  ...
    +  {mod_echo, [{host, "mirror.example.org"}]},
    +  ...
    + ]}.
    +

    However, if there are several virtual hosts and this module is enabled in all of them, +the "@HOST@" keyword must be used: +

    {modules,
    + [
    +  ...
    +  {mod_echo, [{host, "mirror.@HOST@"}]},
    +  ...
    + ]}.
    +

    +

    3.3.3  mod_announce

    +

    This module enables configured users to broadcast announcements and to set +the message of the day (MOTD). +Configured users can perform these actions with a +XMPP client either using Ad-hoc commands +or sending messages to specific JIDs.

    The Ad-hoc commands are listed in the Server Discovery. +For this feature to work, mod_adhoc must be enabled.

    The specific JIDs where messages can be sent are listed bellow. +The first JID in each entry will apply only to the specified virtual host +example.org, while the JID between brackets will apply to all virtual +hosts in ejabberd. +

    +example.org/announce/all (example.org/announce/all-hosts/all)
    The +message is sent to all registered users. If the user is online and connected +to several resources, only the resource with the highest priority will receive +the message. If the registered user is not connected, the message will be +stored offline in assumption that offline storage +(see section 3.3.12) is enabled. +
    example.org/announce/online (example.org/announce/all-hosts/online)
    The +message is sent to all connected users. If the user is online and connected +to several resources, all resources will receive the message. +
    example.org/announce/motd (example.org/announce/all-hosts/motd)
    The +message is set as the message of the day (MOTD) and is sent to users when they +login. In addition the message is sent to all connected users (similar to +announce/online). +
    example.org/announce/motd/update (example.org/announce/all-hosts/motd/update)
    +The message is set as message of the day (MOTD) and is sent to users when they +login. The message is not sent to any currently connected user. +
    example.org/announce/motd/delete (example.org/announce/all-hosts/motd/delete)
    +Any message sent to this JID removes the existing message of the day (MOTD). +

    Options: +

    +{access, AccessName}
    This option specifies who is allowed to +send announcements and to set the message of the day (by default, nobody is +able to send such messages). +

    Examples: +

    • +Only administrators can send announcements: +
      {access, announce, [{allow, admins}]}.
      +
      +{modules,
      + [
      +  ...
      +  {mod_adhoc, []},
      +  {mod_announce, [{access, announce}]},
      +  ...
      + ]}.
      +
    • Administrators as well as the direction can send announcements: +
      {acl, direction, {user, "big_boss", "example.org"}}.
      +{acl, direction, {user, "assistant", "example.org"}}.
      +{acl, admins, {user, "admin", "example.org"}}.
      +
      +{access, announce, [{allow, admins},
      +                    {allow, direction}]}.
      +
      +{modules,
      + [
      +  ...
      +  {mod_adhoc, []},
      +  {mod_announce, [{access, announce}]},
      +  ...
      + ]}.
      +

    Note that mod_announce can be resource intensive on large +deployments as it can broadcast lot of messages. This module should be +disabled for instances of ejabberd with hundreds of thousands users.

    +

    3.3.4  mod_disco

    + + + + +

    This module adds support for Service Discovery (XEP-0030). With +this module enabled, services on your server can be discovered by +XMPP clients. Note that ejabberd has no modules with support +for the superseded Jabber Browsing (XEP-0011) and Agent Information +(XEP-0094). Accordingly, XMPP clients need to have support for +the newer Service Discovery protocol if you want them be able to discover +the services you offer.

    Options: +

    +{iqdisc, Discipline}
    This specifies +the processing discipline for Service Discovery (http://jabber.org/protocol/disco#items and +http://jabber.org/protocol/disco#info) IQ queries (see section 3.3.2). +
    {extra_domains, [Domain, ...]}
    With this option, +you can specify a list of extra domains that are added to the Service Discovery item list. +
    {server_info, [ {Modules, Field, [Value, ...]}, ... ]}
    +Specify additional information about the server, +as described in Contact Addresses for XMPP Services (XEP-0157). +Modules can be the keyword ‘all’, +in which case the information is reported in all the services; +or a list of ejabberd modules, +in which case the information is only specified for the services provided by those modules. +Any arbitrary Field and Value can be specified, not only contact addresses. +

    Examples: +

    • +To serve a link to the Jabber User Directory on jabber.org: +
      {modules,
      + [
      +  ...
      +  {mod_disco, [{extra_domains, ["users.jabber.org"]}]},
      +  ...
      + ]}.
      +
    • To serve a link to the transports on another server: +
      {modules,
      + [
      +  ...
      +  {mod_disco, [{extra_domains, ["icq.example.com",
      +                                "msn.example.com"]}]},
      +  ...
      + ]}.
      +
    • To serve a link to a few friendly servers: +
      {modules,
      + [
      +  ...
      +  {mod_disco, [{extra_domains, ["example.org",
      +                                "example.com"]}]},
      +  ...
      + ]}.
      +
    • With this configuration, all services show abuse addresses, +feedback address on the main server, +and admin addresses for both the main server and the vJUD service: +
      {modules,
      + [
      +  ...
      +  {mod_disco, [{server_info, [
      +      {all,
      +       "abuse-addresses",
      +       ["mailto:abuse@shakespeare.lit"]},
      +      {[mod_muc],
      +       "Web chatroom logs",
      +       ["http://www.example.org/muc-logs"]},
      +      {[mod_disco],
      +       "feedback-addresses",
      +       ["http://shakespeare.lit/feedback.php", "mailto:feedback@shakespeare.lit", "xmpp:feedback@shakespeare.lit"]},
      +      {[mod_disco, mod_vcard],
      +       "admin-addresses",
      +       ["mailto:xmpp@shakespeare.lit", "xmpp:admins@shakespeare.lit"]}
      +  ]}]},
      +  ...
      + ]}.
      +

    +

    3.3.5  mod_echo

    +

    This module simply echoes any XMPP +packet back to the sender. This mirror can be of interest for +ejabberd and XMPP client debugging.

    Options: +

    + +{host, HostName}
    This option defines the Jabber ID of the +service. If the host option is not specified, the Jabber ID will be the +hostname of the virtual host with the prefix ‘echo.’. The keyword "@HOST@" +is replaced at start time with the real virtual host name. + +

    Example: Mirror, mirror, on the wall, who is the most beautiful +of them all? +

    {modules,
    + [
    +  ...
    +  {mod_echo, [{host, "mirror.example.org"}]},
    +  ...
    + ]}.
    +

    +

    3.3.6  mod_http_bind

    +

    This module implements XMPP over Bosh (formerly known as HTTP Binding) +as defined in XEP-0124 and XEP-0206. +It extends ejabberd’s built in HTTP service with a configurable +resource at which this service will be hosted.

    To use HTTP-Binding, enable the module: +

    {modules,
    + [
    +  ...
    +  {mod_http_bind, []},
    +  ...
    +]}.
    +

    and add http_bind in the HTTP service. For example: +

    {listen, 
    + [
    +  ...
    +  {5280, ejabberd_http, [
    +                         http_bind,
    +                         http_poll,
    +                         web_admin
    +                        ]
    +  },
    +  ...
    +]}.
    +

    With this configuration, the module will serve the requests sent to +http://example.org:5280/http-bind/ +Remember that this page is not designed to be used by web browsers, +it is used by XMPP clients that support XMPP over Bosh.

    If you want to set the service in a different URI path or use a different module, +you can configure it manually using the option request_handlers. +For example: +

    {listen, 
    + [
    +  ...
    +  {5280, ejabberd_http, [
    +                         {request_handlers, [{["http-bind"], mod_http_bind}]},
    +                         http_poll,
    +                         web_admin
    +                        ]
    +  },
    +  ...
    +]}.
    +

    Options: +

    +{max_inactivity, Seconds}
    +Define the maximum inactivity period in seconds. +Default value is 30 seconds. +For example, to set 50 seconds: +
    {modules,
    + [
    +  ...
    +  {mod_http_bind, [ {max_inactivity, 50} ]},
    +  ...
    +]}.
    +

    +

    3.3.7  mod_http_fileserver

    +

    This simple module serves files from the local disk over HTTP.

    Options: +

    +{docroot, Path}
    +Directory to serve the files. +
    {accesslog, Path}
    +File to log accesses using an Apache-like format. +No log will be recorded if this option is not specified. +
    {directory_indices, [Index, ...]}
    +Indicate one or more directory index files, similarly to Apache’s +DirectoryIndex variable. When a web request hits a directory +instead of a regular file, those directory indices are looked in +order, and the first one found is returned. +
    {custom_headers, [ {Name, Value}, ...]}
    +Indicate custom HTTP headers to be included in all responses. +Default value is: [] +
    {content_types, [ {Name, Type}, ...]}
    +Specify mappings of extension to content type. +There are several content types already defined, +with this option you can add new definitions, modify or delete existing ones. +To delete an existing definition, simply define it with a value: ‘undefined’. +
    {default_content_type, Type}
    +Specify the content type to use for unknown extensions. +Default value is ‘application/octet-stream’. +

    This example configuration will serve the files from +the local directory /var/www +in the address http://example.org:5280/pub/archive/. +In this example a new content type ogg is defined, +png is redefined, and jpg definition is deleted. +To use this module you must enable it: +

    {modules,
    + [
    +  ...
    +  {mod_http_fileserver, [
    +                         {docroot, "/var/www"}, 
    +                         {accesslog, "/var/log/ejabberd/access.log"},
    +                         {directory_indices, ["index.html", "main.htm"]},
    +                         {custom_headers, [{"X-Powered-By", "Erlang/OTP"},
    +                                           {"X-Fry", "It's a widely-believed fact!"}
    +                                          ]},
    +                         {content_types, [{".ogg", "audio/ogg"},
    +                                          {".png", "image/png"},
    +                                          {".jpg", undefined}
    +                                         ]},
    +                         {default_content_type, "text/html"}
    +                        ]
    +  },
    +  ...
    +]}.
    +

    And define it as a handler in the HTTP service: +

    {listen, 
    + [
    +  ...
    +  {5280, ejabberd_http, [
    +                         ...
    +                         {request_handlers, [
    +                                             ...
    +                                             {["pub", "archive"], mod_http_fileserver},
    +                                             ...
    +                                            ]
    +                         },
    +                         ...
    +                        ]
    +  },
    +  ...
    +]}.
    +

    +

    3.3.8  mod_irc

    +

    This module is an IRC transport that can be used to join channels on IRC +servers.

    End user information: + +

    • +A XMPP client with ‘groupchat 1.0’ support or Multi-User +Chat support (XEP-0045) is necessary to join IRC channels. +
    • An IRC channel can be joined in nearly the same way as joining a +XMPP Multi-User Chat room. The difference is that the room name will +be ‘channel%irc.example.org’ in case irc.example.org is +the IRC server hosting ‘channel’. And of course the host should point +to the IRC transport instead of the Multi-User Chat service. +
    • You can register your nickame by sending ‘IDENTIFY password’ to
      + nickserver!irc.example.org@irc.jabberserver.org. +
    • Entering your password is possible by sending ‘LOGIN nick password’
      + to nickserver!irc.example.org@irc.jabberserver.org. +
    • The IRC transport provides Ad-Hoc Commands (XEP-0050) +to join a channel, and to set custom IRC username and encoding. +
    • When using a popular XMPP server, it can occur that no +connection can be achieved with some IRC servers because they limit the +number of conections from one IP. +

    Options: +

    + +{host, HostName}
    This option defines the Jabber ID of the +service. If the host option is not specified, the Jabber ID will be the +hostname of the virtual host with the prefix ‘irc.’. The keyword "@HOST@" +is replaced at start time with the real virtual host name. + +
    {access, AccessName}
    This option can be used to specify who +may use the IRC transport (default value: all). +
    {default_encoding, Encoding}
    Set the default IRC encoding. +Default value: "koi8-r" +

    Examples: +

    • +In the first example, the IRC transport is available on (all) your +virtual host(s) with the prefix ‘irc.’. Furthermore, anyone is +able to use the transport. The default encoding is set to "iso8859-15". +
      {modules,
      + [
      +  ...
      +  {mod_irc, [{access, all}, {default_encoding, "iso8859-15"}]},
      +  ...
      + ]}.
      +
    • In next example the IRC transport is available with JIDs with prefix irc-t.net. +Moreover, the transport is only accessible to two users +of example.org, and any user of example.com: +
      {acl, paying_customers, {user, "customer1", "example.org"}}.
      +{acl, paying_customers, {user, "customer2", "example.org"}}.
      +{acl, paying_customers, {server, "example.com"}}.
      +
      +{access, irc_users, [{allow, paying_customers}, {deny, all}]}.
      +
      +{modules,
      + [
      +  ...
      +  {mod_irc, [{access, irc_users},
      +             {host, "irc.example.net"}]},
      +  ...
      + ]}.
      +

    +

    3.3.9  mod_last

    +

    This module adds support for Last Activity (XEP-0012). It can be used to +discover when a disconnected user last accessed the server, to know when a +connected user was last active on the server, or to query the uptime of the +ejabberd server.

    Options: +

    +{iqdisc, Discipline}
    This specifies +the processing discipline for Last activity (jabber:iq:last) IQ queries (see section 3.3.2). +

    +

    3.3.10  mod_muc

    +

    This module provides a Multi-User Chat (XEP-0045) service. +Users can discover existing rooms, join or create them. +Occupants of a room can chat in public or have private chats.

    Some of the features of Multi-User Chat: +

    • +Sending public and private messages to room occupants. +
    • Inviting other users to a room. +
    • Setting a room subject. +
    • Creating password protected rooms. +
    • Kicking and banning occupants. +

    The MUC service allows any Jabber ID to register a nickname, +so nobody else can use that nickname in any room in the MUC service. +To register a nickname, open the Service Discovery in your +XMPP client and register in the MUC service.

    This module supports clustering and load +balancing. One module can be started per cluster node. Rooms are +distributed at creation time on all available MUC module +instances. The multi-user chat module is clustered but the rooms +themselves are not clustered nor fault-tolerant: if the node managing a +set of rooms goes down, the rooms disappear and they will be recreated +on an available node on first connection attempt.

    Module options: +

    + +{host, HostName}
    This option defines the Jabber ID of the +service. If the host option is not specified, the Jabber ID will be the +hostname of the virtual host with the prefix ‘conference.’. The keyword "@HOST@" +is replaced at start time with the real virtual host name. + +
    {access, AccessName}
    You can specify who is allowed to use +the Multi-User Chat service. By default everyone is allowed to use it. +
    {access_create, AccessName}
    To configure who is +allowed to create new rooms at the Multi-User Chat service, this option can be used. +By default any account in the local ejabberd server is allowed to create rooms. +
    {access_persistent, AccessName}
    To configure who is +allowed to modify the ’persistent’ room option. +By default any account in the local ejabberd server is allowed to modify that option. +
    {access_admin, AccessName}
    This option specifies +who is allowed to administrate the Multi-User Chat service. The default +value is none, which means that only the room creator can +administer his room. +The administrators can send a normal message to the service JID, +and it will be shown in all active rooms as a service message. +The administrators can send a groupchat message to the JID of an active room, +and the message will be shown in the room as a service message. +
    {history_size, Size}
    A small history of +the current discussion is sent to users when they enter the +room. With this option you can define the number of history messages +to keep and send to users joining the room. The value is an +integer. Setting the value to 0 disables the history feature +and, as a result, nothing is kept in memory. The default value is +20. This value is global and thus affects all rooms on the +service. +
    {max_users, Number}
    This option defines at +the service level, the maximum number of users allowed per +room. It can be lowered in each room configuration but cannot be +increased in individual room configuration. The default value is +200. +
    {max_users_admin_threshold, Number}
    + This option defines the +number of service admins or room owners allowed to enter the room when +the maximum number of allowed occupants was reached. The default limit +is 5. +
    {max_user_conferences, Number}
    + This option defines the maximum +number of rooms that any given user can join. The default value +is 10. This option is used to prevent possible abuses. Note that +this is a soft limit: some users can sometimes join more conferences +in cluster configurations. +
    {max_room_id, Number}
    +This option defines the maximum number of characters that Room ID +can have when creating a new room. +The default value is to not limit: infinite. +
    {max_room_name, Number}
    +This option defines the maximum number of characters that Room Name +can have when configuring the room. +The default value is to not limit: infinite. +
    {max_room_desc, Number}
    +This option defines the maximum number of characters that Room Description +can have when configuring the room. +The default value is to not limit: infinite. +
    {min_message_interval, Number}
    +This option defines the minimum interval between two messages send +by an occupant in seconds. This option is global and valid for all +rooms. A decimal value can be used. When this option is not defined, +message rate is not limited. This feature can be used to protect a +MUC service from occupant abuses and limit number of messages that will +be broadcasted by the service. A good value for this minimum message +interval is 0.4 second. If an occupant tries to send messages faster, an +error is send back explaining that the message has been discarded +and describing the reason why the message is not acceptable. +
    {min_presence_interval, Number}
    + This option defines the +minimum of time between presence changes coming from a given occupant in +seconds. This option is global and valid for all rooms. A +decimal value can be used. When this option is not defined, no +restriction is applied. This option can be used to protect a MUC +service for occupants abuses. If an occupant tries +to change its presence more often than the specified interval, the +presence is cached by ejabberd and only the last presence is +broadcasted to all occupants in the room after expiration of the +interval delay. Intermediate presence packets are silently +discarded. A good value for this option is 4 seconds. +
    {default_room_options, [ {OptionName, OptionValue}, ...]}
    +This module option allows to define the desired default room options. +Note that the creator of a room can modify the options of his room +at any time using a XMPP client with MUC capability. +The available room options and the default values are: +
    +{allow_change_subj, true|false}
    Allow occupants to change the subject. +
    {allow_private_messages, true|false}
    Occupants can send private messages to other occupants. +
    {allow_query_users, true|false}
    Occupants can send IQ queries to other occupants. +
    {allow_user_invites, false|true}
    Allow occupants to send invitations. +
    {allow_visitor_nickchange, true|false}
    Allow visitors to +change nickname. +
    {allow_visitor_status, true|false}
    Allow visitors to send +status text in presence updates. If disallowed, the status +text is stripped before broadcasting the presence update to all +the room occupants. +
    {anonymous, true|false}
    The room is anonymous: +occupants don’t see the real JIDs of other occupants. +Note that the room moderators can always see the real JIDs of the occupants. +
    {captcha_protected, false}
    +When a user tries to join a room where he has no affiliation (not owner, admin or member), +the room requires him to fill a CAPTCHA challenge (see section 3.1.8) +in order to accept her join in the room. +
    {logging, false|true}
    The public messages are logged using mod_muc_log. +
    {max_users, 200}
    Maximum number of occupants in the room. +
    {members_by_default, true|false}
    The occupants that enter the room are participants by default, so they have ’voice’. +
    {members_only, false|true}
    Only members of the room can enter. +
    {moderated, true|false}
    Only occupants with ’voice’ can send public messages. +
    {password, "roompass123"}
    Password of the room. You may want to enable the next option too. +
    {password_protected, false|true}
    The password is required to enter the room. +
    {persistent, false|true}
    The room persists even if the last participant leaves. +
    {public, true|false}
    The room is public in the list of the MUC service, so it can be discovered. +
    {public_list, true|false}
    The list of participants is public, without requiring to enter the room. +
    {title, "Room Title"}
    A human-readable title of the room. +
    +All of those room options can be set to true or false, +except password and title which are strings, +and max_users that is integer. +

    Examples: +

    • +In the first example everyone is allowed to use the Multi-User Chat +service. Everyone will also be able to create new rooms but only the user +admin@example.org is allowed to administrate any room. In this +example he is also a global administrator. When admin@example.org +sends a message such as ‘Tomorrow, the XMPP server will be moved +to new hardware. This will involve service breakdowns around 23:00 UMT. +We apologise for this inconvenience.’ to conference.example.org, +it will be displayed in all active rooms. In this example the history +feature is disabled. +
      {acl, admin, {user, "admin", "example.org"}}.
      +
      +{access, muc_admin, [{allow, admin}]}.
      +
      +{modules,
      + [
      +  ...
      +  {mod_muc, [{access, all},
      +             {access_create, all},
      +             {access_admin, muc_admin},
      +             {history_size, 0}]},
      +  ...
      + ]}.
      +
    • In the second example the Multi-User Chat service is only accessible by +paying customers registered on our domains and on other servers. Of course +the administrator is also allowed to access rooms. In addition, he is the +only authority able to create and administer rooms. When +admin@example.org sends a message such as ‘Tomorrow, the Jabber +server will be moved to new hardware. This will involve service breakdowns +around 23:00 UMT. We apologise for this inconvenience.’ to +conference.example.org, it will be displayed in all active rooms. No +history_size option is used, this means that the feature is enabled +and the default value of 20 history messages will be send to the users. +
      {acl, paying_customers, {user, "customer1", "example.net"}}.
      +{acl, paying_customers, {user, "customer2", "example.com"}}.
      +{acl, paying_customers, {user, "customer3", "example.org"}}.
      +{acl, admin, {user, "admin", "example.org"}}.
      +
      +{access, muc_admin, [{allow, admin},
      +                      {deny, all}]}.
      +{access, muc_access, [{allow, paying_customers},
      +                      {allow, admin},
      +                      {deny, all}]}.
      +
      +{modules,
      + [
      +  ...
      +  {mod_muc, [{access, muc_access},
      +             {access_create, muc_admin},
      +             {access_admin, muc_admin}]},
      +  ...
      + ]}.
      +
    • In the following example, MUC anti abuse options are used. An +occupant cannot send more than one message every 0.4 seconds and cannot +change its presence more than once every 4 seconds. +The length of Room IDs and Room Names are limited to 20 characters, +and Room Description to 300 characters. No ACLs are +defined, but some user restriction could be added as well:
      {modules,
      + [
      +  ...
      +  {mod_muc, [{min_message_interval, 0.4},
      +             {min_presence_interval, 4},
      +             {max_room_id, 20},
      +             {max_room_name, 20},
      +             {max_room_desc, 300}]},
      +  ...
      + ]}.
      +
    • This example shows how to use default_room_options to make sure +the newly created rooms have by default those options. +
      {modules,
      + [
      +  ...
      +  {mod_muc, [{access, muc_access},
      +             {access_create, muc_admin},
      +             {default_room_options,
      +              [
      +               {allow_change_subj, false},
      +               {allow_query_users, true},
      +               {allow_private_messages, true},
      +               {members_by_default, false},
      +               {title, "New chatroom"},
      +               {anonymous, false}
      +              ]},
      +             {access_admin, muc_admin}]},
      +  ...
      + ]}.
      +

    +

    3.3.11  mod_muc_log

    +

    This module enables optional logging of Multi-User Chat (MUC) public conversations to +HTML. Once you enable this module, users can join a room using a MUC capable +XMPP client, and if they have enough privileges, they can request the +configuration form in which they can set the option to enable room logging.

    Features: +

    • +Room details are added on top of each page: room title, JID, +author, subject and configuration. +
    • +The room JID in the generated HTML is a link to join the room (using +XMPP URI). +
    • Subject and room configuration changes are tracked and displayed. +
    • Joins, leaves, nick changes, kicks, bans and ‘/me’ are tracked and +displayed, including the reason if available. +
    • Generated HTML files are XHTML 1.0 Transitional and CSS compliant. +
    • Timestamps are self-referencing links. +
    • Links on top for quicker navigation: Previous day, Next day, Up. +
    • CSS is used for style definition, and a custom CSS file can be used. +
    • URLs on messages and subjects are converted to hyperlinks. +
    • Timezone used on timestamps is shown on the log files. +
    • A custom link can be added on top of each page. +

    Options: +

    +{access_log, AccessName}
    +This option restricts which occupants are allowed to enable or disable room +logging. The default value is muc_admin. Note for this default setting +you need to have an access rule for muc_admin in order to take effect. +
    {cssfile, false|URL}
    +With this option you can set whether the HTML files should have a custom CSS +file or if they need to use the embedded CSS file. Allowed values are +false and an URL to a CSS file. With the first value, HTML files will +include the embedded CSS code. With the latter, you can specify the URL of the +custom CSS file (for example: "http://example.com/my.css"). The default value +is false. +
    {dirname, room_jid|room_name}
    +Allows to configure the name of the room directory. +Allowed values are room_jid and room_name. +With the first value, the room directory name will be the full room JID. +With the latter, the room directory name will be only the room name, +not including the MUC service name. +The default value is room_jid. +
    {dirtype, subdirs|plain}
    +The type of the created directories can be specified with this option. Allowed +values are subdirs and plain. With the first value, +subdirectories are created for each year and month. With the latter, the +names of the log files contain the full date, and there are no subdirectories. +The default value is subdirs. +
    {file_format, html|plaintext}
    +Define the format of the log files: +html stores in HTML format, +plaintext stores in plain text. +The default value is html. +
    {outdir, Path}
    +This option sets the full path to the directory in which the HTML files should +be stored. Make sure the ejabberd daemon user has write access on that +directory. The default value is "www/muc". +
    {spam_prevention true|false}
    +To prevent spam, the spam_prevention option adds a special attribute +to links that prevent their indexation by search engines. The default value +is true, which mean that nofollow attributes will be added to user +submitted links. +
    {timezone, local|universal}
    +The time zone for the logs is configurable with this option. Allowed values +are local and universal. With the first value, the local time, +as reported to Erlang by the operating system, will be used. With the latter, +GMT/UTC time will be used. The default value is local. +
    {top_link, {URL, Text}}
    +With this option you can customize the link on the top right corner of each +log file. The default value is {"/", "Home"}. +

    Examples: +

    • +In the first example any room owner can enable logging, and a +custom CSS file will be used (http://example.com/my.css). The names +of the log files will contain the full date, and there will be no +subdirectories. The log files will be stored in /var/www/muclogs, and the +time zone will be GMT/UTC. Finally, the top link will be +<a href="http://www.jabber.ru/">Jabber.ru</a>. +
      {access, muc, [{allow, all}]}.
      +
      +{modules,
      + [
      +  ...
      +  {mod_muc_log, [
      +                 {access_log, muc},
      +                 {cssfile, "http://example.com/my.css"},
      +                 {dirtype, plain},
      +                 {dirname, room_jid},
      +                 {outdir, "/var/www/muclogs"},
      +                 {timezone, universal},
      +                 {spam_prevention, true},
      +                 {top_link, {"http://www.jabber.ru/", "Jabber.ru"}}
      +                ]},
      +  ...
      + ]}.
      +
    • In the second example only admin1@example.org and +admin2@example.net can enable logging, and the embedded CSS file will be +used. The names of the log files will only contain the day (number), +and there will be subdirectories for each year and month. The log files will +be stored in /var/www/muclogs, and the local time will be used. Finally, the +top link will be the default <a href="/">Home</a>. +
      {acl, admins, {user, "admin1", "example.org"}}.
      +{acl, admins, {user, "admin2", "example.net"}}.
      +
      +{access, muc_log, [{allow, admins},
      +                   {deny, all}]}.
      +
      +{modules,
      + [
      +  ...
      +  {mod_muc_log, [
      +                 {access_log, muc_log},
      +                 {cssfile, false},
      +                 {dirtype, subdirs},
      +                 {outdir, "/var/www/muclogs"},
      +                 {timezone, local}
      +                ]},
      +  ...
      + ]}.
      +

    +

    3.3.12  mod_offline

    +

    This module implements offline message storage (XEP-0160). +This means that all messages +sent to an offline user will be stored on the server until that user comes +online again. Thus it is very similar to how email works. Note that +ejabberdctl has a command to delete expired messages +(see section 4.1).

    +{access_max_user_messages, AccessName}
    +This option defines which access rule will be enforced to limit +the maximum number of offline messages that a user can have (quota). +When a user has too many offline messages, any new messages that he receive are discarded, +and a resource-constraint error is returned to the sender. +The default value is max_user_offline_messages. +Then you can define an access rule with a syntax similar to +max_user_sessions (see 3.1.5). +

    This example allows power users to have as much as 5000 offline messages, +administrators up to 2000, +and all the other users up to 100. +

    {acl, admin, {user, "admin1", "localhost"}}.
    +{acl, admin, {user, "admin2", "example.org"}}.
    +{acl, poweruser, {user, "bob", "example.org"}}.
    +{acl, poweruser, {user, "jane", "example.org"}}.
    +
    +{access, max_user_offline_messages, [ {5000, poweruser}, {2000, admin}, {100, all} ]}.
    +
    +{modules,
    + [
    +  ...
    +  {mod_offline,  [ {access_max_user_messages, max_user_offline_messages} ]},
    +  ...
    + ]}.
    +

    +

    3.3.13  mod_ping

    +

    This module implements support for XMPP Ping (XEP-0199) and periodic keepalives. +When this module is enabled ejabberd responds correctly to +ping requests, as defined in the protocol.

    Configuration options: +

    +{send_pings, true|false}
    +If this option is set to true, the server sends pings to connected clients +that are not active in a given interval ping_interval. +This is useful to keep client connections alive or checking availability. +By default this option is disabled. +
    {ping_interval, Seconds}
    +How often to send pings to connected clients, if the previous option is enabled. +If a client connection does not send or receive any stanza in this interval, +a ping request is sent to the client. +The default value is 60 seconds. +
    {timeout_action, none|kill}
    +What to do when a client does not answer to a server ping request in less than 32 seconds. +The default is to do nothing. +

    This example enables Ping responses, configures the module to send pings +to client connections that are inactive for 4 minutes, +and if a client does not answer to the ping in less than 32 seconds, its connection is closed: +

    {modules,
    + [
    +  ...
    +  {mod_ping,  [{send_pings, true}, {ping_interval, 240}, {timeout_action, kill}]},
    +  ...
    + ]}.
    +

    +

    3.3.14  mod_privacy

    +

    This module implements Blocking Communication (also known as Privacy Rules) +as defined in section 10 from XMPP IM. If end users have support for it in +their XMPP client, they will be able to: +

    +
    • +Retrieving one’s privacy lists. +
    • Adding, removing, and editing one’s privacy lists. +
    • Setting, changing, or declining active lists. +
    • Setting, changing, or declining the default list (i.e., the list that +is active by default). +
    • Allowing or blocking messages based on JID, group, or subscription type +(or globally). +
    • Allowing or blocking inbound presence notifications based on JID, group, +or subscription type (or globally). +
    • Allowing or blocking outbound presence notifications based on JID, group, +or subscription type (or globally). +
    • Allowing or blocking IQ stanzas based on JID, group, or subscription type +(or globally). +
    • Allowing or blocking all communications based on JID, group, or +subscription type (or globally). +
    +(from http://xmpp.org/rfcs/rfc3921.html#privacy) +

    Options: +

    +{iqdisc, Discipline}
    This specifies +the processing discipline for Blocking Communication (jabber:iq:privacy) IQ queries (see section 3.3.2). +

    +

    3.3.15  mod_private

    +

    This module adds support for Private XML Storage (XEP-0049): +

    +Using this method, XMPP entities can store private data on the server and +retrieve it whenever necessary. The data stored might be anything, as long as +it is valid XML. One typical usage for this namespace is the server-side storage +of client-specific preferences; another is Bookmark Storage (XEP-0048). +

    Options: +

    +{iqdisc, Discipline}
    This specifies +the processing discipline for Private XML Storage (jabber:iq:private) IQ queries (see section 3.3.2). +

    +

    3.3.16  mod_proxy65

    +

    This module implements SOCKS5 Bytestreams (XEP-0065). +It allows ejabberd to act as a file transfer proxy between two +XMPP clients.

    Options: +

    + +{host, HostName}
    This option defines the Jabber ID of the +service. If the host option is not specified, the Jabber ID will be the +hostname of the virtual host with the prefix ‘proxy.’. The keyword "@HOST@" +is replaced at start time with the real virtual host name. + +
    {name, Text}
    Defines Service Discovery name of the service. +Default is "SOCKS5 Bytestreams". +
    {ip, IPTuple}
    This option specifies which network interface +to listen for. Default is an IP address of the service’s DNS name, or, +if fails, {127,0,0,1}. +
    {port, Number}
    This option defines port to listen for +incoming connections. Default is 7777. +
    {hostname, HostName}
    Defines a hostname advertised +by the service when establishing a session with clients. This is useful when +you run the service behind a NAT. The default is the value of ip option. +Examples: "proxy.mydomain.org", "200.150.100.50". Note that +not all clients understand domain names in stream negotiation, +so you should think twice before setting domain name in this option. +
    {auth_type, anonymous|plain}
    SOCKS5 authentication type. +Possible values are anonymous and plain. Default is +anonymous. +
    {access, AccessName}
    Defines ACL for file transfer initiators. +Default is all. +
    {max_connections, Number}
    Maximum number of +active connections per file transfer initiator. No limit by default. +
    {shaper, none|ShaperName}
    This option defines shaper for +the file transfer peers. Shaper with the maximum bandwidth will be selected. +Default is none. +

    Examples: +

    • +The simpliest configuration of the module: +
      {modules,
      + [
      +  ...
      +  {mod_proxy65, []},
      +  ...
      + ]}.
      +
    • More complicated configuration. +
      {acl, proxy_users, {server, "example.org"}}.
      +{access, proxy65_access, [{allow, proxy_users}, {deny, all}]}.
      +
      +{acl, admin, {user, "admin", "example.org"}}.
      +{shaper, proxyrate, {maxrate, 10240}}. %% 10 Kbytes/sec
      +{access, proxy65_shaper, [{none, admin}, {proxyrate, proxy_users}]}.
      +
      +{modules,
      + [
      +  ...
      +  {mod_proxy65, [{host, "proxy1.example.org"},
      +                 {name, "File Transfer Proxy"},
      +                 {ip, {200,150,100,1}},
      +                 {port, 7778},
      +                 {max_connections, 5},
      +                 {access, proxy65_access},
      +                 {shaper, proxy65_shaper}]},
      +  ...
      + ]}.
      +

    +

    3.3.17  mod_pubsub

    +

    This module offers a Publish-Subscribe Service (XEP-0060). +The functionality in mod_pubsub can be extended using plugins. +The plugin that implements PEP (Personal Eventing via Pubsub) (XEP-0163) +is enabled in the default ejabberd configuration file, +and it requires mod_caps.

    Options: +

    + +{host, HostName}
    This option defines the Jabber ID of the +service. If the host option is not specified, the Jabber ID will be the +hostname of the virtual host with the prefix ‘pubsub.’. The keyword "@HOST@" +is replaced at start time with the real virtual host name. + +If you use mod_pubsub_odbc, please ensure the prefix contains only one dot, +for example ‘pubsub.’, or ‘publish.’,. +
    {access_createnode, AccessName}
    +This option restricts which users are allowed to create pubsub nodes using +ACL and ACCESS. +By default any account in the local ejabberd server is allowed to create pubsub nodes. +
    {max_items_node, MaxItems}
    +Define the maximum number of items that can be stored in a node. +Default value is 10. +
    {plugins, [ Plugin, ...]}
    +To specify which pubsub node plugins to use. +The first one in the list is used by default. +If this option is not defined, the default plugins list is: ["flat"]. +PubSub clients can define which plugin to use when creating a node: +add type=’plugin-name’ attribute to the create stanza element. +
    {nodetree, Nodetree}
    +To specify which nodetree to use. +If not defined, the default pubsub nodetree is used: "tree". +Only one nodetree can be used per host, and is shared by all node plugins.

    The "virtual" nodetree does not store nodes on database. +This saves resources on systems with tons of nodes. +If using the "virtual" nodetree, +you can only enable those node plugins: +["flat","pep"] or ["flat"]; +any other plugins configuration will not work. +Also, all nodes will have the defaut configuration, +and this can not be changed. +Using "virtual" nodetree requires to start from a clean database, +it will not work if you used the default "tree" nodetree before.

    The "dag" nodetree provides experimental support for PubSub Collection Nodes (XEP-0248). +In that case you should also add "dag" node plugin as default, for example: +{plugins, ["dag","flat","hometree","pep"]} +

    {ignore_pep_from_offline, false|true}
    +To specify whether or not we should get last published PEP items +from users in our roster which are offline when we connect. Value is true or false. +If not defined, pubsub assumes true so we only get last items of online contacts. +
    {last_item_cache, false|true}
    +To specify whether or not pubsub should cache last items. Value is true +or false. If not defined, pubsub do not cache last items. On systems with not so many nodes, +caching last items speeds up pubsub and allows to raise user connection rate. The cost is memory +usage, as every item is stored in memory. +
    {pep_mapping, [ {Key, Value}, ...]}
    +This allow to define a Key-Value list to choose defined node plugins on given PEP namespace. +The following example will use node_tune instead of node_pep for every PEP node with tune namespace: +
      {mod_pubsub, [{pep_mapping, [{"http://jabber.org/protocol/tune", "tune"}]}]}
    +

    Example of configuration that uses flat nodes as default, and allows use of flat, nodetree and pep nodes: +

    {modules,
    + [
    +  ...
    +  {mod_pubsub, [
    +                {access_createnode, pubsub_createnode},
    +                {plugins, ["flat", "hometree", "pep"]}
    +               ]},
    +  ...
    + ]}.
    +

    Using ODBC database requires use of dedicated plugins. The following example shows previous configuration +with ODBC usage: +

    {modules,
    + [
    +  ...
    +  {mod_pubsub_odbc, [
    +                {access_createnode, pubsub_createnode},
    +                {plugins, ["flat_odbc", "hometree_odbc", "pep_odbc"]}
    +               ]},
    +  ...
    + ]}.
    +

    +

    3.3.18  mod_register

    +

    This module adds support for In-Band Registration (XEP-0077). This protocol +enables end users to use a XMPP client to: +

    • +Register a new account on the server. +
    • Change the password from an existing account on the server. +
    • Delete an existing account on the server. +

    Options: +

    +{access, AccessName}
    This option can be configured to specify +rules to restrict registration. If a rule returns ‘deny’ on the requested +user name, registration for that user name is denied. (there are no +restrictions by default). +
    {access_from, AccessName}
    By default, ejabberd +doesn’t allow to register new accounts from s2s or existing c2s sessions. You can +change it by defining access rule in this option. Use with care: allowing registration +from s2s leads to uncontrolled massive accounts creation by rogue users. +
    {welcome_message, Message}
    Set a welcome message that +is sent to each newly registered account. The first string is the subject, and +the second string is the message body. +In the body you can set a newline with the characters: \n +
    {registration_watchers, [ JID, ...]}
    This option defines a +list of JIDs which will be notified each time a new account is registered. +
    {iqdisc, Discipline}
    This specifies +the processing discipline for In-Band Registration (jabber:iq:register) IQ queries (see section 3.3.2). +

    This module reads also another option defined globally for the server: +{registration_timeout, Timeout}. +This option limits the frequency of registration from a given IP or username. +So, a user that tries to register a new account from the same IP address or JID during +this number of seconds after his previous registration +will receive an error resource-constraint with the explanation: +“Users are not allowed to register accounts so quickly”. +The timeout is expressed in seconds, and it must be an integer. +To disable this limitation, +instead of an integer put a word like: infinity. +Default value: 600 seconds.

    Examples: +

    • +Next example prohibits the registration of too short account names: +
      {acl, shortname, {user_glob, "?"}}.
      +{acl, shortname, {user_glob, "??"}}.
      +%% The same using regexp:
      +%%{acl, shortname, {user_regexp, "^..?$"}}.
      +
      +{access, register, [{deny, shortname},
      +                    {allow, all}]}.
      +
      +{modules,
      + [
      +  ...
      +  {mod_register, [{access, register}]},
      +  ...
      + ]}.
      +
    • This configuration prohibits usage of In-Band Registration +to create or delete accounts, +but allows existing accounts to change the password: +
      {access, register, [{deny, all}]}.
      +
      +{modules,
      + [
      +  ...
      +  {mod_register, [{access, register}]},
      +  ...
      + ]}.
      +
    • This configuration disables all In-Band Registration +functionality: create, delete accounts and change password: +
      {modules,
      + [
      +  ...
      +  %% {mod_register, [{access, register}]},
      +  ...
      + ]}.
      +
    • Define the welcome message and two registration watchers. +Also define a registration timeout of one hour: +
      {registration_timeout, 3600}.
      +{modules,
      + [
      +  ...
      +  {mod_register,
      +   [
      +    {welcome_message, {"Welcome!", "Hi.\nWelcome to this Jabber server.\n Check http://www.jabber.org\n\nBye"}},
      +    {registration_watchers, ["admin1@example.org", "boss@example.net"]}
      +   ]},
      +  ...
      + ]}.
      +

    +

    3.3.19  mod_roster

    +

    This module implements roster management as defined in +RFC 3921: XMPP IM. +It also supports Roster Versioning (XEP-0237).

    Options: +

    +{iqdisc, Discipline}
    This specifies +the processing discipline for Roster Management (jabber:iq:roster) IQ queries (see section 3.3.2). +
    {versioning, false|true}
    Enables +Roster Versioning. +This option is disabled by default. +
    {store_current_id, false|true}
    +If this option is enabled, the current version number is stored on the database. +If disabled, the version number is calculated on the fly each time. +Enabling this option reduces the load for both ejabberd and the database. +This option does not affect the client in any way. +This option is only useful if Roster Versioning is enabled. +This option is disabled by default. +Important: if you use mod_shared_roster, you must disable this option. +

    This example configuration enables Roster Versioning with storage of current id: +

    {modules,
    + [
    +  ...
    +  {mod_roster, [{versioning, true}, {store_current_id, true}]},
    +  ...
    + ]}.
    +

    +

    3.3.20  mod_service_log

    +

    This module adds support for logging end user packets via a XMPP message +auditing service such as +Bandersnatch. All user +packets are encapsulated in a <route/> element and sent to the specified +service(s).

    Options: +

    +{loggers, [Names, ...]}
    With this option a (list of) service(s) +that will receive the packets can be specified. +

    Examples: +

    • +To log all end user packets to the Bandersnatch service running on +bandersnatch.example.com: +
      {modules,
      + [
      +  ...
      +  {mod_service_log, [{loggers, ["bandersnatch.example.com"]}]},
      +  ...
      + ]}.
      +
    • To log all end user packets to the Bandersnatch service running on +bandersnatch.example.com and the backup service on +bandersnatch.example.org: +
      {modules,
      + [
      +  ...
      +  {mod_service_log, [{loggers, ["bandersnatch.example.com",
      +                                "bandersnatch.example.org"]}]},
      +  ...
      + ]}.
      +

    +

    3.3.21  mod_shared_roster

    +

    This module enables you to create shared roster groups. This means that you can +create groups of people that can see members from (other) groups in their +rosters. The big advantages of this feature are that end users do not need to +manually add all users to their rosters, and that they cannot permanently delete +users from the shared roster groups. +A shared roster group can have members from any XMPP server, +but the presence will only be available from and to members +of the same virtual host where the group is created.

    Shared roster groups can be edited only via the Web Admin. Each group +has a unique identification and the following parameters: +

    +Name
    The name of the group, which will be displayed in the roster. +
    Description
    The description of the group. This parameter does not affect +anything. +
    Members
    A list of full JIDs of group members, entered one per line in +the Web Admin. +To put as members all the registered users in the virtual hosts, +you can use the special directive: @all@. +Note that this directive is designed for a small server with just a few hundred users. +
    Displayed groups
    A list of groups that will be in the rosters of this +group’s members. +

    Examples: +

    • +Take the case of a computer club that wants all its members seeing each +other in their rosters. To achieve this, they need to create a shared roster +group similar to next table: +

      + + + + + +
      IdentificationGroup ‘club_members
      NameClub Members
      DescriptionMembers from the computer club
      Members + + +
      member1@example.org
      member2@example.org
      member3@example.org
      Displayed groupsclub_members
      +

      +
    • In another case we have a company which has three divisions: Management, +Marketing and Sales. All group members should see all other members in their +rosters. Additionally, all managers should have all marketing and sales people +in their roster. Simultaneously, all marketeers and the whole sales team +should see all managers. This scenario can be achieved by creating shared +roster groups as shown in the following table: +

      + + + + + +
      Identification Group ‘management Group ‘marketing Group ‘sales
      NameManagementMarketingSales
      Description 
      Members + + + +
      manager1@example.org
      manager2@example.org
      manager3@example.org
      manager4@example.org
      +
      + + + +
      marketeer1@example.org
      marketeer2@example.org
      marketeer3@example.org
      marketeer4@example.org
      +
      + + + +
      saleswoman1@example.org
      salesman1@example.org
      saleswoman2@example.org
      salesman2@example.org
      Displayed groups + + +
      management
      marketing
      sales
      +
      + +
      management
      marketing
      +
      + +
      management
      sales
      +

      +

    +

    3.3.22  mod_sic

    +

    This module adds support for Server IP Check (XEP-0279). This protocol +enables a client to discover its external IP address.

    Options: +

    +{iqdisc, Discipline}
    This specifies +the processing discipline for urn:xmpp:sic:0 IQ queries (see section 3.3.2). +

    +

    3.3.23  mod_stats

    +

    This module adds support for Statistics Gathering (XEP-0039). This protocol +allows you to retrieve next statistics from your ejabberd deployment: +

    • +Total number of registered users on the current virtual host (users/total). +
    • Total number of registered users on all virtual hosts (users/all-hosts/total). +
    • Total number of online users on the current virtual host (users/online). +
    • Total number of online users on all virtual hosts (users/all-hosts/online). +

    Options: +

    +{iqdisc, Discipline}
    This specifies +the processing discipline for Statistics Gathering (http://jabber.org/protocol/stats) IQ queries (see section 3.3.2). +

    As there are only a small amount of clients (for example +Tkabber) and software libraries with +support for this XEP, a few examples are given of the XML you need to send +in order to get the statistics. Here they are: +

    • +You can request the number of online users on the current virtual host +(example.org) by sending: +
      <iq to='example.org' type='get'>
      +  <query xmlns='http://jabber.org/protocol/stats'>
      +    <stat name='users/online'/>
      +  </query>
      +</iq>
      +
    • You can request the total number of registered users on all virtual hosts +by sending: +
      <iq to='example.org' type='get'>
      +  <query xmlns='http://jabber.org/protocol/stats'>
      +    <stat name='users/all-hosts/total'/>
      +  </query>
      +</iq>
      +

    +

    3.3.24  mod_time

    +

    This module features support for Entity Time (XEP-0202). By using this XEP, +you are able to discover the time at another entity’s location.

    Options: +

    +{iqdisc, Discipline}
    This specifies +the processing discipline for Entity Time (jabber:iq:time) IQ queries (see section 3.3.2). +

    +

    3.3.25  mod_vcard

    +

    This module allows end users to store and retrieve their vCard, and to retrieve +other users vCards, as defined in vcard-temp (XEP-0054). The module also +implements an uncomplicated Jabber User Directory based on the vCards of +these users. Moreover, it enables the server to send its vCard when queried.

    Options: +

    + +{host, HostName}
    This option defines the Jabber ID of the +service. If the host option is not specified, the Jabber ID will be the +hostname of the virtual host with the prefix ‘vjud.’. The keyword "@HOST@" +is replaced at start time with the real virtual host name. + +
    {iqdisc, Discipline}
    This specifies +the processing discipline for vcard-temp IQ queries (see section 3.3.2). +
    {search, true|false}
    This option specifies whether the search +functionality is enabled or not +If disabled, the option host will be ignored and the +Jabber User Directory service will not appear in the Service Discovery item +list. The default value is true. +
    {matches, infinity|Number}
    With this option, the number of reported +search results can be limited. If the option’s value is set to infinity, +all search results are reported. The default value is 30. +
    {allow_return_all, false|true}
    This option enables +you to specify if search operations with empty input fields should return all +users who added some information to their vCard. The default value is +false. +
    {search_all_hosts, true|false}
    If this option is set +to true, search operations will apply to all virtual hosts. Otherwise +only the current host will be searched. The default value is true. +This option is available in mod_vcard, but not available in mod_vcard_odbc. +

    Examples: +

    • +In this first situation, search results are limited to twenty items, +every user who added information to their vCard will be listed when people +do an empty search, and only users from the current host will be returned: +
      {modules,
      + [
      +  ...
      +  {mod_vcard, [{search, true},
      +               {matches, 20},
      +               {allow_return_all, true},
      +               {search_all_hosts, false}]},
      +  ...
      + ]}.
      +
    • The second situation differs in a way that search results are not limited, +and that all virtual hosts will be searched instead of only the current one: +
      {modules,
      + [
      +  ...
      +  {mod_vcard, [{search, true},
      +               {matches, infinity},
      +               {allow_return_all, true}]},
      +  ...
      + ]}.
      +

    +

    3.3.26  mod_vcard_ldap

    +

    ejabberd can map LDAP attributes to vCard fields. This behaviour is +implemented in the mod_vcard_ldap module. This module does not depend on the +authentication method (see 3.2.5).

    Usually ejabberd treats LDAP as a read-only storage: +it is possible to consult data, but not possible to +create accounts or edit vCard that is stored in LDAP. +However, it is possible to change passwords if mod_register module is enabled +and LDAP server supports +RFC 3062.

    The mod_vcard_ldap module has +its own optional parameters. The first group of parameters has the same +meaning as the top-level LDAP parameters to set the authentication method: +ldap_servers, ldap_port, ldap_rootdn, +ldap_password, ldap_base, ldap_uids, and +ldap_filter. See section 3.2.5 for detailed information +about these options. If one of these options is not set, ejabberd will look +for the top-level option with the same name.

    The second group of parameters +consists of the following mod_vcard_ldap-specific options:

    + +{host, HostName}
    This option defines the Jabber ID of the +service. If the host option is not specified, the Jabber ID will be the +hostname of the virtual host with the prefix ‘vjud.’. The keyword "@HOST@" +is replaced at start time with the real virtual host name. + +
    {iqdisc, Discipline}
    This specifies +the processing discipline for vcard-temp IQ queries (see section 3.3.2). +
    {search, true|false}
    This option specifies whether the search +functionality is enabled (value: true) or disabled (value: +false). If disabled, the option host will be ignored and the +Jabber User Directory service will not appear in the Service Discovery item +list. The default value is true. +
    {matches, infinity|Number}
    With this option, the number of reported +search results can be limited. If the option’s value is set to infinity, +all search results are reported. The default value is 30. +
    {ldap_vcard_map, [ {Name, Pattern, LDAPattributes}, ...]}
    +With this option you can set the table that maps LDAP attributes to vCard fields. + +Name is the type name of the vCard as defined in +RFC 2426. +Pattern is a string which contains pattern variables +"%u", "%d" or "%s". +LDAPattributes is the list containing LDAP attributes. +The pattern variables +"%s" will be sequentially replaced +with the values of LDAP attributes from List_of_LDAP_attributes, +"%u" will be replaced with the user part of a JID, +and "%d" will be replaced with the domain part of a JID. +The default is: +
    [{"NICKNAME", "%u", []},
    + {"FN", "%s", ["displayName"]},
    + {"LAST", "%s", ["sn"]},
    + {"FIRST", "%s", ["givenName"]},
    + {"MIDDLE", "%s", ["initials"]},
    + {"ORGNAME", "%s", ["o"]},
    + {"ORGUNIT", "%s", ["ou"]},
    + {"CTRY", "%s", ["c"]},
    + {"LOCALITY", "%s", ["l"]},
    + {"STREET", "%s", ["street"]},
    + {"REGION", "%s", ["st"]},
    + {"PCODE", "%s", ["postalCode"]},
    + {"TITLE", "%s", ["title"]},
    + {"URL", "%s", ["labeleduri"]},
    + {"DESC", "%s", ["description"]},
    + {"TEL", "%s", ["telephoneNumber"]},
    + {"EMAIL", "%s", ["mail"]},
    + {"BDAY", "%s", ["birthDay"]},
    + {"ROLE", "%s", ["employeeType"]},
    + {"PHOTO", "%s", ["jpegPhoto"]}]
    +
    {ldap_search_fields, [ {Name, Attribute}, ...]}
    This option +defines the search form and the LDAP attributes to search within. +Name is the name of a search form +field which will be automatically translated by using the translation +files (see msgs/*.msg for available words). Attribute is the +LDAP attribute or the pattern "%u". The default is: +
    [{"User", "%u"},
    + {"Full Name", "displayName"},
    + {"Given Name", "givenName"},
    + {"Middle Name", "initials"},
    + {"Family Name", "sn"},
    + {"Nickname", "%u"},
    + {"Birthday", "birthDay"},
    + {"Country", "c"},
    + {"City", "l"},
    + {"Email", "mail"},
    + {"Organization Name", "o"},
    + {"Organization Unit", "ou"}]
    +
    {ldap_search_reported, [ {SearchField, VcardField}, ...]}
    This option +defines which search fields should be reported. +SearchField is the name of a search form +field which will be automatically translated by using the translation +files (see msgs/*.msg for available words). VcardField is the +vCard field name defined in the ldap_vcard_map option. The default +is: +
    [{"Full Name", "FN"},
    + {"Given Name", "FIRST"},
    + {"Middle Name", "MIDDLE"},
    + {"Family Name", "LAST"},
    + {"Nickname", "NICKNAME"},
    + {"Birthday", "BDAY"},
    + {"Country", "CTRY"},
    + {"City", "LOCALITY"},
    + {"Email", "EMAIL"},
    + {"Organization Name", "ORGNAME"},
    + {"Organization Unit", "ORGUNIT"}]
    +

    Examples: +

    • +

      Let’s say ldap.example.org is the name of our LDAP server. We have +users with their passwords in "ou=Users,dc=example,dc=org" directory. +Also we have addressbook, which contains users emails and their additional +infos in "ou=AddressBook,dc=example,dc=org" directory. Corresponding +authentication section should looks like this:

      %% authentication method
      +{auth_method, ldap}.
      +%% DNS name of our LDAP server
      +{ldap_servers, ["ldap.example.org"]}.
      +%% We want to authorize users from 'shadowAccount' object class only
      +{ldap_filter, "(objectClass=shadowAccount)"}.
      +

      Now we want to use users LDAP-info as their vCards. We have four attributes +defined in our LDAP schema: "mail" — email address, "givenName" +— first name, "sn" — second name, "birthDay" — birthday. +Also we want users to search each other. Let’s see how we can set it up:

      {modules,
      +  ...
      +  {mod_vcard_ldap,
      +   [
      +    %% We use the same server and port, but want to bind anonymously because
      +    %% our LDAP server accepts anonymous requests to
      +    %% "ou=AddressBook,dc=example,dc=org" subtree.
      +    {ldap_rootdn, ""},
      +    {ldap_password, ""},
      +    %% define the addressbook's base
      +    {ldap_base, "ou=AddressBook,dc=example,dc=org"},
      +    %% uidattr: user's part of JID is located in the "mail" attribute
      +    %% uidattr_format: common format for our emails
      +    {ldap_uids, [{"mail","%u@mail.example.org"}]},
      +    %% We have to define empty filter here, because entries in addressbook does not
      +    %% belong to shadowAccount object class
      +    {ldap_filter, ""},
      +    %% Now we want to define vCard pattern
      +    {ldap_vcard_map,
      +     [{"NICKNAME", "%u", []}, % just use user's part of JID as his nickname
      +      {"FIRST", "%s", ["givenName"]},
      +      {"LAST", "%s", ["sn"]},
      +      {"FN", "%s, %s", ["sn", "givenName"]}, % example: "Smith, John"
      +      {"EMAIL", "%s", ["mail"]},
      +      {"BDAY", "%s", ["birthDay"]}]},
      +    %% Search form
      +    {ldap_search_fields,
      +     [{"User", "%u"},
      +      {"Name", "givenName"},
      +      {"Family Name", "sn"},
      +      {"Email", "mail"},
      +      {"Birthday", "birthDay"}]},
      +    %% vCard fields to be reported
      +    %% Note that JID is always returned with search results
      +    {ldap_search_reported,
      +     [{"Full Name", "FN"},
      +      {"Nickname", "NICKNAME"},
      +      {"Birthday", "BDAY"}]}
      +  ]}
      +  ...
      +}.
      +

      Note that mod_vcard_ldap module checks an existence of the user before +searching his info in LDAP.

    • ldap_vcard_map example: +
      {ldap_vcard_map,
      + [{"NICKNAME", "%u", []},
      +  {"FN", "%s", ["displayName"]},
      +  {"CTRY", "Russia", []},
      +  {"EMAIL", "%u@%d", []},
      +  {"DESC", "%s\n%s", ["title", "description"]}
      + ]},
      +
    • ldap_search_fields example: +
      {ldap_search_fields,
      + [{"User", "uid"},
      +  {"Full Name", "displayName"},
      +  {"Email", "mail"}
      + ]},
      +
    • ldap_search_reported example: +
      {ldap_search_reported,
      + [{"Full Name", "FN"},
      +  {"Email", "EMAIL"},
      +  {"Birthday", "BDAY"},
      +  {"Nickname", "NICKNAME"}
      + ]},
      +

    +

    3.3.27  mod_vcard_xupdate

    +

    The user’s client can store an avatar in the user vCard. +The vCard-Based Avatars protocol (XEP-0153) +provides a method for clients to inform the contacts what is the avatar hash value. +However, simple or small clients may not implement that protocol.

    If this module is enabled, all the outgoing client presence stanzas get automatically +the avatar hash on behalf of the client. +So, the contacts receive the presence stanzas with the Update Data described +in XEP-0153 as if the client would had inserted it itself. +If the client had already included such element in the presence stanza, +it is replaced with the element generated by ejabberd.

    By enabling this module, each vCard modification produces a hash recalculation, +and each presence sent by a client produces hash retrieval and a +presence stanza rewrite. +For this reason, enabling this module will introduce a computational overhead +in servers with clients that change frequently their presence.

    +

    3.3.28  mod_version

    +

    This module implements Software Version (XEP-0092). Consequently, it +answers ejabberd’s version when queried.

    Options: +

    +{show_os, true|false}
    Should the operating system be revealed or not. +The default value is true. +
    {iqdisc, Discipline}
    This specifies +the processing discipline for Software Version (jabber:iq:version) IQ queries (see section 3.3.2). +

    +

    Chapter 4  Managing an ejabberd Server

    +

    4.1  ejabberdctl

    With the ejabberdctl command line administration script +you can execute ejabberdctl commands (described in the next section, 4.1.1) +and also many general ejabberd commands (described in section 4.2). +This means you can start, stop and perform many other administrative tasks +in a local or remote ejabberd server (by providing the argument --node NODENAME).

    The ejabberdctl script can be configured in the file ejabberdctl.cfg. +This file includes detailed information about each configurable option. See section 4.1.2.

    The ejabberdctl script returns a numerical status code. +Success is represented by 0, +error is represented by 1, +and other codes may be used for specific results. +This can be used by other scripts to determine automatically +if a command succeeded or failed, +for example using: echo $?

    +

    4.1.1  ejabberdctl Commands

    When ejabberdctl is executed without any parameter, +it displays the available options. If there isn’t an ejabberd server running, +the available parameters are: +

    +start
    Start ejabberd in background mode. This is the default method. +
    debug
    Attach an Erlang shell to an already existing ejabberd server. This allows to execute commands interactively in the ejabberd server. +
    live
    Start ejabberd in live mode: the shell keeps attached to the started server, showing log messages and allowing to execute interactive commands. +

    If there is an ejabberd server running in the system, +ejabberdctl shows the ejabberdctl commands described bellow +and all the ejabberd commands available in that server (see 4.2.1).

    The ejabberdctl commands are: +

    +help
    Get help about ejabberdctl or any available command. Try ejabberdctl help help. +
    status
    Check the status of the ejabberd server. +
    stop
    Stop the ejabberd server. +
    restart
    Restart the ejabberd server. +
    mnesia
    Get information about the Mnesia database. +

    The ejabberdctl script can be restricted to require authentication +and execute some ejabberd commands; see 4.2.2. +Add the option to the file ejabberd.cfg. +In this example there is no restriction: +

    {ejabberdctl_access_commands, []}.
    +

    If account robot1@example.org is registered in ejabberd with password abcdef +(which MD5 is E8B501798950FC58AAD83C8C14978E), +and ejabberd.cfg contains this setting: +

    {hosts, ["example.org"]}.
    +{acl, bots, {user, "robot1", "example.org"}}.
    +{access, ctlaccess, [{allow, bots}]}.
    +{ejabberdctl_access_commands, [ {ctlaccess, [registered_users, register], []} ]}.
    +

    then you can do this in the shell: +

    $ ejabberdctl registered_users example.org
    +Error: no_auth_provided
    +$ ejabberdctl --auth robot1 example.org E8B501798950FC58AAD83C8C14978E registered_users example.org
    +robot1
    +testuser1
    +testuser2
    +

    +

    4.1.2  Erlang Runtime System

    ejabberd is an Erlang/OTP application that runs inside an Erlang runtime system. +This system is configured using environment variables and command line parameters. +The ejabberdctl administration script uses many of those possibilities. +You can configure some of them with the file ejabberdctl.cfg, +which includes detailed description about them. +This section describes for reference purposes +all the environment variables and command line parameters.

    The environment variables: +

    +EJABBERD_CONFIG_PATH
    + Path to the ejabberd configuration file. +
    EJABBERD_MSGS_PATH
    + Path to the directory with translated strings. +
    EJABBERD_LOG_PATH
    + Path to the ejabberd service log file. +
    EJABBERD_SO_PATH
    + Path to the directory with binary system libraries. +
    EJABBERD_DOC_PATH
    + Path to the directory with ejabberd documentation. +
    EJABBERD_PID_PATH
    + Path to the PID file that ejabberd can create when started. +
    HOME
    + Path to the directory that is considered ejabberd’s home. + This path is used to read the file .erlang.cookie. +
    ERL_CRASH_DUMP
    + Path to the file where crash reports will be dumped. +
    ERL_INETRC
    + Indicates which IP name resolution to use. + If using -sname, specify either this option or -kernel inetrc filepath. +
    ERL_MAX_PORTS
    + Maximum number of simultaneously open Erlang ports. +
    ERL_MAX_ETS_TABLES
    + Maximum number of ETS and Mnesia tables. +

    The command line parameters: +

    +-sname ejabberd
    + The Erlang node will be identified using only the first part + of the host name, i. e. other Erlang nodes outside this domain cannot contact + this node. This is the preferable option in most cases. +
    -name ejabberd
    + The Erlang node will be fully identified. +This is only useful if you plan to setup an ejabberd cluster with nodes in different networks. +
    -kernel inetrc ’"/etc/ejabberd/inetrc"’
    + Indicates which IP name resolution to use. + If using -sname, specify either this option or ERL_INETRC. +
    -kernel inet_dist_listen_min 4200 inet_dist_listen_min 4210
    + Define the first and last ports that epmd (section 5.2) can listen to. +
    -detached
    +Starts the Erlang system detached from the system console. + Useful for running daemons and backgrounds processes. +
    -noinput
    + Ensures that the Erlang system never tries to read any input. + Useful for running daemons and backgrounds processes. +
    -pa /var/lib/ejabberd/ebin
    + Specify the directory where Erlang binary files (*.beam) are located. +
    -s ejabberd
    + Tell Erlang runtime system to start the ejabberd application. +
    -mnesia dir ’"/var/lib/ejabberd/"’
    + Specify the Mnesia database directory. +
    -sasl sasl_error_logger {file, "/var/log/ejabberd/erlang.log"}
    + Path to the Erlang/OTP system log file. +SASL here means “System Architecture Support Libraries” +not “Simple Authentication and Security Layer”. +
    +K [true|false]
    + Kernel polling. +
    -smp [auto|enable|disable]
    + SMP support. +
    +P 250000
    + Maximum number of Erlang processes. +
    -remsh ejabberd@localhost
    + Open an Erlang shell in a remote Erlang node. +
    -hidden
    + The connections to other nodes are hidden (not published). + The result is that this node is not considered part of the cluster. + This is important when starting a temporary ctl or debug node. +

    +Note that some characters need to be escaped when used in shell scripts, for instance " and {}. +You can find other options in the Erlang manual page (erl -man erl).

    +

    4.2  ejabberd Commands

    An ejabberd command is an abstract function identified by a name, +with a defined number and type of calling arguments and type of result +that is registered in the ejabberd_commands service. +Those commands can be defined in any Erlang module and executed using any valid frontend.

    ejabberd includes a frontend to execute ejabberd commands: the script ejabberdctl. +Other known frontends that can be installed to execute ejabberd commands in different ways are: +ejabberd_xmlrpc (XML-RPC service), +mod_rest (HTTP POST service), +mod_shcommands (ejabberd WebAdmin page).

    +

    4.2.1  List of ejabberd Commands

    ejabberd includes a few ejabberd Commands by default. +When more modules are installed, new commands may be available in the frontends.

    The easiest way to get a list of the available commands, and get help for them is to use +the ejabberdctl script: +

    $ ejabberdctl help
    +Usage: ejabberdctl [--node nodename] [--auth user host password] command [options]
    +
    +Available commands in this ejabberd node:
    +  backup file                  Store the database to backup file
    +  connected_users              List all established sessions
    +  connected_users_number       Get the number of established sessions
    +  ...
    +

    The most interesting ones are: +

    +reopen_log
    Reopen the log files after they were renamed. +If the old files were not renamed before calling this command, +they are automatically renamed to "*-old.log". See section 7.1. +
    backup ejabberd.backup
    +Store internal Mnesia database to a binary backup file. +
    restore ejabberd.backup
    +Restore immediately from a binary backup file the internal Mnesia database. +This will consume a lot of memory if you have a large database, +so better use install_fallback. +
    install_fallback ejabberd.backup
    +The binary backup file is installed as fallback: +it will be used to restore the database at the next ejabberd start. +This means that, after running this command, you have to restart ejabberd. +This command requires less memory than restore. +
    dump ejabberd.dump
    +Dump internal Mnesia database to a text file dump. +
    load ejabberd.dump
    +Restore immediately from a text file dump. +This is not recommended for big databases, as it will consume much time, +memory and processor. In that case it’s preferable to use backup and install_fallback. +
    import_piefxis, export_piefxis, export_piefxis_host
    +These options can be used to migrate accounts +using XEP-0227 formatted XML files +from/to other Jabber/XMPP servers +or move users of a vhost to another ejabberd installation. +See also ejabberd migration kit. +
    import_file, import_dir
    +These options can be used to migrate accounts +using jabberd1.4 formatted XML files. +from other Jabber/XMPP servers +There exist tutorials to +migrate from other software to ejabberd. +
    delete_expired_messages
    This option can be used to delete old messages +in offline storage. This might be useful when the number of offline messages +is very high. +
    delete_old_messages days
    Delete offline messages older than the given days. +
    register user host password
    Register an account in that domain with the given password. +
    unregister user host
    Unregister the given account. +

    +

    4.2.2  Restrict Execution with AccessCommands

    The frontends can be configured to restrict access to certain commands. +In that case, authentication information must be provided. +In each frontend the AccessCommands option is defined +in a different place. But in all cases the option syntax is the same: +

    AccessCommands = [ {Access, CommandNames, Arguments}, ...]
    +Access = atom()
    +CommandNames = all | [CommandName]
    +CommandName = atom()
    +Arguments = [ {ArgumentName, ArgumentValue}, ...]
    +ArgumentName = atom()
    +ArgumentValue = any()
    +

    The default value is to not define any restriction: []. +The authentication information is provided when executing a command, +and is Username, Hostname and Password of a local XMPP account +that has permission to execute the corresponding command. +This means that the account must be registered in the local ejabberd, +because the information will be verified. +It is possible to provide the plaintext password or its MD5 sum.

    When one or several access restrictions are defined and the +authentication information is provided, +each restriction is verified until one matches completely: +the account matches the Access rule, +the command name is listed in CommandNames, +and the provided arguments do not contradict Arguments.

    As an example to understand the syntax, let’s suppose those options: +

    {hosts, ["example.org"]}.
    +{acl, bots, {user, "robot1", "example.org"}}.
    +{access, commaccess, [{allow, bots}]}.
    +

    This list of access restrictions allows only robot1@example.org to execute all commands: +

    [{commaccess, all, []}]
    +

    See another list of restrictions (the corresponding ACL and ACCESS are not shown): +

    [
    + %% This bot can execute all commands:
    + {bot, all, []},
    + %% This bot can only execute the command 'dump'. No argument restriction:
    + {bot_backups, [dump], []}
    + %% This bot can execute all commands,
    + %% but if a 'host' argument is provided, it must be "example.org":
    + {bot_all_example, all, [{host, "example.org"}]},
    + %% This bot can only execute the command 'register',
    + %% and if argument 'host' is provided, it must be "example.org":
    + {bot_reg_example, [register], [{host, "example.org"}]},
    + %% This bot can execute the commands 'register' and 'unregister',
    + %% if argument host is provided, it must be "test.org":
    + {_bot_reg_test, [register, unregister], [{host, "test.org"}]}
    +]
    +

    +

    4.3  Web Admin

    +

    The ejabberd Web Admin allows to administer most of ejabberd using a web browser.

    This feature is enabled by default: +a ejabberd_http listener with the option web_admin (see +section 3.1.3) is included in the listening ports. Then you can open +http://server:port/admin/ in your favourite web browser. You +will be asked to enter the username (the full Jabber ID) and password +of an ejabberd user with administrator rights. After authentication +you will see a page similar to figure 4.1.


    + +webadmmain.png + + +
    +
    Figure 4.1: Top page from the Web Admin
    + +

    +Here you can edit access restrictions, manage users, create backups, +manage the database, enable/disable ports listened for, view server +statistics,…

    The access rule configure determines what accounts can access the Web Admin and modify it. +The access rule webadmin_view is to grant only view access: those accounts can browse the Web Admin with read-only access.

    Example configurations: +

    • +You can serve the Web Admin on the same port as the +HTTP Polling interface. In this example +you should point your web browser to http://example.org:5280/admin/ to +administer all virtual hosts or to +http://example.org:5280/admin/server/example.com/ to administer only +the virtual host example.com. Before you get access to the Web Admin +you need to enter as username, the JID and password from a registered user +that is allowed to configure ejabberd. In this example you can enter as +username ‘admin@example.net’ to administer all virtual hosts (first +URL). If you log in with ‘admin@example.com’ on
      + http://example.org:5280/admin/server/example.com/ you can only +administer the virtual host example.com. +The account ‘reviewer@example.com’ can browse that vhost in read-only mode. +
      {acl, admins, {user, "admin", "example.net"}}.
      +{host_config, "example.com", [{acl, admins, {user, "admin", "example.com"}}]}.
      +{host_config, "example.com", [{acl, viewers, {user, "reviewer", "example.com"}}]}.
      +
      +{access, configure, [{allow, admins}]}.
      +{access, webadmin_view, [{allow, viewers}]}.
      +
      +{hosts, ["example.org"]}.
      +
      +{listen,
      + [
      +  ...
      +  {5280, ejabberd_http, [http_poll, web_admin]},
      +  ...
      + ]}.
      +
    • For security reasons, you can serve the Web Admin on a secured +connection, on a port differing from the HTTP Polling interface, and bind it +to the internal LAN IP. The Web Admin will be accessible by pointing your +web browser to https://192.168.1.1:5282/admin/: +
      +{hosts, ["example.org"]}.
      +
      +{listen,
      + [
      +  ...
      +  {5280, ejabberd_http, [
      +                         http_poll
      +                        ]},
      +  {{5282, "192.168.1.1"}, ejabberd_http, [
      +                                          web_admin,
      +                                          tls, {certfile, "/usr/local/etc/server.pem"}
      +                                         ]},
      +  ...
      + ]}.
      +

    Certain pages in the ejabberd Web Admin contain a link to a related +section in the ejabberd Installation and Operation Guide. +In order to view such links, a copy in HTML format of the Guide must +be installed in the system. +The file is searched by default in +"/share/doc/ejabberd/guide.html". +The directory of the documentation can be specified in +the environment variable EJABBERD_DOC_PATH. +See section 4.1.2.

    +

    4.4  Ad-hoc Commands

    If you enable mod_configure and mod_adhoc, +you can perform several administrative tasks in ejabberd +with a XMPP client. +The client must support Ad-Hoc Commands (XEP-0050), +and you must login in the XMPP server with +an account with proper privileges.

    +

    4.5  Change Computer Hostname

    ejabberd uses the distributed Mnesia database. +Being distributed, Mnesia enforces consistency of its file, +so it stores the name of the Erlang node in it (see section 5.4). +The name of an Erlang node includes the hostname of the computer. +So, the name of the Erlang node changes +if you change the name of the machine in which ejabberd runs, +or when you move ejabberd to a different machine.

    You have two ways to use the old Mnesia database in an ejabberd with new node name: +put the old node name in ejabberdctl.cfg, +or convert the database to the new node name.

    Those example steps will backup, convert and load the Mnesia database. +You need to have either the old Mnesia spool dir or a backup of Mnesia. +If you already have a backup file of the old database, you can go directly to step 5. +You also need to know the old node name and the new node name. +If you don’t know them, look for them by executing ejabberdctl +or in the ejabberd log files.

    Before starting, setup some variables: +

    OLDNODE=ejabberd@oldmachine
    +NEWNODE=ejabberd@newmachine
    +OLDFILE=/tmp/old.backup
    +NEWFILE=/tmp/new.backup
    +
    1. +Start ejabberd enforcing the old node name: +
      ejabberdctl --node $OLDNODE start
      +
    2. Generate a backup file: +
      ejabberdctl --node $OLDNODE backup $OLDFILE
      +
    3. Stop the old node: +
      ejabberdctl --node $OLDNODE stop
      +
    4. Make sure there aren’t files in the Mnesia spool dir. For example: +
      mkdir /var/lib/ejabberd/oldfiles
      +mv /var/lib/ejabberd/*.* /var/lib/ejabberd/oldfiles/
      +
    5. Start ejabberd. There isn’t any need to specify the node name anymore: +
      ejabberdctl start
      +
    6. Convert the backup to new node name: +
      ejabberdctl mnesia_change_nodename $OLDNODE $NEWNODE $OLDFILE $NEWFILE
      +
    7. Install the backup file as a fallback: +
      ejabberdctl install_fallback $NEWFILE
      +
    8. Stop ejabberd: +
      ejabberdctl stop
      +
      You may see an error message in the log files, it’s normal, so don’t worry: +
      Mnesia(ejabberd@newmachine):
      +** ERROR ** (ignoring core)
      +** FATAL ** A fallback is installed and Mnesia must be restarted.
      +  Forcing shutdown after mnesia_down from ejabberd@newmachine...
      +
    9. Now you can finally start ejabberd: +
      ejabberdctl start
      +
    10. Check that the information of the old database is available: accounts, rosters... +After you finish, remember to delete the temporary backup files from public directories. +

    +

    Chapter 5  Securing ejabberd

    +

    5.1  Firewall Settings

    +

    You need to take the following TCP ports in mind when configuring your firewall: +


    + + + + + + +
    PortDescription
    5222Standard port for Jabber/XMPP client connections, plain or STARTTLS.
    5223Standard port for Jabber client connections using the old SSL method.
    5269Standard port for Jabber/XMPP server connections.
    4369EPMD (section 5.2) listens for Erlang node name requests.
    port rangeUsed for connections between Erlang nodes. This range is configurable (see section 5.2).
    +

    +

    5.2  epmd

    epmd (Erlang Port Mapper Daemon) +is a small name server included in Erlang/OTP +and used by Erlang programs when establishing distributed Erlang communications. +ejabberd needs epmd to use ejabberdctl and also when clustering ejabberd nodes. +This small program is automatically started by Erlang, and is never stopped. +If ejabberd is stopped, and there aren’t any other Erlang programs +running in the system, you can safely stop epmd if you want.

    ejabberd runs inside an Erlang node. +To communicate with ejabberd, the script ejabberdctl starts a new Erlang node +and connects to the Erlang node that holds ejabberd. +In order for this communication to work, +epmd must be running and listening for name requests in the port 4369. +You should block the port 4369 in the firewall in such a way that +only the programs in your machine can access it.

    If you build a cluster of several ejabberd instances, +each ejabberd instance is called an ejabberd node. +Those ejabberd nodes use a special Erlang communication method to +build the cluster, and EPMD is again needed listening in the port 4369. +So, if you plan to build a cluster of ejabberd nodes +you must open the port 4369 for the machines involved in the cluster. +Remember to block the port so Internet doesn’t have access to it.

    Once an Erlang node solved the node name of another Erlang node using EPMD and port 4369, +the nodes communicate directly. +The ports used in this case by default are random, +but can be configured in the file ejabberdctl.cfg. +The Erlang command-line parameter used internally is, for example: +

    erl ... -kernel inet_dist_listen_min 4370 inet_dist_listen_max 4375
    +

    +

    5.3  Erlang Cookie

    The Erlang cookie is a string with numbers and letters. +An Erlang node reads the cookie at startup from the command-line parameter -setcookie. +If not indicated, the cookie is read from the cookie file $HOME/.erlang.cookie. +If this file does not exist, it is created immediately with a random cookie. +Two Erlang nodes communicate only if they have the same cookie. +Setting a cookie on the Erlang node allows you to structure your Erlang network +and define which nodes are allowed to connect to which.

    Thanks to Erlang cookies, you can prevent access to the Erlang node by mistake, +for example when there are several Erlang nodes running different programs in the same machine.

    Setting a secret cookie is a simple method +to difficult unauthorized access to your Erlang node. +However, the cookie system is not ultimately effective +to prevent unauthorized access or intrusion to an Erlang node. +The communication between Erlang nodes are not encrypted, +so the cookie could be read sniffing the traffic on the network. +The recommended way to secure the Erlang node is to block the port 4369.

    +

    5.4  Erlang Node Name

    An Erlang node may have a node name. +The name can be short (if indicated with the command-line parameter -sname) +or long (if indicated with the parameter -name). +Starting an Erlang node with -sname limits the communication between Erlang nodes to the LAN.

    Using the option -sname instead of -name is a simple method +to difficult unauthorized access to your Erlang node. +However, it is not ultimately effective to prevent access to the Erlang node, +because it may be possible to fake the fact that you are on another network +using a modified version of Erlang epmd. +The recommended way to secure the Erlang node is to block the port 4369.

    +

    5.5  Securing Sensitive Files

    ejabberd stores sensitive data in the file system either in plain text or binary files. +The file system permissions should be set to only allow the proper user to read, +write and execute those files and directories.

    +ejabberd configuration file: /etc/ejabberd/ejabberd.cfg
    +Contains the JID of administrators +and passwords of external components. +The backup files probably contain also this information, +so it is preferable to secure the whole /etc/ejabberd/ directory. +
    ejabberd service log: /var/log/ejabberd/ejabberd.log
    +Contains IP addresses of clients. +If the loglevel is set to 5, it contains whole conversations and passwords. +If a logrotate system is used, there may be several log files with similar information, +so it is preferable to secure the whole /var/log/ejabberd/ directory. +
    Mnesia database spool files in /var/lib/ejabberd/
    +The files store binary data, but some parts are still readable. +The files are generated by Mnesia and their permissions cannot be set directly, +so it is preferable to secure the whole /var/lib/ejabberd/ directory. +
    Erlang cookie file: /var/lib/ejabberd/.erlang.cookie
    +See section 5.3. +

    +

    Chapter 6  Clustering

    +

    +

    6.1  How it Works

    +

    A XMPP domain is served by one or more ejabberd nodes. These nodes can +be run on different machines that are connected via a network. They all +must have the ability to connect to port 4369 of all another nodes, and must +have the same magic cookie (see Erlang/OTP documentation, in other words the +file ~ejabberd/.erlang.cookie must be the same on all nodes). This is +needed because all nodes exchange information about connected users, s2s +connections, registered services, etc…

    Each ejabberd node has the following modules: +

    • +router, +
    • local router, +
    • session manager, +
    • s2s manager. +

    +

    6.1.1  Router

    +

    This module is the main router of XMPP packets on each node. It +routes them based on their destination’s domains. It uses a global +routing table. The domain of the packet’s destination is searched in the +routing table, and if it is found, the packet is routed to the +appropriate process. If not, it is sent to the s2s manager.

    +

    6.1.2  Local Router

    +

    This module routes packets which have a destination domain equal to +one of this server’s host names. If the destination JID has a non-empty user +part, it is routed to the session manager, otherwise it is processed depending +on its content.

    +

    6.1.3  Session Manager

    +

    This module routes packets to local users. It looks up to which user +resource a packet must be sent via a presence table. Then the packet is +either routed to the appropriate c2s process, or stored in offline +storage, or bounced back.

    +

    6.1.4  s2s Manager

    +

    This module routes packets to other XMPP servers. First, it +checks if an opened s2s connection from the domain of the packet’s +source to the domain of the packet’s destination exists. If that is the case, +the s2s manager routes the packet to the process +serving this connection, otherwise a new connection is opened.

    +

    6.2  Clustering Setup

    +

    Suppose you already configured ejabberd on one machine named (first), +and you need to setup another one to make an ejabberd cluster. Then do +following steps:

    1. +Copy ~ejabberd/.erlang.cookie file from first to +second.

      (alt) You can also add ‘-setcookie content_of_.erlang.cookie’ +option to all ‘erl’ commands below.

    2. On second run the following command as the ejabberd daemon user, +in the working directory of ejabberd:
      erl -sname ejabberd \
      +    -mnesia dir '"/var/lib/ejabberd/"' \
      +    -mnesia extra_db_nodes "['ejabberd@first']" \
      +    -s mnesia
      +

      This will start Mnesia serving the same database as ejabberd@first. +You can check this by running the command ‘mnesia:info().’. You +should see a lot of remote tables and a line like the following:

      Note: the Mnesia directory may be different in your system. +To know where does ejabberd expect Mnesia to be installed by default, +call 4.1 without options and it will show some help, +including the Mnesia database spool dir.

      running db nodes   = [ejabberd@first, ejabberd@second]
      +
    3. Now run the following in the same ‘erl’ session:
      mnesia:change_table_copy_type(schema, node(), disc_copies).
      +

      This will create local disc storage for the database.

      (alt) Change storage type of the scheme table to ‘RAM and disc +copy’ on the second node via the Web Admin.

    4. Now you can add replicas of various tables to this node with +‘mnesia:add_table_copy’ or +‘mnesia:change_table_copy_type’ as above (just replace +‘schema’ with another table name and ‘disc_copies’ +can be replaced with ‘ram_copies’ or +‘disc_only_copies’).

      Which tables to replicate is very dependant on your needs, you can get +some hints from the command ‘mnesia:info().’, by looking at the +size of tables and the default storage type for each table on ’first’.

      Replicating a table makes lookups in this table faster on this node. +Writing, on the other hand, will be slower. And of course if machine with one +of the replicas is down, other replicas will be used.

      Also section 5.3 (Table Fragmentation) of Mnesia User’s Guide can be helpful. +

      (alt) Same as in previous item, but for other tables.

    5. Run ‘init:stop().’ or just ‘q().’ to exit from +the Erlang shell. This probably can take some time if Mnesia has not yet +transfered and processed all data it needed from first.
    6. Now run ejabberd on second with a configuration similar as +on first: you probably do not need to duplicate ‘acl’ +and ‘access’ options because they will be taken from +first; and mod_irc should be +enabled only on one machine in the cluster. +

    You can repeat these steps for other machines supposed to serve this +domain.

    +

    6.3  Service Load-Balancing

    +

    +

    6.3.1  Components Load-Balancing

    +

    6.3.2  Domain Load-Balancing Algorithm

    +

    ejabberd includes an algorithm to load balance the components that are plugged on an ejabberd cluster. It means that you can plug one or several instances of the same component on each ejabberd cluster and that the traffic will be automatically distributed.

    The default distribution algorithm try to deliver to a local instance of a component. If several local instances are available, one instance is chosen randomly. If no instance is available locally, one instance is chosen randomly among the remote component instances.

    If you need a different behaviour, you can change the load balancing behaviour with the option domain_balancing. The syntax of the option is the following: +

    {domain_balancing, "component.example.com", BalancingCriteria}.

    Several balancing criteria are available: +

    • +destination: the full JID of the packet to attribute is used. +
    • source: the full JID of the packet from attribute is used. +
    • bare_destination: the bare JID (without resource) of the packet to attribute is used. +
    • bare_source: the bare JID (without resource) of the packet from attribute is used. +

    If the value corresponding to the criteria is the same, the same component instance in the cluster will be used.

    +

    6.3.3  Load-Balancing Buckets

    +

    When there is a risk of failure for a given component, domain balancing can cause service trouble. If one component is failing the service will not work correctly unless the sessions are rebalanced.

    In this case, it is best to limit the problem to the sessions handled by the failing component. This is what the domain_balancing_component_number option does, making the load balancing algorithm not dynamic, but sticky on a fix number of component instances.

    The syntax is: +

    {domain_balancing_component_number, "component.example.com", Number}.

    +

    Chapter 7  Debugging

    +

    +

    7.1  Log Files

    An ejabberd node writes two log files: +

    + ejabberd.log
    is the ejabberd service log, with the messages reported by ejabberd code +
    erlang.log
    is the Erlang/OTP system log, with the messages reported by Erlang/OTP using SASL (System Architecture Support Libraries) +

    The option loglevel modifies the verbosity of the file ejabberd.log. The syntax is: +

    {loglevel, Level}.

    The possible Level are: +

    + 0
    No ejabberd log at all (not recommended) +
    1
    Critical +
    2
    Error +
    3
    Warning +
    4
    Info +
    5
    Debug +

    +For example, the default configuration is: +

    {loglevel, 4}.
    +

    The log files grow continually, so it is recommended to rotate them periodically. +To rotate the log files, rename the files and then reopen them. +The ejabberdctl command reopen-log +(please refer to section 4.1.1) +reopens the log files, +and also renames the old ones if you didn’t rename them.

    +

    7.2  Debug Console

    The Debug Console is an Erlang shell attached to an already running ejabberd server. +With this Erlang shell, an experienced administrator can perform complex tasks.

    This shell gives complete control over the ejabberd server, +so it is important to use it with extremely care. +There are some simple and safe examples in the article +Interconnecting Erlang Nodes

    To exit the shell, close the window or press the keys: control+c control+c.

    +

    7.3  Watchdog Alerts

    +

    ejabberd includes a watchdog mechanism that may be useful to developers +when troubleshooting a problem related to memory usage. +If a process in the ejabberd server consumes more memory than the configured threshold, +a message is sent to the XMPP accounts defined with the option +watchdog_admins + in the ejabberd configuration file.

    The syntax is: +

    {watchdog_admins, [JID, ...]}.

    The memory consumed is measured in words: +a word on 32-bit architecture is 4 bytes, +and a word on 64-bit architecture is 8 bytes. +The threshold by default is 1000000 words. +This value can be configured with the option watchdog_large_heap, +or in a conversation with the watchdog alert bot.

    The syntax is: +

    {watchdog_large_heap, Number}.

    Example configuration: +

    {watchdog_admins, ["admin2@localhost", "admin2@example.org"]}.
    +{watchdog_large_heap, 30000000}.
    +

    To remove watchdog admins, remove them in the option. +To remove all watchdog admins, set the option with an empty list: +

    {watchdog_admins, []}.
    +

    +

    Appendix A  Internationalization and Localization

    +

    The source code of ejabberd supports localization. +The translators can edit the +gettext .po files +using any capable program (KBabel, Lokalize, Poedit...) or a simple text editor.

    Then gettext +is used to extract, update and export those .po files to the .msg format read by ejabberd. +To perform those management tasks, in the src/ directory execute make translations. +The translatable strings are extracted from source code to generate the file ejabberd.pot. +This file is merged with each .po file to produce updated .po files. +Finally those .po files are exported to .msg files, that have a format easily readable by ejabberd.

    All built-in modules support the xml:lang attribute inside IQ queries. +Figure A.1, for example, shows the reply to the following query: +

    <iq id='5'
    +    to='example.org'
    +    type='get'
    +    xml:lang='ru'>
    +  <query xmlns='http://jabber.org/protocol/disco#items'/>
    +</iq>
    +

    + +discorus.png + + +
    +
    Figure A.1: Service Discovery when xml:lang=’ru’
    + +

    The Web Admin also supports the Accept-Language HTTP header.


    + +webadmmainru.png + + +
    +
    Figure A.2: Web Admin showing a virtual host when the web browser provides the +HTTP header ‘Accept-Language: ru’
    + +

    +

    Appendix B  Release Notes

    +

    Release notes are available from ejabberd Home Page

    +

    Appendix C  Acknowledgements

    Thanks to all people who contributed to this guide: +

    +

    Appendix D  Copyright Information

    Ejabberd Installation and Operation Guide.
    +Copyright © 2003 — 2010 ProcessOne

    This document 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 document 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 document; if not, write to the Free Software Foundation, Inc., 51 Franklin +Street, Fifth Floor, Boston, MA 02110-1301, USA.

    + + + +
    This document was translated from LATEX by +HEVEA.
    + diff --git a/src/configure b/src/configure new file mode 100755 index 000000000..ff51ca020 --- /dev/null +++ b/src/configure @@ -0,0 +1,6310 @@ +#! /bin/sh +# Guess values for system-dependent variables and create Makefiles. +# Generated by GNU Autoconf 2.67 for ejabberd 2.1.x. +# +# Report bugs to . +# +# +# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, +# 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software +# Foundation, Inc. +# +# +# This configure script is free software; the Free Software Foundation +# gives unlimited permission to copy, distribute and modify it. +## -------------------- ## +## M4sh Initialization. ## +## -------------------- ## + +# Be more Bourne compatible +DUALCASE=1; export DUALCASE # for MKS sh +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; +esac +fi + + +as_nl=' +' +export as_nl +# Printing a long string crashes Solaris 7 /usr/bin/printf. +as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo +# Prefer a ksh shell builtin over an external printf program on Solaris, +# but without wasting forks for bash or zsh. +if test -z "$BASH_VERSION$ZSH_VERSION" \ + && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='print -r --' + as_echo_n='print -rn --' +elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='printf %s\n' + as_echo_n='printf %s' +else + if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then + as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' + as_echo_n='/usr/ucb/echo -n' + else + as_echo_body='eval expr "X$1" : "X\\(.*\\)"' + as_echo_n_body='eval + arg=$1; + case $arg in #( + *"$as_nl"*) + expr "X$arg" : "X\\(.*\\)$as_nl"; + arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; + esac; + expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" + ' + export as_echo_n_body + as_echo_n='sh -c $as_echo_n_body as_echo' + fi + export as_echo_body + as_echo='sh -c $as_echo_body as_echo' +fi + +# The user is always right. +if test "${PATH_SEPARATOR+set}" != set; then + PATH_SEPARATOR=: + (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { + (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || + PATH_SEPARATOR=';' + } +fi + + +# IFS +# We need space, tab and new line, in precisely that order. Quoting is +# there to prevent editors from complaining about space-tab. +# (If _AS_PATH_WALK were called with IFS unset, it would disable word +# splitting by setting IFS to empty value.) +IFS=" "" $as_nl" + +# Find who we are. Look in the path if we contain no directory separator. +case $0 in #(( + *[\\/]* ) as_myself=$0 ;; + *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break + done +IFS=$as_save_IFS + + ;; +esac +# We did not find ourselves, most probably we were run as `sh COMMAND' +# in which case we are not to be found in the path. +if test "x$as_myself" = x; then + as_myself=$0 +fi +if test ! -f "$as_myself"; then + $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + exit 1 +fi + +# Unset variables that we do not need and which cause bugs (e.g. in +# pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" +# suppresses any "Segmentation fault" message there. '((' could +# trigger a bug in pdksh 5.2.14. +for as_var in BASH_ENV ENV MAIL MAILPATH +do eval test x\${$as_var+set} = xset \ + && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : +done +PS1='$ ' +PS2='> ' +PS4='+ ' + +# NLS nuisances. +LC_ALL=C +export LC_ALL +LANGUAGE=C +export LANGUAGE + +# CDPATH. +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH + +if test "x$CONFIG_SHELL" = x; then + as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then : + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which + # is contrary to our usage. Disable this feature. + alias -g '\${1+\"\$@\"}'='\"\$@\"' + setopt NO_GLOB_SUBST +else + case \`(set -o) 2>/dev/null\` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; +esac +fi +" + as_required="as_fn_return () { (exit \$1); } +as_fn_success () { as_fn_return 0; } +as_fn_failure () { as_fn_return 1; } +as_fn_ret_success () { return 0; } +as_fn_ret_failure () { return 1; } + +exitcode=0 +as_fn_success || { exitcode=1; echo as_fn_success failed.; } +as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; } +as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; } +as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; } +if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then : + +else + exitcode=1; echo positional parameters were not saved. +fi +test x\$exitcode = x0 || exit 1" + as_suggested=" as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO + as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO + eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" && + test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1 +test \$(( 1 + 1 )) = 2 || exit 1" + if (eval "$as_required") 2>/dev/null; then : + as_have_required=yes +else + as_have_required=no +fi + if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then : + +else + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_found=false +for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + as_found=: + case $as_dir in #( + /*) + for as_base in sh bash ksh sh5; do + # Try only shells that exist, to save several forks. + as_shell=$as_dir/$as_base + if { test -f "$as_shell" || test -f "$as_shell.exe"; } && + { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then : + CONFIG_SHELL=$as_shell as_have_required=yes + if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then : + break 2 +fi +fi + done;; + esac + as_found=false +done +$as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } && + { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then : + CONFIG_SHELL=$SHELL as_have_required=yes +fi; } +IFS=$as_save_IFS + + + if test "x$CONFIG_SHELL" != x; then : + # We cannot yet assume a decent shell, so we have to provide a + # neutralization value for shells without unset; and this also + # works around shells that cannot unset nonexistent variables. + BASH_ENV=/dev/null + ENV=/dev/null + (unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV + export CONFIG_SHELL + exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"} +fi + + if test x$as_have_required = xno; then : + $as_echo "$0: This script requires a shell more modern than all" + $as_echo "$0: the shells that I found on your system." + if test x${ZSH_VERSION+set} = xset ; then + $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should" + $as_echo "$0: be upgraded to zsh 4.3.4 or later." + else + $as_echo "$0: Please tell bug-autoconf@gnu.org and +$0: ejabberd@process-one.net about your system, including +$0: any error possibly output before this message. Then +$0: install a modern shell, or manually run the script +$0: under such a shell if you do have one." + fi + exit 1 +fi +fi +fi +SHELL=${CONFIG_SHELL-/bin/sh} +export SHELL +# Unset more variables known to interfere with behavior of common tools. +CLICOLOR_FORCE= GREP_OPTIONS= +unset CLICOLOR_FORCE GREP_OPTIONS + +## --------------------- ## +## M4sh Shell Functions. ## +## --------------------- ## +# as_fn_unset VAR +# --------------- +# Portably unset VAR. +as_fn_unset () +{ + { eval $1=; unset $1;} +} +as_unset=as_fn_unset + +# as_fn_set_status STATUS +# ----------------------- +# Set $? to STATUS, without forking. +as_fn_set_status () +{ + return $1 +} # as_fn_set_status + +# as_fn_exit STATUS +# ----------------- +# Exit the shell with STATUS, even in a "trap 0" or "set -e" context. +as_fn_exit () +{ + set +e + as_fn_set_status $1 + exit $1 +} # as_fn_exit + +# as_fn_mkdir_p +# ------------- +# Create "$as_dir" as a directory, including parents if necessary. +as_fn_mkdir_p () +{ + + case $as_dir in #( + -*) as_dir=./$as_dir;; + esac + test -d "$as_dir" || eval $as_mkdir_p || { + as_dirs= + while :; do + case $as_dir in #( + *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( + *) as_qdir=$as_dir;; + esac + as_dirs="'$as_qdir' $as_dirs" + as_dir=`$as_dirname -- "$as_dir" || +$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_dir" : 'X\(//\)[^/]' \| \ + X"$as_dir" : 'X\(//\)$' \| \ + X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_dir" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + test -d "$as_dir" && break + done + test -z "$as_dirs" || eval "mkdir $as_dirs" + } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" + + +} # as_fn_mkdir_p +# as_fn_append VAR VALUE +# ---------------------- +# Append the text in VALUE to the end of the definition contained in VAR. Take +# advantage of any shell optimizations that allow amortized linear growth over +# repeated appends, instead of the typical quadratic growth present in naive +# implementations. +if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : + eval 'as_fn_append () + { + eval $1+=\$2 + }' +else + as_fn_append () + { + eval $1=\$$1\$2 + } +fi # as_fn_append + +# as_fn_arith ARG... +# ------------------ +# Perform arithmetic evaluation on the ARGs, and store the result in the +# global $as_val. Take advantage of shells that can avoid forks. The arguments +# must be portable across $(()) and expr. +if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : + eval 'as_fn_arith () + { + as_val=$(( $* )) + }' +else + as_fn_arith () + { + as_val=`expr "$@" || test $? -eq 1` + } +fi # as_fn_arith + + +# as_fn_error STATUS ERROR [LINENO LOG_FD] +# ---------------------------------------- +# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are +# provided, also output the error to LOG_FD, referencing LINENO. Then exit the +# script with STATUS, using 1 if that was 0. +as_fn_error () +{ + as_status=$1; test $as_status -eq 0 && as_status=1 + if test "$4"; then + as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 + fi + $as_echo "$as_me: error: $2" >&2 + as_fn_exit $as_status +} # as_fn_error + +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then + as_expr=expr +else + as_expr=false +fi + +if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then + as_basename=basename +else + as_basename=false +fi + +if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then + as_dirname=dirname +else + as_dirname=false +fi + +as_me=`$as_basename -- "$0" || +$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ + X"$0" : 'X\(//\)$' \| \ + X"$0" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X/"$0" | + sed '/^.*\/\([^/][^/]*\)\/*$/{ + s//\1/ + q + } + /^X\/\(\/\/\)$/{ + s//\1/ + q + } + /^X\/\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits + + + as_lineno_1=$LINENO as_lineno_1a=$LINENO + as_lineno_2=$LINENO as_lineno_2a=$LINENO + eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" && + test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || { + # Blame Lee E. McMahon (1931-1989) for sed's syntax. :-) + sed -n ' + p + /[$]LINENO/= + ' <$as_myself | + sed ' + s/[$]LINENO.*/&-/ + t lineno + b + :lineno + N + :loop + s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ + t loop + s/-\n.*// + ' >$as_me.lineno && + chmod +x "$as_me.lineno" || + { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; } + + # Don't try to exec as it changes $[0], causing all sort of problems + # (the dirname of $[0] is not the place where we might find the + # original and so on. Autoconf is especially sensitive to this). + . "./$as_me.lineno" + # Exit status is that of the last command. + exit +} + +ECHO_C= ECHO_N= ECHO_T= +case `echo -n x` in #((((( +-n*) + case `echo 'xy\c'` in + *c*) ECHO_T=' ';; # ECHO_T is single tab character. + xy) ECHO_C='\c';; + *) echo `echo ksh88 bug on AIX 6.1` > /dev/null + ECHO_T=' ';; + esac;; +*) + ECHO_N='-n';; +esac + +rm -f conf$$ conf$$.exe conf$$.file +if test -d conf$$.dir; then + rm -f conf$$.dir/conf$$.file +else + rm -f conf$$.dir + mkdir conf$$.dir 2>/dev/null +fi +if (echo >conf$$.file) 2>/dev/null; then + if ln -s conf$$.file conf$$ 2>/dev/null; then + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -p'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || + as_ln_s='cp -p' + elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln + else + as_ln_s='cp -p' + fi +else + as_ln_s='cp -p' +fi +rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file +rmdir conf$$.dir 2>/dev/null + +if mkdir -p . 2>/dev/null; then + as_mkdir_p='mkdir -p "$as_dir"' +else + test -d ./-p && rmdir ./-p + as_mkdir_p=false +fi + +if test -x / >/dev/null 2>&1; then + as_test_x='test -x' +else + if ls -dL / >/dev/null 2>&1; then + as_ls_L_option=L + else + as_ls_L_option= + fi + as_test_x=' + eval sh -c '\'' + if test -d "$1"; then + test -d "$1/."; + else + case $1 in #( + -*)set "./$1";; + esac; + case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in #(( + ???[sx]*):;;*)false;;esac;fi + '\'' sh + ' +fi +as_executable_p=$as_test_x + +# Sed expression to map a string onto a valid CPP name. +as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" + +# Sed expression to map a string onto a valid variable name. +as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" + + +test -n "$DJDIR" || exec 7<&0 &1 + +# Name of the host. +# hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status, +# so uname gets run too. +ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q` + +# +# Initializations. +# +ac_default_prefix=/usr/local +ac_clean_files= +ac_config_libobj_dir=. +LIBOBJS= +cross_compiling=no +subdirs= +MFLAGS= +MAKEFLAGS= + +# Identity of this package. +PACKAGE_NAME='ejabberd' +PACKAGE_TARNAME='ejabberd' +PACKAGE_VERSION='2.1.x' +PACKAGE_STRING='ejabberd 2.1.x' +PACKAGE_BUGREPORT='ejabberd@process-one.net' +PACKAGE_URL='' + +# Factoring default headers for most tests. +ac_includes_default="\ +#include +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_SYS_STAT_H +# include +#endif +#ifdef STDC_HEADERS +# include +# include +#else +# ifdef HAVE_STDLIB_H +# include +# endif +#endif +#ifdef HAVE_STRING_H +# if !defined STDC_HEADERS && defined HAVE_MEMORY_H +# include +# endif +# include +#endif +#ifdef HAVE_STRINGS_H +# include +#endif +#ifdef HAVE_INTTYPES_H +# include +#endif +#ifdef HAVE_STDINT_H +# include +#endif +#ifdef HAVE_UNISTD_H +# include +#endif" + +ac_default_prefix=/ +ac_subst_vars='LTLIBOBJS +ERLCFLAGS +target_os +target_vendor +target_cpu +target +host_os +host_vendor +host_cpu +host +build_os +build_vendor +build_cpu +build +md2 +INSTALLUSER +SSL_CFLAGS +SSL_LIBS +nif +full_xml +transient_supervisors +db_type +flash_hack +roster_gateway_workaround +hipe +PAM_LIBS +PAM_CFLAGS +make_pam +pam +ZLIB_LIBS +ZLIB_CFLAGS +make_ejabberd_zlib +ejabberd_zlib +make_web +web +make_tls +tls +make_odbc +odbc +make_eldap +eldap +make_mod_pubsub +mod_pubsub +make_mod_proxy65 +mod_proxy65 +make_mod_muc +mod_muc +make_mod_irc +mod_irc +LIBOBJS +EXPAT_LIBS +EXPAT_CFLAGS +EGREP +GREP +CPP +LIBICONV +ERLANG_SSLVER +ERLANG_LIBS +ERLANG_CFLAGS +ERL +ERLC +SET_MAKE +OBJEXT +EXEEXT +ac_ct_CC +CPPFLAGS +LDFLAGS +CFLAGS +CC +target_alias +host_alias +build_alias +LIBS +ECHO_T +ECHO_N +ECHO_C +DEFS +mandir +localedir +libdir +psdir +pdfdir +dvidir +htmldir +infodir +docdir +oldincludedir +includedir +localstatedir +sharedstatedir +sysconfdir +datadir +datarootdir +libexecdir +sbindir +bindir +program_transform_name +prefix +exec_prefix +PACKAGE_URL +PACKAGE_BUGREPORT +PACKAGE_STRING +PACKAGE_VERSION +PACKAGE_TARNAME +PACKAGE_NAME +PATH_SEPARATOR +SHELL' +ac_subst_files='' +ac_user_opts=' +enable_option_checking +with_erlang +with_libiconv_prefix +with_expat +enable_mod_irc +enable_mod_muc +enable_mod_proxy65 +enable_mod_pubsub +enable_eldap +enable_odbc +enable_tls +enable_web +enable_ejabberd_zlib +with_zlib +enable_pam +with_pam +enable_hipe +enable_roster_gateway_workaround +enable_flash_hack +enable_mssql +enable_transient_supervisors +enable_full_xml +enable_nif +with_openssl +enable_user +' + ac_precious_vars='build_alias +host_alias +target_alias +CC +CFLAGS +LDFLAGS +LIBS +CPPFLAGS +CPP +ERLC +ERLCFLAGS' + + +# Initialize some variables set by options. +ac_init_help= +ac_init_version=false +ac_unrecognized_opts= +ac_unrecognized_sep= +# The variables have the same names as the options, with +# dashes changed to underlines. +cache_file=/dev/null +exec_prefix=NONE +no_create= +no_recursion= +prefix=NONE +program_prefix=NONE +program_suffix=NONE +program_transform_name=s,x,x, +silent= +site= +srcdir= +verbose= +x_includes=NONE +x_libraries=NONE + +# Installation directory options. +# These are left unexpanded so users can "make install exec_prefix=/foo" +# and all the variables that are supposed to be based on exec_prefix +# by default will actually change. +# Use braces instead of parens because sh, perl, etc. also accept them. +# (The list follows the same order as the GNU Coding Standards.) +bindir='${exec_prefix}/bin' +sbindir='${exec_prefix}/sbin' +libexecdir='${exec_prefix}/libexec' +datarootdir='${prefix}/share' +datadir='${datarootdir}' +sysconfdir='${prefix}/etc' +sharedstatedir='${prefix}/com' +localstatedir='${prefix}/var' +includedir='${prefix}/include' +oldincludedir='/usr/include' +docdir='${datarootdir}/doc/${PACKAGE_TARNAME}' +infodir='${datarootdir}/info' +htmldir='${docdir}' +dvidir='${docdir}' +pdfdir='${docdir}' +psdir='${docdir}' +libdir='${exec_prefix}/lib' +localedir='${datarootdir}/locale' +mandir='${datarootdir}/man' + +ac_prev= +ac_dashdash= +for ac_option +do + # If the previous option needs an argument, assign it. + if test -n "$ac_prev"; then + eval $ac_prev=\$ac_option + ac_prev= + continue + fi + + case $ac_option in + *=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;; + *=) ac_optarg= ;; + *) ac_optarg=yes ;; + esac + + # Accept the important Cygnus configure options, so we can diagnose typos. + + case $ac_dashdash$ac_option in + --) + ac_dashdash=yes ;; + + -bindir | --bindir | --bindi | --bind | --bin | --bi) + ac_prev=bindir ;; + -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*) + bindir=$ac_optarg ;; + + -build | --build | --buil | --bui | --bu) + ac_prev=build_alias ;; + -build=* | --build=* | --buil=* | --bui=* | --bu=*) + build_alias=$ac_optarg ;; + + -cache-file | --cache-file | --cache-fil | --cache-fi \ + | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c) + ac_prev=cache_file ;; + -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \ + | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*) + cache_file=$ac_optarg ;; + + --config-cache | -C) + cache_file=config.cache ;; + + -datadir | --datadir | --datadi | --datad) + ac_prev=datadir ;; + -datadir=* | --datadir=* | --datadi=* | --datad=*) + datadir=$ac_optarg ;; + + -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \ + | --dataroo | --dataro | --datar) + ac_prev=datarootdir ;; + -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \ + | --dataroot=* | --dataroo=* | --dataro=* | --datar=*) + datarootdir=$ac_optarg ;; + + -disable-* | --disable-*) + ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid feature name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"enable_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval enable_$ac_useropt=no ;; + + -docdir | --docdir | --docdi | --doc | --do) + ac_prev=docdir ;; + -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*) + docdir=$ac_optarg ;; + + -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv) + ac_prev=dvidir ;; + -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*) + dvidir=$ac_optarg ;; + + -enable-* | --enable-*) + ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid feature name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"enable_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval enable_$ac_useropt=\$ac_optarg ;; + + -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ + | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ + | --exec | --exe | --ex) + ac_prev=exec_prefix ;; + -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \ + | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \ + | --exec=* | --exe=* | --ex=*) + exec_prefix=$ac_optarg ;; + + -gas | --gas | --ga | --g) + # Obsolete; use --with-gas. + with_gas=yes ;; + + -help | --help | --hel | --he | -h) + ac_init_help=long ;; + -help=r* | --help=r* | --hel=r* | --he=r* | -hr*) + ac_init_help=recursive ;; + -help=s* | --help=s* | --hel=s* | --he=s* | -hs*) + ac_init_help=short ;; + + -host | --host | --hos | --ho) + ac_prev=host_alias ;; + -host=* | --host=* | --hos=* | --ho=*) + host_alias=$ac_optarg ;; + + -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht) + ac_prev=htmldir ;; + -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \ + | --ht=*) + htmldir=$ac_optarg ;; + + -includedir | --includedir | --includedi | --included | --include \ + | --includ | --inclu | --incl | --inc) + ac_prev=includedir ;; + -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \ + | --includ=* | --inclu=* | --incl=* | --inc=*) + includedir=$ac_optarg ;; + + -infodir | --infodir | --infodi | --infod | --info | --inf) + ac_prev=infodir ;; + -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*) + infodir=$ac_optarg ;; + + -libdir | --libdir | --libdi | --libd) + ac_prev=libdir ;; + -libdir=* | --libdir=* | --libdi=* | --libd=*) + libdir=$ac_optarg ;; + + -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \ + | --libexe | --libex | --libe) + ac_prev=libexecdir ;; + -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \ + | --libexe=* | --libex=* | --libe=*) + libexecdir=$ac_optarg ;; + + -localedir | --localedir | --localedi | --localed | --locale) + ac_prev=localedir ;; + -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*) + localedir=$ac_optarg ;; + + -localstatedir | --localstatedir | --localstatedi | --localstated \ + | --localstate | --localstat | --localsta | --localst | --locals) + ac_prev=localstatedir ;; + -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \ + | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*) + localstatedir=$ac_optarg ;; + + -mandir | --mandir | --mandi | --mand | --man | --ma | --m) + ac_prev=mandir ;; + -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*) + mandir=$ac_optarg ;; + + -nfp | --nfp | --nf) + # Obsolete; use --without-fp. + with_fp=no ;; + + -no-create | --no-create | --no-creat | --no-crea | --no-cre \ + | --no-cr | --no-c | -n) + no_create=yes ;; + + -no-recursion | --no-recursion | --no-recursio | --no-recursi \ + | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) + no_recursion=yes ;; + + -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \ + | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \ + | --oldin | --oldi | --old | --ol | --o) + ac_prev=oldincludedir ;; + -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \ + | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \ + | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*) + oldincludedir=$ac_optarg ;; + + -prefix | --prefix | --prefi | --pref | --pre | --pr | --p) + ac_prev=prefix ;; + -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*) + prefix=$ac_optarg ;; + + -program-prefix | --program-prefix | --program-prefi | --program-pref \ + | --program-pre | --program-pr | --program-p) + ac_prev=program_prefix ;; + -program-prefix=* | --program-prefix=* | --program-prefi=* \ + | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*) + program_prefix=$ac_optarg ;; + + -program-suffix | --program-suffix | --program-suffi | --program-suff \ + | --program-suf | --program-su | --program-s) + ac_prev=program_suffix ;; + -program-suffix=* | --program-suffix=* | --program-suffi=* \ + | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*) + program_suffix=$ac_optarg ;; + + -program-transform-name | --program-transform-name \ + | --program-transform-nam | --program-transform-na \ + | --program-transform-n | --program-transform- \ + | --program-transform | --program-transfor \ + | --program-transfo | --program-transf \ + | --program-trans | --program-tran \ + | --progr-tra | --program-tr | --program-t) + ac_prev=program_transform_name ;; + -program-transform-name=* | --program-transform-name=* \ + | --program-transform-nam=* | --program-transform-na=* \ + | --program-transform-n=* | --program-transform-=* \ + | --program-transform=* | --program-transfor=* \ + | --program-transfo=* | --program-transf=* \ + | --program-trans=* | --program-tran=* \ + | --progr-tra=* | --program-tr=* | --program-t=*) + program_transform_name=$ac_optarg ;; + + -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd) + ac_prev=pdfdir ;; + -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*) + pdfdir=$ac_optarg ;; + + -psdir | --psdir | --psdi | --psd | --ps) + ac_prev=psdir ;; + -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*) + psdir=$ac_optarg ;; + + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil) + silent=yes ;; + + -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) + ac_prev=sbindir ;; + -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ + | --sbi=* | --sb=*) + sbindir=$ac_optarg ;; + + -sharedstatedir | --sharedstatedir | --sharedstatedi \ + | --sharedstated | --sharedstate | --sharedstat | --sharedsta \ + | --sharedst | --shareds | --shared | --share | --shar \ + | --sha | --sh) + ac_prev=sharedstatedir ;; + -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \ + | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \ + | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \ + | --sha=* | --sh=*) + sharedstatedir=$ac_optarg ;; + + -site | --site | --sit) + ac_prev=site ;; + -site=* | --site=* | --sit=*) + site=$ac_optarg ;; + + -srcdir | --srcdir | --srcdi | --srcd | --src | --sr) + ac_prev=srcdir ;; + -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*) + srcdir=$ac_optarg ;; + + -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \ + | --syscon | --sysco | --sysc | --sys | --sy) + ac_prev=sysconfdir ;; + -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \ + | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*) + sysconfdir=$ac_optarg ;; + + -target | --target | --targe | --targ | --tar | --ta | --t) + ac_prev=target_alias ;; + -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*) + target_alias=$ac_optarg ;; + + -v | -verbose | --verbose | --verbos | --verbo | --verb) + verbose=yes ;; + + -version | --version | --versio | --versi | --vers | -V) + ac_init_version=: ;; + + -with-* | --with-*) + ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid package name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"with_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval with_$ac_useropt=\$ac_optarg ;; + + -without-* | --without-*) + ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid package name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"with_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval with_$ac_useropt=no ;; + + --x) + # Obsolete; use --with-x. + with_x=yes ;; + + -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \ + | --x-incl | --x-inc | --x-in | --x-i) + ac_prev=x_includes ;; + -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \ + | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*) + x_includes=$ac_optarg ;; + + -x-libraries | --x-libraries | --x-librarie | --x-librari \ + | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l) + ac_prev=x_libraries ;; + -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \ + | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) + x_libraries=$ac_optarg ;; + + -*) as_fn_error $? "unrecognized option: \`$ac_option' +Try \`$0 --help' for more information" + ;; + + *=*) + ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` + # Reject names that are not valid shell variable names. + case $ac_envvar in #( + '' | [0-9]* | *[!_$as_cr_alnum]* ) + as_fn_error $? "invalid variable name: \`$ac_envvar'" ;; + esac + eval $ac_envvar=\$ac_optarg + export $ac_envvar ;; + + *) + # FIXME: should be removed in autoconf 3.0. + $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2 + expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && + $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2 + : ${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option} + ;; + + esac +done + +if test -n "$ac_prev"; then + ac_option=--`echo $ac_prev | sed 's/_/-/g'` + as_fn_error $? "missing argument to $ac_option" +fi + +if test -n "$ac_unrecognized_opts"; then + case $enable_option_checking in + no) ;; + fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;; + *) $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;; + esac +fi + +# Check all directory arguments for consistency. +for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ + datadir sysconfdir sharedstatedir localstatedir includedir \ + oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ + libdir localedir mandir +do + eval ac_val=\$$ac_var + # Remove trailing slashes. + case $ac_val in + */ ) + ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'` + eval $ac_var=\$ac_val;; + esac + # Be sure to have absolute directory names. + case $ac_val in + [\\/$]* | ?:[\\/]* ) continue;; + NONE | '' ) case $ac_var in *prefix ) continue;; esac;; + esac + as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val" +done + +# There might be people who depend on the old broken behavior: `$host' +# used to hold the argument of --host etc. +# FIXME: To remove some day. +build=$build_alias +host=$host_alias +target=$target_alias + +# FIXME: To remove some day. +if test "x$host_alias" != x; then + if test "x$build_alias" = x; then + cross_compiling=maybe + $as_echo "$as_me: WARNING: if you wanted to set the --build type, don't use --host. + If a cross compiler is detected then cross compile mode will be used" >&2 + elif test "x$build_alias" != "x$host_alias"; then + cross_compiling=yes + fi +fi + +ac_tool_prefix= +test -n "$host_alias" && ac_tool_prefix=$host_alias- + +test "$silent" = yes && exec 6>/dev/null + + +ac_pwd=`pwd` && test -n "$ac_pwd" && +ac_ls_di=`ls -di .` && +ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || + as_fn_error $? "working directory cannot be determined" +test "X$ac_ls_di" = "X$ac_pwd_ls_di" || + as_fn_error $? "pwd does not report name of working directory" + + +# Find the source files, if location was not specified. +if test -z "$srcdir"; then + ac_srcdir_defaulted=yes + # Try the directory containing this script, then the parent directory. + ac_confdir=`$as_dirname -- "$as_myself" || +$as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_myself" : 'X\(//\)[^/]' \| \ + X"$as_myself" : 'X\(//\)$' \| \ + X"$as_myself" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_myself" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + srcdir=$ac_confdir + if test ! -r "$srcdir/$ac_unique_file"; then + srcdir=.. + fi +else + ac_srcdir_defaulted=no +fi +if test ! -r "$srcdir/$ac_unique_file"; then + test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." + as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir" +fi +ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" +ac_abs_confdir=`( + cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg" + pwd)` +# When building in place, set srcdir=. +if test "$ac_abs_confdir" = "$ac_pwd"; then + srcdir=. +fi +# Remove unnecessary trailing slashes from srcdir. +# Double slashes in file names in object file debugging info +# mess up M-x gdb in Emacs. +case $srcdir in +*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;; +esac +for ac_var in $ac_precious_vars; do + eval ac_env_${ac_var}_set=\${${ac_var}+set} + eval ac_env_${ac_var}_value=\$${ac_var} + eval ac_cv_env_${ac_var}_set=\${${ac_var}+set} + eval ac_cv_env_${ac_var}_value=\$${ac_var} +done + +# +# Report the --help message. +# +if test "$ac_init_help" = "long"; then + # Omit some internal or obsolete options to make the list less imposing. + # This message is too long to be a string in the A/UX 3.1 sh. + cat <<_ACEOF +\`configure' configures ejabberd 2.1.x to adapt to many kinds of systems. + +Usage: $0 [OPTION]... [VAR=VALUE]... + +To assign environment variables (e.g., CC, CFLAGS...), specify them as +VAR=VALUE. See below for descriptions of some of the useful variables. + +Defaults for the options are specified in brackets. + +Configuration: + -h, --help display this help and exit + --help=short display options specific to this package + --help=recursive display the short help of all the included packages + -V, --version display version information and exit + -q, --quiet, --silent do not print \`checking ...' messages + --cache-file=FILE cache test results in FILE [disabled] + -C, --config-cache alias for \`--cache-file=config.cache' + -n, --no-create do not create output files + --srcdir=DIR find the sources in DIR [configure dir or \`..'] + +Installation directories: + --prefix=PREFIX install architecture-independent files in PREFIX + [$ac_default_prefix] + --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX + [PREFIX] + +By default, \`make install' will install all the files in +\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify +an installation prefix other than \`$ac_default_prefix' using \`--prefix', +for instance \`--prefix=\$HOME'. + +For better control, use the options below. + +Fine tuning of the installation directories: + --bindir=DIR user executables [EPREFIX/bin] + --sbindir=DIR system admin executables [EPREFIX/sbin] + --libexecdir=DIR program executables [EPREFIX/libexec] + --sysconfdir=DIR read-only single-machine data [PREFIX/etc] + --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] + --localstatedir=DIR modifiable single-machine data [PREFIX/var] + --libdir=DIR object code libraries [EPREFIX/lib] + --includedir=DIR C header files [PREFIX/include] + --oldincludedir=DIR C header files for non-gcc [/usr/include] + --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] + --datadir=DIR read-only architecture-independent data [DATAROOTDIR] + --infodir=DIR info documentation [DATAROOTDIR/info] + --localedir=DIR locale-dependent data [DATAROOTDIR/locale] + --mandir=DIR man documentation [DATAROOTDIR/man] + --docdir=DIR documentation root [DATAROOTDIR/doc/ejabberd] + --htmldir=DIR html documentation [DOCDIR] + --dvidir=DIR dvi documentation [DOCDIR] + --pdfdir=DIR pdf documentation [DOCDIR] + --psdir=DIR ps documentation [DOCDIR] +_ACEOF + + cat <<\_ACEOF + +System types: + --build=BUILD configure for building on BUILD [guessed] + --host=HOST cross-compile to build programs to run on HOST [BUILD] + --target=TARGET configure for building compilers for TARGET [HOST] +_ACEOF +fi + +if test -n "$ac_init_help"; then + case $ac_init_help in + short | recursive ) echo "Configuration of ejabberd 2.1.x:";; + esac + cat <<\_ACEOF + +Optional Features: + --disable-option-checking ignore unrecognized --enable/--with options + --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) + --enable-FEATURE[=ARG] include FEATURE [ARG=yes] + --enable-mod_irc enable mod_irc (default: yes) + --enable-mod_muc enable mod_muc (default: yes) + --enable-mod_proxy65 enable mod_proxy65 (default: yes) + --enable-mod_pubsub enable mod_pubsub (default: yes) + --enable-eldap enable eldap (default: yes) + --enable-odbc enable odbc (default: no) + --enable-tls enable tls (default: yes) + --enable-web enable web (default: yes) + --enable-ejabberd_zlib enable ejabberd_zlib (default: yes) + --enable-pam enable pam (default: no) + --enable-hipe compile natively with HiPE, not recommended + (default: no) + --enable-roster-gateway-workaround + turn on workaround for processing gateway + subscriptions (default: no) + --enable-flash-hack support Adobe Flash client XML (default: no) + --enable-mssql use Microsoft SQL Server database (default: no, + requires --enable-odbc) + --enable-transient_supervisors + use Erlang supervision for transient process + (default: yes) + --enable-full-xml use XML features in XMPP stream (ex: CDATA) + (default: no, requires XML compliant clients) + --enable-nif replace some functions with C equivalents. Requires + Erlang R13B04 or higher (default: no) + --enable-user[[[=USER]]] + allow this system user to start ejabberd (default: + no) + +Optional Packages: + --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] + --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no) + --with-erlang=PREFIX path to erlc and erl + --with-libiconv-prefix=PREFIX + prefix where libiconv is installed + --with-expat=PREFIX prefix where EXPAT is installed + --with-zlib=PREFIX prefix where zlib is installed + --with-pam=PREFIX prefix where PAM is installed + --with-openssl=PREFIX prefix where OPENSSL is installed + +Some influential environment variables: + CC C compiler command + CFLAGS C compiler flags + LDFLAGS linker flags, e.g. -L if you have libraries in a + nonstandard directory + LIBS libraries to pass to the linker, e.g. -l + CPPFLAGS (Objective) C/C++ preprocessor flags, e.g. -I if + you have headers in a nonstandard directory + CPP C preprocessor + ERLC Erlang/OTP compiler command [autodetected] + ERLCFLAGS Erlang/OTP compiler flags [none] + +Use these variables to override the choices made by `configure' or to help +it to find libraries and programs with nonstandard names/locations. + +Report bugs to . +_ACEOF +ac_status=$? +fi + +if test "$ac_init_help" = "recursive"; then + # If there are subdirs, report their specific --help. + for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue + test -d "$ac_dir" || + { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } || + continue + ac_builddir=. + +case "$ac_dir" in +.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; +*) + ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` + # A ".." for each directory in $ac_dir_suffix. + ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` + case $ac_top_builddir_sub in + "") ac_top_builddir_sub=. ac_top_build_prefix= ;; + *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; + esac ;; +esac +ac_abs_top_builddir=$ac_pwd +ac_abs_builddir=$ac_pwd$ac_dir_suffix +# for backward compatibility: +ac_top_builddir=$ac_top_build_prefix + +case $srcdir in + .) # We are building in place. + ac_srcdir=. + ac_top_srcdir=$ac_top_builddir_sub + ac_abs_top_srcdir=$ac_pwd ;; + [\\/]* | ?:[\\/]* ) # Absolute name. + ac_srcdir=$srcdir$ac_dir_suffix; + ac_top_srcdir=$srcdir + ac_abs_top_srcdir=$srcdir ;; + *) # Relative name. + ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix + ac_top_srcdir=$ac_top_build_prefix$srcdir + ac_abs_top_srcdir=$ac_pwd/$srcdir ;; +esac +ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix + + cd "$ac_dir" || { ac_status=$?; continue; } + # Check for guested configure. + if test -f "$ac_srcdir/configure.gnu"; then + echo && + $SHELL "$ac_srcdir/configure.gnu" --help=recursive + elif test -f "$ac_srcdir/configure"; then + echo && + $SHELL "$ac_srcdir/configure" --help=recursive + else + $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 + fi || ac_status=$? + cd "$ac_pwd" || { ac_status=$?; break; } + done +fi + +test -n "$ac_init_help" && exit $ac_status +if $ac_init_version; then + cat <<\_ACEOF +ejabberd configure 2.1.x +generated by GNU Autoconf 2.67 + +Copyright (C) 2010 Free Software Foundation, Inc. +This configure script is free software; the Free Software Foundation +gives unlimited permission to copy, distribute and modify it. +_ACEOF + exit +fi + +## ------------------------ ## +## Autoconf initialization. ## +## ------------------------ ## + +# ac_fn_c_try_compile LINENO +# -------------------------- +# Try to compile conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_compile () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + rm -f conftest.$ac_objext + if { { ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_compile") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then : + ac_retval=0 +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=1 +fi + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + as_fn_set_status $ac_retval + +} # ac_fn_c_try_compile + +# ac_fn_c_try_link LINENO +# ----------------------- +# Try to link conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_link () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + rm -f conftest.$ac_objext conftest$ac_exeext + if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + $as_test_x conftest$ac_exeext + }; then : + ac_retval=0 +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=1 +fi + # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information + # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would + # interfere with the next link command; also delete a directory that is + # left behind by Apple's compiler. We do this before executing the actions. + rm -rf conftest.dSYM conftest_ipa8_conftest.oo + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + as_fn_set_status $ac_retval + +} # ac_fn_c_try_link + +# ac_fn_c_try_cpp LINENO +# ---------------------- +# Try to preprocess conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_cpp () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if { { ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } > conftest.i && { + test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + test ! -s conftest.err + }; then : + ac_retval=0 +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=1 +fi + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + as_fn_set_status $ac_retval + +} # ac_fn_c_try_cpp + +# ac_fn_c_check_header_mongrel LINENO HEADER VAR INCLUDES +# ------------------------------------------------------- +# Tests whether HEADER exists, giving a warning if it cannot be compiled using +# the include files in INCLUDES and setting the cache variable VAR +# accordingly. +ac_fn_c_check_header_mongrel () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if eval "test \"\${$3+set}\"" = set; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if eval "test \"\${$3+set}\"" = set; then : + $as_echo_n "(cached) " >&6 +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +else + # Is the header compilable? +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5 +$as_echo_n "checking $2 usability... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +#include <$2> +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_header_compiler=yes +else + ac_header_compiler=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5 +$as_echo "$ac_header_compiler" >&6; } + +# Is the header present? +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5 +$as_echo_n "checking $2 presence... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include <$2> +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + ac_header_preproc=yes +else + ac_header_preproc=no +fi +rm -f conftest.err conftest.i conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5 +$as_echo "$ac_header_preproc" >&6; } + +# So? What about this header? +case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in #(( + yes:no: ) + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&5 +$as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} + ;; + no:yes:* ) + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cannot be compiled" >&5 +$as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: check for missing prerequisite headers?" >&5 +$as_echo "$as_me: WARNING: $2: check for missing prerequisite headers?" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf documentation" >&5 +$as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&5 +$as_echo "$as_me: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} +( $as_echo "## --------------------------------------- ## +## Report this to ejabberd@process-one.net ## +## --------------------------------------- ##" + ) | sed "s/^/$as_me: WARNING: /" >&2 + ;; +esac + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if eval "test \"\${$3+set}\"" = set; then : + $as_echo_n "(cached) " >&6 +else + eval "$3=\$ac_header_compiler" +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +fi + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + +} # ac_fn_c_check_header_mongrel + +# ac_fn_c_try_run LINENO +# ---------------------- +# Try to link conftest.$ac_ext, and return whether this succeeded. Assumes +# that executables *can* be run. +ac_fn_c_try_run () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { ac_try='./conftest$ac_exeext' + { { case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; }; then : + ac_retval=0 +else + $as_echo "$as_me: program exited with status $ac_status" >&5 + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=$ac_status +fi + rm -rf conftest.dSYM conftest_ipa8_conftest.oo + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + as_fn_set_status $ac_retval + +} # ac_fn_c_try_run + +# ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES +# ------------------------------------------------------- +# Tests whether HEADER exists and can be compiled using the include files in +# INCLUDES, setting the cache variable VAR accordingly. +ac_fn_c_check_header_compile () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if eval "test \"\${$3+set}\"" = set; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +#include <$2> +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + eval "$3=yes" +else + eval "$3=no" +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + +} # ac_fn_c_check_header_compile + +# ac_fn_erl_try_run LINENO +# ------------------------ +# Try to link conftest.$ac_ext, and return whether this succeeded. Assumes +# that executables *can* be run. +ac_fn_erl_try_run () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { ac_try='./conftest$ac_exeext' + { { case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; }; then : + ac_retval=0 +else + $as_echo "$as_me: program exited with status $ac_status" >&5 + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=$ac_status +fi + rm -rf conftest.dSYM conftest_ipa8_conftest.oo + eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + as_fn_set_status $ac_retval + +} # ac_fn_erl_try_run +cat >config.log <<_ACEOF +This file contains any messages produced by compilers while +running configure, to aid debugging if configure makes a mistake. + +It was created by ejabberd $as_me 2.1.x, which was +generated by GNU Autoconf 2.67. Invocation command line was + + $ $0 $@ + +_ACEOF +exec 5>>config.log +{ +cat <<_ASUNAME +## --------- ## +## Platform. ## +## --------- ## + +hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` +uname -m = `(uname -m) 2>/dev/null || echo unknown` +uname -r = `(uname -r) 2>/dev/null || echo unknown` +uname -s = `(uname -s) 2>/dev/null || echo unknown` +uname -v = `(uname -v) 2>/dev/null || echo unknown` + +/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` +/bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` + +/bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` +/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` +/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` +/usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` +/bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` +/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` +/bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` + +_ASUNAME + +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + $as_echo "PATH: $as_dir" + done +IFS=$as_save_IFS + +} >&5 + +cat >&5 <<_ACEOF + + +## ----------- ## +## Core tests. ## +## ----------- ## + +_ACEOF + + +# Keep a trace of the command line. +# Strip out --no-create and --no-recursion so they do not pile up. +# Strip out --silent because we don't want to record it for future runs. +# Also quote any args containing shell meta-characters. +# Make two passes to allow for proper duplicate-argument suppression. +ac_configure_args= +ac_configure_args0= +ac_configure_args1= +ac_must_keep_next=false +for ac_pass in 1 2 +do + for ac_arg + do + case $ac_arg in + -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil) + continue ;; + *\'*) + ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + case $ac_pass in + 1) as_fn_append ac_configure_args0 " '$ac_arg'" ;; + 2) + as_fn_append ac_configure_args1 " '$ac_arg'" + if test $ac_must_keep_next = true; then + ac_must_keep_next=false # Got value, back to normal. + else + case $ac_arg in + *=* | --config-cache | -C | -disable-* | --disable-* \ + | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ + | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ + | -with-* | --with-* | -without-* | --without-* | --x) + case "$ac_configure_args0 " in + "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; + esac + ;; + -* ) ac_must_keep_next=true ;; + esac + fi + as_fn_append ac_configure_args " '$ac_arg'" + ;; + esac + done +done +{ ac_configure_args0=; unset ac_configure_args0;} +{ ac_configure_args1=; unset ac_configure_args1;} + +# When interrupted or exit'd, cleanup temporary files, and complete +# config.log. We remove comments because anyway the quotes in there +# would cause problems or look ugly. +# WARNING: Use '\'' to represent an apostrophe within the trap. +# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. +trap 'exit_status=$? + # Save into config.log some information that might help in debugging. + { + echo + + $as_echo "## ---------------- ## +## Cache variables. ## +## ---------------- ##" + echo + # The following way of writing the cache mishandles newlines in values, +( + for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do + eval ac_val=\$$ac_var + case $ac_val in #( + *${as_nl}*) + case $ac_var in #( + *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 +$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; + esac + case $ac_var in #( + _ | IFS | as_nl) ;; #( + BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( + *) { eval $ac_var=; unset $ac_var;} ;; + esac ;; + esac + done + (set) 2>&1 | + case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( + *${as_nl}ac_space=\ *) + sed -n \ + "s/'\''/'\''\\\\'\'''\''/g; + s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" + ;; #( + *) + sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" + ;; + esac | + sort +) + echo + + $as_echo "## ----------------- ## +## Output variables. ## +## ----------------- ##" + echo + for ac_var in $ac_subst_vars + do + eval ac_val=\$$ac_var + case $ac_val in + *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + esac + $as_echo "$ac_var='\''$ac_val'\''" + done | sort + echo + + if test -n "$ac_subst_files"; then + $as_echo "## ------------------- ## +## File substitutions. ## +## ------------------- ##" + echo + for ac_var in $ac_subst_files + do + eval ac_val=\$$ac_var + case $ac_val in + *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + esac + $as_echo "$ac_var='\''$ac_val'\''" + done | sort + echo + fi + + if test -s confdefs.h; then + $as_echo "## ----------- ## +## confdefs.h. ## +## ----------- ##" + echo + cat confdefs.h + echo + fi + test "$ac_signal" != 0 && + $as_echo "$as_me: caught signal $ac_signal" + $as_echo "$as_me: exit $exit_status" + } >&5 + rm -f core *.core core.conftest.* && + rm -f -r conftest* confdefs* conf$$* $ac_clean_files && + exit $exit_status +' 0 +for ac_signal in 1 2 13 15; do + trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal +done +ac_signal=0 + +# confdefs.h avoids OS command line length limits that DEFS can exceed. +rm -f -r conftest* confdefs.h + +$as_echo "/* confdefs.h */" > confdefs.h + +# Predefined preprocessor variables. + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_NAME "$PACKAGE_NAME" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_TARNAME "$PACKAGE_TARNAME" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_VERSION "$PACKAGE_VERSION" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_STRING "$PACKAGE_STRING" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_URL "$PACKAGE_URL" +_ACEOF + + +# Let the site file select an alternate cache file if it wants to. +# Prefer an explicitly selected file to automatically selected ones. +ac_site_file1=NONE +ac_site_file2=NONE +if test -n "$CONFIG_SITE"; then + # We do not want a PATH search for config.site. + case $CONFIG_SITE in #(( + -*) ac_site_file1=./$CONFIG_SITE;; + */*) ac_site_file1=$CONFIG_SITE;; + *) ac_site_file1=./$CONFIG_SITE;; + esac +elif test "x$prefix" != xNONE; then + ac_site_file1=$prefix/share/config.site + ac_site_file2=$prefix/etc/config.site +else + ac_site_file1=$ac_default_prefix/share/config.site + ac_site_file2=$ac_default_prefix/etc/config.site +fi +for ac_site_file in "$ac_site_file1" "$ac_site_file2" +do + test "x$ac_site_file" = xNONE && continue + if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5 +$as_echo "$as_me: loading site script $ac_site_file" >&6;} + sed 's/^/| /' "$ac_site_file" >&5 + . "$ac_site_file" \ + || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "failed to load site script $ac_site_file +See \`config.log' for more details" "$LINENO" 5 ; } + fi +done + +if test -r "$cache_file"; then + # Some versions of bash will fail to source /dev/null (special files + # actually), so we avoid doing that. DJGPP emulates it as a regular file. + if test /dev/null != "$cache_file" && test -f "$cache_file"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5 +$as_echo "$as_me: loading cache $cache_file" >&6;} + case $cache_file in + [\\/]* | ?:[\\/]* ) . "$cache_file";; + *) . "./$cache_file";; + esac + fi +else + { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5 +$as_echo "$as_me: creating cache $cache_file" >&6;} + >$cache_file +fi + +# Check that the precious variables saved in the cache have kept the same +# value. +ac_cache_corrupted=false +for ac_var in $ac_precious_vars; do + eval ac_old_set=\$ac_cv_env_${ac_var}_set + eval ac_new_set=\$ac_env_${ac_var}_set + eval ac_old_val=\$ac_cv_env_${ac_var}_value + eval ac_new_val=\$ac_env_${ac_var}_value + case $ac_old_set,$ac_new_set in + set,) + { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 +$as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} + ac_cache_corrupted=: ;; + ,set) + { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5 +$as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} + ac_cache_corrupted=: ;; + ,);; + *) + if test "x$ac_old_val" != "x$ac_new_val"; then + # differences in whitespace do not lead to failure. + ac_old_val_w=`echo x $ac_old_val` + ac_new_val_w=`echo x $ac_new_val` + if test "$ac_old_val_w" != "$ac_new_val_w"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5 +$as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} + ac_cache_corrupted=: + else + { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5 +$as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;} + eval $ac_var=\$ac_old_val + fi + { $as_echo "$as_me:${as_lineno-$LINENO}: former value: \`$ac_old_val'" >&5 +$as_echo "$as_me: former value: \`$ac_old_val'" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: current value: \`$ac_new_val'" >&5 +$as_echo "$as_me: current value: \`$ac_new_val'" >&2;} + fi;; + esac + # Pass precious variables to config.status. + if test "$ac_new_set" = set; then + case $ac_new_val in + *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; + *) ac_arg=$ac_var=$ac_new_val ;; + esac + case " $ac_configure_args " in + *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. + *) as_fn_append ac_configure_args " '$ac_arg'" ;; + esac + fi +done +if $ac_cache_corrupted; then + { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5 +$as_echo "$as_me: error: changes in the environment can compromise the build" >&2;} + as_fn_error $? "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5 +fi +## -------------------- ## +## Main body of script. ## +## -------------------- ## + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + + +# Checks for programs. +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. +set dummy ${ac_tool_prefix}gcc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_CC+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_CC="${ac_tool_prefix}gcc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_CC"; then + ac_ct_CC=$CC + # Extract the first word of "gcc", so it can be a program name with args. +set dummy gcc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_ac_ct_CC+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_CC"; then + ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_CC="gcc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_CC=$ac_cv_prog_ac_ct_CC +if test -n "$ac_ct_CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 +$as_echo "$ac_ct_CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_CC" = x; then + CC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CC=$ac_ct_CC + fi +else + CC="$ac_cv_prog_CC" +fi + +if test -z "$CC"; then + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. +set dummy ${ac_tool_prefix}cc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_CC+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_CC="${ac_tool_prefix}cc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + fi +fi +if test -z "$CC"; then + # Extract the first word of "cc", so it can be a program name with args. +set dummy cc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_CC+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else + ac_prog_rejected=no +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then + ac_prog_rejected=yes + continue + fi + ac_cv_prog_CC="cc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +if test $ac_prog_rejected = yes; then + # We found a bogon in the path, so make sure we never use it. + set dummy $ac_cv_prog_CC + shift + if test $# != 0; then + # We chose a different compiler from the bogus one. + # However, it has the same basename, so the bogon will be chosen + # first if we set CC to just the basename; use the full file name. + shift + ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" + fi +fi +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$CC"; then + if test -n "$ac_tool_prefix"; then + for ac_prog in cl.exe + do + # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. +set dummy $ac_tool_prefix$ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_CC+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_CC="$ac_tool_prefix$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$CC" && break + done +fi +if test -z "$CC"; then + ac_ct_CC=$CC + for ac_prog in cl.exe +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_prog_ac_ct_CC+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_CC"; then + ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_prog_ac_ct_CC="$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_CC=$ac_cv_prog_ac_ct_CC +if test -n "$ac_ct_CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 +$as_echo "$ac_ct_CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$ac_ct_CC" && break +done + + if test "x$ac_ct_CC" = x; then + CC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CC=$ac_ct_CC + fi +fi + +fi + + +test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "no acceptable C compiler found in \$PATH +See \`config.log' for more details" "$LINENO" 5 ; } + +# Provide some information about the compiler. +$as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5 +set X $ac_compile +ac_compiler=$2 +for ac_option in --version -v -V -qversion; do + { { ac_try="$ac_compiler $ac_option >&5" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_compiler $ac_option >&5") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + sed '10a\ +... rest of stderr output deleted ... + 10q' conftest.err >conftest.er1 + cat conftest.er1 >&5 + fi + rm -f conftest.er1 conftest.err + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } +done + +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +ac_clean_files_save=$ac_clean_files +ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out" +# Try to create an executable without -o first, disregard a.out. +# It will help us diagnose broken compilers, and finding out an intuition +# of exeext. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5 +$as_echo_n "checking whether the C compiler works... " >&6; } +ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` + +# The possible output files: +ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*" + +ac_rmfiles= +for ac_file in $ac_files +do + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; + * ) ac_rmfiles="$ac_rmfiles $ac_file";; + esac +done +rm -f $ac_rmfiles + +if { { ac_try="$ac_link_default" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link_default") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then : + # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. +# So ignore a value of `no', otherwise this would lead to `EXEEXT = no' +# in a Makefile. We should not override ac_cv_exeext if it was cached, +# so that the user can short-circuit this test for compilers unknown to +# Autoconf. +for ac_file in $ac_files '' +do + test -f "$ac_file" || continue + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) + ;; + [ab].out ) + # We found the default executable, but exeext='' is most + # certainly right. + break;; + *.* ) + if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no; + then :; else + ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` + fi + # We set ac_cv_exeext here because the later test for it is not + # safe: cross compilers may not add the suffix if given an `-o' + # argument, so we may need to know it at that point already. + # Even if this section looks crufty: it has the advantage of + # actually working. + break;; + * ) + break;; + esac +done +test "$ac_cv_exeext" = no && ac_cv_exeext= + +else + ac_file='' +fi +if test -z "$ac_file"; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +$as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error 77 "C compiler cannot create executables +See \`config.log' for more details" "$LINENO" 5 ; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5 +$as_echo_n "checking for C compiler default output file name... " >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5 +$as_echo "$ac_file" >&6; } +ac_exeext=$ac_cv_exeext + +rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out +ac_clean_files=$ac_clean_files_save +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5 +$as_echo_n "checking for suffix of executables... " >&6; } +if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then : + # If both `conftest.exe' and `conftest' are `present' (well, observable) +# catch `conftest.exe'. For instance with Cygwin, `ls conftest' will +# work properly (i.e., refer to `conftest.exe'), while it won't with +# `rm'. +for ac_file in conftest.exe conftest conftest.*; do + test -f "$ac_file" || continue + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; + *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` + break;; + * ) break;; + esac +done +else + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot compute suffix of executables: cannot compile and link +See \`config.log' for more details" "$LINENO" 5 ; } +fi +rm -f conftest conftest$ac_cv_exeext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5 +$as_echo "$ac_cv_exeext" >&6; } + +rm -f conftest.$ac_ext +EXEEXT=$ac_cv_exeext +ac_exeext=$EXEEXT +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +int +main () +{ +FILE *f = fopen ("conftest.out", "w"); + return ferror (f) || fclose (f) != 0; + + ; + return 0; +} +_ACEOF +ac_clean_files="$ac_clean_files conftest.out" +# Check that the compiler produces executables we can run. If not, either +# the compiler is broken, or we cross compile. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5 +$as_echo_n "checking whether we are cross compiling... " >&6; } +if test "$cross_compiling" != yes; then + { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } + if { ac_try='./conftest$ac_cv_exeext' + { { case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; }; then + cross_compiling=no + else + if test "$cross_compiling" = maybe; then + cross_compiling=yes + else + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot run C compiled programs. +If you meant to cross compile, use \`--host'. +See \`config.log' for more details" "$LINENO" 5 ; } + fi + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5 +$as_echo "$cross_compiling" >&6; } + +rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out +ac_clean_files=$ac_clean_files_save +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5 +$as_echo_n "checking for suffix of object files... " >&6; } +if test "${ac_cv_objext+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.o conftest.obj +if { { ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_compile") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then : + for ac_file in conftest.o conftest.obj conftest.*; do + test -f "$ac_file" || continue; + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;; + *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` + break;; + esac +done +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot compute suffix of object files: cannot compile +See \`config.log' for more details" "$LINENO" 5 ; } +fi +rm -f conftest.$ac_cv_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5 +$as_echo "$ac_cv_objext" >&6; } +OBJEXT=$ac_cv_objext +ac_objext=$OBJEXT +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5 +$as_echo_n "checking whether we are using the GNU C compiler... " >&6; } +if test "${ac_cv_c_compiler_gnu+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ +#ifndef __GNUC__ + choke me +#endif + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_compiler_gnu=yes +else + ac_compiler_gnu=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +ac_cv_c_compiler_gnu=$ac_compiler_gnu + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5 +$as_echo "$ac_cv_c_compiler_gnu" >&6; } +if test $ac_compiler_gnu = yes; then + GCC=yes +else + GCC= +fi +ac_test_CFLAGS=${CFLAGS+set} +ac_save_CFLAGS=$CFLAGS +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5 +$as_echo_n "checking whether $CC accepts -g... " >&6; } +if test "${ac_cv_prog_cc_g+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_save_c_werror_flag=$ac_c_werror_flag + ac_c_werror_flag=yes + ac_cv_prog_cc_g=no + CFLAGS="-g" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_prog_cc_g=yes +else + CFLAGS="" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + +else + ac_c_werror_flag=$ac_save_c_werror_flag + CFLAGS="-g" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_prog_cc_g=yes +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + ac_c_werror_flag=$ac_save_c_werror_flag +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5 +$as_echo "$ac_cv_prog_cc_g" >&6; } +if test "$ac_test_CFLAGS" = set; then + CFLAGS=$ac_save_CFLAGS +elif test $ac_cv_prog_cc_g = yes; then + if test "$GCC" = yes; then + CFLAGS="-g -O2" + else + CFLAGS="-g" + fi +else + if test "$GCC" = yes; then + CFLAGS="-O2" + else + CFLAGS= + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5 +$as_echo_n "checking for $CC option to accept ISO C89... " >&6; } +if test "${ac_cv_prog_cc_c89+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_cv_prog_cc_c89=no +ac_save_CC=$CC +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +#include +#include +/* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ +struct buf { int x; }; +FILE * (*rcsopen) (struct buf *, struct stat *, int); +static char *e (p, i) + char **p; + int i; +{ + return p[i]; +} +static char *f (char * (*g) (char **, int), char **p, ...) +{ + char *s; + va_list v; + va_start (v,p); + s = g (p, va_arg (v,int)); + va_end (v); + return s; +} + +/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has + function prototypes and stuff, but not '\xHH' hex character constants. + These don't provoke an error unfortunately, instead are silently treated + as 'x'. The following induces an error, until -std is added to get + proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an + array size at least. It's necessary to write '\x00'==0 to get something + that's true only with -std. */ +int osf4_cc_array ['\x00' == 0 ? 1 : -1]; + +/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters + inside strings and character constants. */ +#define FOO(x) 'x' +int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1]; + +int test (int i, double x); +struct s1 {int (*f) (int a);}; +struct s2 {int (*f) (double a);}; +int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); +int argc; +char **argv; +int +main () +{ +return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; + ; + return 0; +} +_ACEOF +for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \ + -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" +do + CC="$ac_save_CC $ac_arg" + if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_prog_cc_c89=$ac_arg +fi +rm -f core conftest.err conftest.$ac_objext + test "x$ac_cv_prog_cc_c89" != "xno" && break +done +rm -f conftest.$ac_ext +CC=$ac_save_CC + +fi +# AC_CACHE_VAL +case "x$ac_cv_prog_cc_c89" in + x) + { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 +$as_echo "none needed" >&6; } ;; + xno) + { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 +$as_echo "unsupported" >&6; } ;; + *) + CC="$CC $ac_cv_prog_cc_c89" + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5 +$as_echo "$ac_cv_prog_cc_c89" >&6; } ;; +esac +if test "x$ac_cv_prog_cc_c89" != xno; then : + +fi + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ${MAKE-make} sets \$(MAKE)" >&5 +$as_echo_n "checking whether ${MAKE-make} sets \$(MAKE)... " >&6; } +set x ${MAKE-make} +ac_make=`$as_echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'` +if eval "test \"\${ac_cv_prog_make_${ac_make}_set+set}\"" = set; then : + $as_echo_n "(cached) " >&6 +else + cat >conftest.make <<\_ACEOF +SHELL = /bin/sh +all: + @echo '@@@%%%=$(MAKE)=@@@%%%' +_ACEOF +# GNU make sometimes prints "make[1]: Entering ...", which would confuse us. +case `${MAKE-make} -f conftest.make 2>/dev/null` in + *@@@%%%=?*=@@@%%%*) + eval ac_cv_prog_make_${ac_make}_set=yes;; + *) + eval ac_cv_prog_make_${ac_make}_set=no;; +esac +rm -f conftest.make +fi +if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + SET_MAKE= +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + SET_MAKE="MAKE=${MAKE-make}" +fi + + +if test "x$GCC" = "xyes"; then + CFLAGS="$CFLAGS -Wall" +fi + +#locating erlang + +# Check whether --with-erlang was given. +if test "${with_erlang+set}" = set; then : + withval=$with_erlang; +fi + + + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}erlc", so it can be a program name with args. +set dummy ${ac_tool_prefix}erlc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_path_ERLC+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + case $ERLC in + [\\/]* | ?:[\\/]*) + ac_cv_path_ERLC="$ERLC" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$with_erlang:$with_erlang/bin:$PATH" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_path_ERLC="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ERLC=$ac_cv_path_ERLC +if test -n "$ERLC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ERLC" >&5 +$as_echo "$ERLC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_ERLC"; then + ac_pt_ERLC=$ERLC + # Extract the first word of "erlc", so it can be a program name with args. +set dummy erlc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_path_ac_pt_ERLC+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + case $ac_pt_ERLC in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_ERLC="$ac_pt_ERLC" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$with_erlang:$with_erlang/bin:$PATH" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_path_ac_pt_ERLC="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_ERLC=$ac_cv_path_ac_pt_ERLC +if test -n "$ac_pt_ERLC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_ERLC" >&5 +$as_echo "$ac_pt_ERLC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_pt_ERLC" = x; then + ERLC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + ERLC=$ac_pt_ERLC + fi +else + ERLC="$ac_cv_path_ERLC" +fi + + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}erl", so it can be a program name with args. +set dummy ${ac_tool_prefix}erl; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_path_ERL+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + case $ERL in + [\\/]* | ?:[\\/]*) + ac_cv_path_ERL="$ERL" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$with_erlang:$with_erlang/bin:$PATH" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_path_ERL="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ERL=$ac_cv_path_ERL +if test -n "$ERL"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ERL" >&5 +$as_echo "$ERL" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_ERL"; then + ac_pt_ERL=$ERL + # Extract the first word of "erl", so it can be a program name with args. +set dummy erl; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_path_ac_pt_ERL+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + case $ac_pt_ERL in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_ERL="$ac_pt_ERL" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_dummy="$with_erlang:$with_erlang/bin:$PATH" +for as_dir in $as_dummy +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_path_ac_pt_ERL="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_ERL=$ac_cv_path_ac_pt_ERL +if test -n "$ac_pt_ERL"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_ERL" >&5 +$as_echo "$ac_pt_ERL" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_pt_ERL" = x; then + ERL="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + ERL=$ac_pt_ERL + fi +else + ERL="$ac_cv_path_ERL" +fi + + + if test "z$ERLC" = "z" || test "z$ERL" = "z"; then + as_fn_error $? "erlang not found" "$LINENO" 5 + fi + + + cat >>conftest.erl <<_EOF + +-module(conftest). +-author('alexey@sevcom.net'). + +-export([start/0]). + +start() -> + EIDirS = code:lib_dir("erl_interface") ++ "\n", + EILibS = libpath("erl_interface") ++ "\n", + RootDirS = code:root_dir() ++ "\n", + file:write_file("conftest.out", list_to_binary(EIDirS ++ EILibS ++ ssldef() ++ RootDirS)), + halt(). + +ssldef() -> + OTP = (catch erlang:system_info(otp_release)), + if + OTP >= "R14" -> "-DSSL40\n"; + OTP >= "R12" -> "-DSSL39\n"; + true -> "\n" + end. + +%% return physical architecture based on OS/Processor +archname() -> + ArchStr = erlang:system_info(system_architecture), + case os:type() of + {win32, _} -> "windows"; + {unix,UnixName} -> + Specs = string:tokens(ArchStr,"-"), + Cpu = case lists:nth(2,Specs) of + "pc" -> "x86"; + _ -> hd(Specs) + end, + atom_to_list(UnixName) ++ "-" ++ Cpu; + _ -> "generic" + end. + +%% Return arch-based library path or a default value if this directory +%% does not exist +libpath(App) -> + PrivDir = code:priv_dir(App), + ArchDir = archname(), + LibArchDir = filename:join([PrivDir,"lib",ArchDir]), + case file:list_dir(LibArchDir) of + %% Arch lib dir exists: We use it + {ok, _List} -> LibArchDir; + %% Arch lib dir does not exist: Return the default value + %% ({error, enoent}): + _Error -> code:lib_dir("erl_interface") ++ "/lib" + end. + +_EOF + + if ! $ERLC conftest.erl; then + as_fn_error $? "could not compile sample program" "$LINENO" 5 + fi + + if ! $ERL -s conftest -noshell; then + as_fn_error $? "could not run sample program" "$LINENO" 5 + fi + + if ! test -f conftest.out; then + as_fn_error $? "erlang program was not properly executed, (conftest.out was not produced)" "$LINENO" 5 + fi + + # First line + ERLANG_EI_DIR=`cat conftest.out | head -n 1` + # Second line + ERLANG_EI_LIB=`cat conftest.out | head -n 2 | tail -n 1` + # Third line + ERLANG_SSLVER=`cat conftest.out | head -n 3 | tail -n 1` + # End line + ERLANG_DIR=`cat conftest.out | tail -n 1` + + ERLANG_CFLAGS="-I$ERLANG_EI_DIR/include -I$ERLANG_DIR/usr/include" + ERLANG_LIBS="-L$ERLANG_EI_LIB -lerl_interface -lei" + + + + + + + +#locating iconv + + + +# Check whether --with-libiconv-prefix was given. +if test "${with_libiconv_prefix+set}" = set; then : + withval=$with_libiconv_prefix; + for dir in `echo "$withval" | tr : ' '`; do + if test -d $dir/include; then CPPFLAGS="$CPPFLAGS -I$dir/include"; fi + if test -d $dir/include; then CFLAGS="$CFLAGS -I$dir/include"; fi + if test -d $dir/lib; then LDFLAGS="$LDFLAGS -L$dir/lib"; fi + done + +fi + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for iconv" >&5 +$as_echo_n "checking for iconv... " >&6; } +if test "${am_cv_func_iconv+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + + am_cv_func_iconv="no, consider installing GNU libiconv" + am_cv_lib_iconv=no + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +int +main () +{ +iconv_t cd = iconv_open("",""); + iconv(cd,NULL,NULL,NULL,NULL); + iconv_close(cd); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + am_cv_func_iconv=yes +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext + if test "$am_cv_func_iconv" != yes; then + am_save_LIBS="$LIBS" + LIBS="$LIBS -liconv" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +int +main () +{ +iconv_t cd = iconv_open("",""); + iconv(cd,NULL,NULL,NULL,NULL); + iconv_close(cd); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + am_cv_lib_iconv=yes + am_cv_func_iconv=yes +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext + LIBS="$am_save_LIBS" + fi + if test "$am_cv_func_iconv" != yes; then + am_save_LIBS="$LIBS" + am_save_CFLAGS="$CFLAGS" + am_save_LDFLAGS="$LDFLAGS" + LIBS="$LIBS -liconv" + LDFLAGS="$LDFLAGS -L/usr/local/lib" + CFLAGS="$CFLAGS -I/usr/local/include" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +int +main () +{ +iconv_t cd = iconv_open("",""); + iconv(cd,NULL,NULL,NULL,NULL); + iconv_close(cd); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + am_cv_lib_iconv=yes + am_cv_func_iconv=yes + CPPFLAGS="$CPPFLAGS -I/usr/local/include" +else + LDFLAGS="$am_save_LDFLAGS" + CFLAGS="$am_save_CFLAGS" +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext + LIBS="$am_save_LIBS" + fi + + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $am_cv_func_iconv" >&5 +$as_echo "$am_cv_func_iconv" >&6; } + if test "$am_cv_func_iconv" = yes; then + +$as_echo "#define HAVE_ICONV 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for iconv declaration" >&5 +$as_echo_n "checking for iconv declaration... " >&6; } + if test "${am_cv_proto_iconv+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#include +extern +#ifdef __cplusplus +"C" +#endif +#if defined(__STDC__) || defined(__cplusplus) +size_t iconv (iconv_t cd, char * *inbuf, size_t *inbytesleft, char * *outbuf, size_t *outbytesleft); +#else +size_t iconv(); +#endif + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + am_cv_proto_iconv_arg1="" +else + am_cv_proto_iconv_arg1="const" +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + am_cv_proto_iconv="extern size_t iconv (iconv_t cd, $am_cv_proto_iconv_arg1 char * *inbuf, size_t *inbytesleft, char * *outbuf, size_t *outbytesleft);" +fi + + am_cv_proto_iconv=`echo "$am_cv_proto_iconv" | tr -s ' ' | sed -e 's/( /(/'` + { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${ac_t:- + }$am_cv_proto_iconv" >&5 +$as_echo "${ac_t:- + }$am_cv_proto_iconv" >&6; } + +cat >>confdefs.h <<_ACEOF +#define ICONV_CONST $am_cv_proto_iconv_arg1 +_ACEOF + + fi + LIBICONV= + if test "$am_cv_lib_iconv" = yes; then + LIBICONV="-liconv" + fi + + +#locating libexpat +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5 +$as_echo_n "checking how to run the C preprocessor... " >&6; } +# On Suns, sometimes $CPP names a directory. +if test -n "$CPP" && test -d "$CPP"; then + CPP= +fi +if test -z "$CPP"; then + if test "${ac_cv_prog_CPP+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + # Double quotes because CPP needs to be expanded + for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" + do + ac_preproc_ok=false +for ac_c_preproc_warn_flag in '' yes +do + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # Prefer to if __STDC__ is defined, since + # exists even on freestanding compilers. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#ifdef __STDC__ +# include +#else +# include +#endif + Syntax error +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + +else + # Broken: fails on valid input. +continue +fi +rm -f conftest.err conftest.i conftest.$ac_ext + + # OK, works on sane cases. Now check whether nonexistent headers + # can be detected and how. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + # Broken: success on invalid input. +continue +else + # Passes both tests. +ac_preproc_ok=: +break +fi +rm -f conftest.err conftest.i conftest.$ac_ext + +done +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.i conftest.err conftest.$ac_ext +if $ac_preproc_ok; then : + break +fi + + done + ac_cv_prog_CPP=$CPP + +fi + CPP=$ac_cv_prog_CPP +else + ac_cv_prog_CPP=$CPP +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5 +$as_echo "$CPP" >&6; } +ac_preproc_ok=false +for ac_c_preproc_warn_flag in '' yes +do + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # Prefer to if __STDC__ is defined, since + # exists even on freestanding compilers. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#ifdef __STDC__ +# include +#else +# include +#endif + Syntax error +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + +else + # Broken: fails on valid input. +continue +fi +rm -f conftest.err conftest.i conftest.$ac_ext + + # OK, works on sane cases. Now check whether nonexistent headers + # can be detected and how. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + # Broken: success on invalid input. +continue +else + # Passes both tests. +ac_preproc_ok=: +break +fi +rm -f conftest.err conftest.i conftest.$ac_ext + +done +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.i conftest.err conftest.$ac_ext +if $ac_preproc_ok; then : + +else + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "C preprocessor \"$CPP\" fails sanity check +See \`config.log' for more details" "$LINENO" 5 ; } +fi + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5 +$as_echo_n "checking for grep that handles long lines and -e... " >&6; } +if test "${ac_cv_path_GREP+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if test -z "$GREP"; then + ac_path_GREP_found=false + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in grep ggrep; do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" + { test -f "$ac_path_GREP" && $as_test_x "$ac_path_GREP"; } || continue +# Check for GNU ac_path_GREP and select it if it is found. + # Check for GNU $ac_path_GREP +case `"$ac_path_GREP" --version 2>&1` in +*GNU*) + ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; +*) + ac_count=0 + $as_echo_n 0123456789 >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + $as_echo 'GREP' >> "conftest.nl" + "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + as_fn_arith $ac_count + 1 && ac_count=$as_val + if test $ac_count -gt ${ac_path_GREP_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_GREP="$ac_path_GREP" + ac_path_GREP_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +esac + + $ac_path_GREP_found && break 3 + done + done + done +IFS=$as_save_IFS + if test -z "$ac_cv_path_GREP"; then + as_fn_error $? "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 + fi +else + ac_cv_path_GREP=$GREP +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5 +$as_echo "$ac_cv_path_GREP" >&6; } + GREP="$ac_cv_path_GREP" + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5 +$as_echo_n "checking for egrep... " >&6; } +if test "${ac_cv_path_EGREP+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 + then ac_cv_path_EGREP="$GREP -E" + else + if test -z "$EGREP"; then + ac_path_EGREP_found=false + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in egrep; do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" + { test -f "$ac_path_EGREP" && $as_test_x "$ac_path_EGREP"; } || continue +# Check for GNU ac_path_EGREP and select it if it is found. + # Check for GNU $ac_path_EGREP +case `"$ac_path_EGREP" --version 2>&1` in +*GNU*) + ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; +*) + ac_count=0 + $as_echo_n 0123456789 >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + $as_echo 'EGREP' >> "conftest.nl" + "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + as_fn_arith $ac_count + 1 && ac_count=$as_val + if test $ac_count -gt ${ac_path_EGREP_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_EGREP="$ac_path_EGREP" + ac_path_EGREP_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +esac + + $ac_path_EGREP_found && break 3 + done + done + done +IFS=$as_save_IFS + if test -z "$ac_cv_path_EGREP"; then + as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 + fi +else + ac_cv_path_EGREP=$EGREP +fi + + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5 +$as_echo "$ac_cv_path_EGREP" >&6; } + EGREP="$ac_cv_path_EGREP" + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5 +$as_echo_n "checking for ANSI C header files... " >&6; } +if test "${ac_cv_header_stdc+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +#include +#include + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_header_stdc=yes +else + ac_cv_header_stdc=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +if test $ac_cv_header_stdc = yes; then + # SunOS 4.x string.h does not declare mem*, contrary to ANSI. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "memchr" >/dev/null 2>&1; then : + +else + ac_cv_header_stdc=no +fi +rm -f conftest* + +fi + +if test $ac_cv_header_stdc = yes; then + # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "free" >/dev/null 2>&1; then : + +else + ac_cv_header_stdc=no +fi +rm -f conftest* + +fi + +if test $ac_cv_header_stdc = yes; then + # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. + if test "$cross_compiling" = yes; then : + : +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +#if ((' ' & 0x0FF) == 0x020) +# define ISLOWER(c) ('a' <= (c) && (c) <= 'z') +# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) +#else +# define ISLOWER(c) \ + (('a' <= (c) && (c) <= 'i') \ + || ('j' <= (c) && (c) <= 'r') \ + || ('s' <= (c) && (c) <= 'z')) +# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) +#endif + +#define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) +int +main () +{ + int i; + for (i = 0; i < 256; i++) + if (XOR (islower (i), ISLOWER (i)) + || toupper (i) != TOUPPER (i)) + return 2; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + +else + ac_cv_header_stdc=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5 +$as_echo "$ac_cv_header_stdc" >&6; } +if test $ac_cv_header_stdc = yes; then + +$as_echo "#define STDC_HEADERS 1" >>confdefs.h + +fi + +# On IRIX 5.3, sys/types and inttypes.h are conflicting. +for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ + inttypes.h stdint.h unistd.h +do : + as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default +" +if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +fi + +done + + + +# Check whether --with-expat was given. +if test "${with_expat+set}" = set; then : + withval=$with_expat; +fi + + + EXPAT_CFLAGS= + EXPAT_LIBS= + if test x"$with_expat" != x; then + EXPAT_CFLAGS="-I$with_expat/include" + EXPAT_LIBS="-L$with_expat/lib" + fi + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for XML_ParserCreate in -lexpat" >&5 +$as_echo_n "checking for XML_ParserCreate in -lexpat... " >&6; } +if test "${ac_cv_lib_expat_XML_ParserCreate+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lexpat "$EXPAT_LIBS" $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char XML_ParserCreate (); +int +main () +{ +return XML_ParserCreate (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_expat_XML_ParserCreate=yes +else + ac_cv_lib_expat_XML_ParserCreate=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_expat_XML_ParserCreate" >&5 +$as_echo "$ac_cv_lib_expat_XML_ParserCreate" >&6; } +if test "x$ac_cv_lib_expat_XML_ParserCreate" = x""yes; then : + EXPAT_LIBS="$EXPAT_LIBS -lexpat" + expat_found=yes +else + expat_found=no +fi + + if test $expat_found = no; then + as_fn_error $? "Could not find development files of Expat library" "$LINENO" 5 + fi + expat_save_CFLAGS="$CFLAGS" + CFLAGS="$CFLAGS $EXPAT_CFLAGS" + expat_save_CPPFLAGS="$CPPFLAGS" + CPPFLAGS="$CPPFLAGS $EXPAT_CFLAGS" + for ac_header in expat.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "expat.h" "ac_cv_header_expat_h" "$ac_includes_default" +if test "x$ac_cv_header_expat_h" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_EXPAT_H 1 +_ACEOF + +else + expat_found=no +fi + +done + + if test $expat_found = no; then + as_fn_error $? "Could not find expat.h" "$LINENO" 5 + fi + CFLAGS="$expat_save_CFLAGS" + CPPFLAGS="$expat_save_CPPFLAGS" + + + + + +# Checks for typedefs, structures, and compiler characteristics. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for an ANSI C-conforming const" >&5 +$as_echo_n "checking for an ANSI C-conforming const... " >&6; } +if test "${ac_cv_c_const+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ +/* FIXME: Include the comments suggested by Paul. */ +#ifndef __cplusplus + /* Ultrix mips cc rejects this. */ + typedef int charset[2]; + const charset cs; + /* SunOS 4.1.1 cc rejects this. */ + char const *const *pcpcc; + char **ppc; + /* NEC SVR4.0.2 mips cc rejects this. */ + struct point {int x, y;}; + static struct point const zero = {0,0}; + /* AIX XL C 1.02.0.0 rejects this. + It does not let you subtract one const X* pointer from another in + an arm of an if-expression whose if-part is not a constant + expression */ + const char *g = "string"; + pcpcc = &g + (g ? g-g : 0); + /* HPUX 7.0 cc rejects these. */ + ++pcpcc; + ppc = (char**) pcpcc; + pcpcc = (char const *const *) ppc; + { /* SCO 3.2v4 cc rejects this. */ + char *t; + char const *s = 0 ? (char *) 0 : (char const *) 0; + + *t++ = 0; + if (s) return 0; + } + { /* Someone thinks the Sun supposedly-ANSI compiler will reject this. */ + int x[] = {25, 17}; + const int *foo = &x[0]; + ++foo; + } + { /* Sun SC1.0 ANSI compiler rejects this -- but not the above. */ + typedef const int *iptr; + iptr p = 0; + ++p; + } + { /* AIX XL C 1.02.0.0 rejects this saying + "k.c", line 2.27: 1506-025 (S) Operand must be a modifiable lvalue. */ + struct s { int j; const int *ap[3]; }; + struct s *b; b->j = 5; + } + { /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */ + const int foo = 10; + if (!foo) return 0; + } + return !cs[0] && !zero.x; +#endif + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_c_const=yes +else + ac_cv_c_const=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_const" >&5 +$as_echo "$ac_cv_c_const" >&6; } +if test $ac_cv_c_const = no; then + +$as_echo "#define const /**/" >>confdefs.h + +fi + + +# Check Erlang headers are installed +#AC_CHECK_HEADER(erl_driver.h,,[AC_MSG_ERROR([cannot find Erlang header files])]) + +# Change default prefix + + +# Checks for library functions. +for ac_header in stdlib.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "stdlib.h" "ac_cv_header_stdlib_h" "$ac_includes_default" +if test "x$ac_cv_header_stdlib_h" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_STDLIB_H 1 +_ACEOF + +fi + +done + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU libc compatible malloc" >&5 +$as_echo_n "checking for GNU libc compatible malloc... " >&6; } +if test "${ac_cv_func_malloc_0_nonnull+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + ac_cv_func_malloc_0_nonnull=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#if defined STDC_HEADERS || defined HAVE_STDLIB_H +# include +#else +char *malloc (); +#endif + +int +main () +{ +return ! malloc (0); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_func_malloc_0_nonnull=yes +else + ac_cv_func_malloc_0_nonnull=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_malloc_0_nonnull" >&5 +$as_echo "$ac_cv_func_malloc_0_nonnull" >&6; } +if test $ac_cv_func_malloc_0_nonnull = yes; then : + +$as_echo "#define HAVE_MALLOC 1" >>confdefs.h + +else + $as_echo "#define HAVE_MALLOC 0" >>confdefs.h + + case " $LIBOBJS " in + *" malloc.$ac_objext "* ) ;; + *) LIBOBJS="$LIBOBJS malloc.$ac_objext" + ;; +esac + + +$as_echo "#define malloc rpl_malloc" >>confdefs.h + +fi + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5 +$as_echo_n "checking for ANSI C header files... " >&6; } +if test "${ac_cv_header_stdc+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +#include +#include + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_header_stdc=yes +else + ac_cv_header_stdc=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +if test $ac_cv_header_stdc = yes; then + # SunOS 4.x string.h does not declare mem*, contrary to ANSI. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "memchr" >/dev/null 2>&1; then : + +else + ac_cv_header_stdc=no +fi +rm -f conftest* + +fi + +if test $ac_cv_header_stdc = yes; then + # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "free" >/dev/null 2>&1; then : + +else + ac_cv_header_stdc=no +fi +rm -f conftest* + +fi + +if test $ac_cv_header_stdc = yes; then + # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. + if test "$cross_compiling" = yes; then : + : +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +#if ((' ' & 0x0FF) == 0x020) +# define ISLOWER(c) ('a' <= (c) && (c) <= 'z') +# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) +#else +# define ISLOWER(c) \ + (('a' <= (c) && (c) <= 'i') \ + || ('j' <= (c) && (c) <= 'r') \ + || ('s' <= (c) && (c) <= 'z')) +# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) +#endif + +#define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) +int +main () +{ + int i; + for (i = 0; i < 256; i++) + if (XOR (islower (i), ISLOWER (i)) + || toupper (i) != TOUPPER (i)) + return 2; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + +else + ac_cv_header_stdc=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5 +$as_echo "$ac_cv_header_stdc" >&6; } +if test $ac_cv_header_stdc = yes; then + +$as_echo "#define STDC_HEADERS 1" >>confdefs.h + +fi + + + +mod_irc= +make_mod_irc= +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether build mod_irc" >&5 +$as_echo_n "checking whether build mod_irc... " >&6; } +# Check whether --enable-mod_irc was given. +if test "${enable_mod_irc+set}" = set; then : + enableval=$enable_mod_irc; mr_enable_mod_irc="$enableval" +else + mr_enable_mod_irc=yes +fi + +if test "$mr_enable_mod_irc" = "yes"; then +mod_irc=mod_irc +make_mod_irc=mod_irc/Makefile +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $mr_enable_mod_irc" >&5 +$as_echo "$mr_enable_mod_irc" >&6; } + + + + + +mod_muc= +make_mod_muc= +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether build mod_muc" >&5 +$as_echo_n "checking whether build mod_muc... " >&6; } +# Check whether --enable-mod_muc was given. +if test "${enable_mod_muc+set}" = set; then : + enableval=$enable_mod_muc; mr_enable_mod_muc="$enableval" +else + mr_enable_mod_muc=yes +fi + +if test "$mr_enable_mod_muc" = "yes"; then +mod_muc=mod_muc +make_mod_muc=mod_muc/Makefile +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $mr_enable_mod_muc" >&5 +$as_echo "$mr_enable_mod_muc" >&6; } + + + + + +mod_proxy65= +make_mod_proxy65= +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether build mod_proxy65" >&5 +$as_echo_n "checking whether build mod_proxy65... " >&6; } +# Check whether --enable-mod_proxy65 was given. +if test "${enable_mod_proxy65+set}" = set; then : + enableval=$enable_mod_proxy65; mr_enable_mod_proxy65="$enableval" +else + mr_enable_mod_proxy65=yes +fi + +if test "$mr_enable_mod_proxy65" = "yes"; then +mod_proxy65=mod_proxy65 +make_mod_proxy65=mod_proxy65/Makefile +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $mr_enable_mod_proxy65" >&5 +$as_echo "$mr_enable_mod_proxy65" >&6; } + + + + + +mod_pubsub= +make_mod_pubsub= +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether build mod_pubsub" >&5 +$as_echo_n "checking whether build mod_pubsub... " >&6; } +# Check whether --enable-mod_pubsub was given. +if test "${enable_mod_pubsub+set}" = set; then : + enableval=$enable_mod_pubsub; mr_enable_mod_pubsub="$enableval" +else + mr_enable_mod_pubsub=yes +fi + +if test "$mr_enable_mod_pubsub" = "yes"; then +mod_pubsub=mod_pubsub +make_mod_pubsub=mod_pubsub/Makefile +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $mr_enable_mod_pubsub" >&5 +$as_echo "$mr_enable_mod_pubsub" >&6; } + + + + + +eldap= +make_eldap= +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether build eldap" >&5 +$as_echo_n "checking whether build eldap... " >&6; } +# Check whether --enable-eldap was given. +if test "${enable_eldap+set}" = set; then : + enableval=$enable_eldap; mr_enable_eldap="$enableval" +else + mr_enable_eldap=yes +fi + +if test "$mr_enable_eldap" = "yes"; then +eldap=eldap +make_eldap=eldap/Makefile +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $mr_enable_eldap" >&5 +$as_echo "$mr_enable_eldap" >&6; } + + + + + +odbc= +make_odbc= +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether build odbc" >&5 +$as_echo_n "checking whether build odbc... " >&6; } +# Check whether --enable-odbc was given. +if test "${enable_odbc+set}" = set; then : + enableval=$enable_odbc; mr_enable_odbc="$enableval" +else + mr_enable_odbc=no +fi + +if test "$mr_enable_odbc" = "yes"; then +odbc=odbc +make_odbc=odbc/Makefile +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $mr_enable_odbc" >&5 +$as_echo "$mr_enable_odbc" >&6; } + + + + + +tls= +make_tls= +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether build tls" >&5 +$as_echo_n "checking whether build tls... " >&6; } +# Check whether --enable-tls was given. +if test "${enable_tls+set}" = set; then : + enableval=$enable_tls; mr_enable_tls="$enableval" +else + mr_enable_tls=yes +fi + +if test "$mr_enable_tls" = "yes"; then +tls=tls +make_tls=tls/Makefile +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $mr_enable_tls" >&5 +$as_echo "$mr_enable_tls" >&6; } + + + + + +web= +make_web= +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether build web" >&5 +$as_echo_n "checking whether build web... " >&6; } +# Check whether --enable-web was given. +if test "${enable_web+set}" = set; then : + enableval=$enable_web; mr_enable_web="$enableval" +else + mr_enable_web=yes +fi + +if test "$mr_enable_web" = "yes"; then +web=web +make_web=web/Makefile +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $mr_enable_web" >&5 +$as_echo "$mr_enable_web" >&6; } + + + + + + +ejabberd_zlib= +make_ejabberd_zlib= +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether build ejabberd_zlib" >&5 +$as_echo_n "checking whether build ejabberd_zlib... " >&6; } +# Check whether --enable-ejabberd_zlib was given. +if test "${enable_ejabberd_zlib+set}" = set; then : + enableval=$enable_ejabberd_zlib; mr_enable_ejabberd_zlib="$enableval" +else + mr_enable_ejabberd_zlib=yes +fi + +if test "$mr_enable_ejabberd_zlib" = "yes"; then +ejabberd_zlib=ejabberd_zlib +make_ejabberd_zlib=ejabberd_zlib/Makefile +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $mr_enable_ejabberd_zlib" >&5 +$as_echo "$mr_enable_ejabberd_zlib" >&6; } + + + + +#locating zlib + +# Check whether --with-zlib was given. +if test "${with_zlib+set}" = set; then : + withval=$with_zlib; +fi + + +if test x"$ejabberd_zlib" != x; then + ZLIB_CFLAGS= + ZLIB_LIBS= + if test x"$with_zlib" != x; then + ZLIB_CFLAGS="-I$with_zlib/include" + ZLIB_LIBS="-L$with_zlib/lib" + fi + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for gzgets in -lz" >&5 +$as_echo_n "checking for gzgets in -lz... " >&6; } +if test "${ac_cv_lib_z_gzgets+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lz "$ZLIB_LIBS" $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char gzgets (); +int +main () +{ +return gzgets (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_z_gzgets=yes +else + ac_cv_lib_z_gzgets=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_z_gzgets" >&5 +$as_echo "$ac_cv_lib_z_gzgets" >&6; } +if test "x$ac_cv_lib_z_gzgets" = x""yes; then : + ZLIB_LIBS="$ZLIB_LIBS -lz" + zlib_found=yes +else + zlib_found=no +fi + + if test $zlib_found = no; then + as_fn_error $? "Could not find development files of zlib library. Install them or disable \`ejabberd_zlib' with: --disable-ejabberd_zlib" "$LINENO" 5 + fi + zlib_save_CFLAGS="$CFLAGS" + CFLAGS="$CFLAGS $ZLIB_CFLAGS" + zlib_save_CPPFLAGS="$CFLAGS" + CPPFLAGS="$CPPFLAGS $ZLIB_CFLAGS" + for ac_header in zlib.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "zlib.h" "ac_cv_header_zlib_h" "$ac_includes_default" +if test "x$ac_cv_header_zlib_h" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_ZLIB_H 1 +_ACEOF + +else + zlib_found=no +fi + +done + + if test $zlib_found = no; then + as_fn_error $? "Could not find zlib.h. Install it or disable \`ejabberd_zlib' with: --disable-ejabberd_zlib" "$LINENO" 5 + fi + CFLAGS="$zlib_save_CFLAGS" + CPPFLAGS="$zlib_save_CPPFLAGS" + + + +fi + + + +pam= +make_pam= +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether build pam" >&5 +$as_echo_n "checking whether build pam... " >&6; } +# Check whether --enable-pam was given. +if test "${enable_pam+set}" = set; then : + enableval=$enable_pam; mr_enable_pam="$enableval" +else + mr_enable_pam=no +fi + +if test "$mr_enable_pam" = "yes"; then +pam=pam +make_pam=pam/Makefile +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $mr_enable_pam" >&5 +$as_echo "$mr_enable_pam" >&6; } + + + + +#locating PAM + +# Check whether --with-pam was given. +if test "${with_pam+set}" = set; then : + withval=$with_pam; +fi + +if test x"$pam" != x; then + PAM_CFLAGS= + PAM_LIBS= + if test x"$with_pam" != x; then + PAM_CFLAGS="-I$with_pam/include" + PAM_LIBS="-L$with_pam/lib" + fi + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for pam_start in -lpam" >&5 +$as_echo_n "checking for pam_start in -lpam... " >&6; } +if test "${ac_cv_lib_pam_pam_start+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lpam "$PAM_LIBS" $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char pam_start (); +int +main () +{ +return pam_start (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_pam_pam_start=yes +else + ac_cv_lib_pam_pam_start=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_pam_pam_start" >&5 +$as_echo "$ac_cv_lib_pam_pam_start" >&6; } +if test "x$ac_cv_lib_pam_pam_start" = x""yes; then : + PAM_LIBS="$PAM_LIBS -lpam" + pam_found=yes +else + pam_found=no +fi + + if test $pam_found = no; then + as_fn_error $? "Could not find development files of PAM library. Install them or disable \`pam' with: --disable-pam" "$LINENO" 5 + fi + pam_save_CFLAGS="$CFLAGS" + CFLAGS="$CFLAGS $PAM_CFLAGS" + pam_save_CPPFLAGS="$CPPFLAGS" + CPPFLAGS="$CPPFLAGS $PAM_CFLAGS" + for ac_header in security/pam_appl.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "security/pam_appl.h" "ac_cv_header_security_pam_appl_h" "$ac_includes_default" +if test "x$ac_cv_header_security_pam_appl_h" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_SECURITY_PAM_APPL_H 1 +_ACEOF + +else + pam_found=no +fi + +done + + if test $pam_found = no; then + as_fn_error $? "Could not find security/pam_appl.h. Install it or disable \`pam' with: --disable-pam" "$LINENO" 5 + fi + CFLAGS="$pam_save_CFLAGS" + CPPFLAGS="$pam_save_CPPFLAGS" + + + +fi + + +# Check whether --enable-hipe was given. +if test "${enable_hipe+set}" = set; then : + enableval=$enable_hipe; case "${enableval}" in + yes) hipe=true ;; + no) hipe=false ;; + *) as_fn_error $? "bad value ${enableval} for --enable-hipe" "$LINENO" 5 ;; +esac +else + hipe=false +fi + + + +# Check whether --enable-roster_gateway_workaround was given. +if test "${enable_roster_gateway_workaround+set}" = set; then : + enableval=$enable_roster_gateway_workaround; case "${enableval}" in + yes) roster_gateway_workaround=true ;; + no) roster_gateway_workaround=false ;; + *) as_fn_error $? "bad value ${enableval} for --enable-roster-gateway-workaround" "$LINENO" 5 ;; +esac +else + roster_gateway_workaround=false +fi + + + +# Check whether --enable-flash_hack was given. +if test "${enable_flash_hack+set}" = set; then : + enableval=$enable_flash_hack; case "${enableval}" in + yes) flash_hack=true ;; + no) flash_hack=false ;; + *) as_fn_error $? "bad value ${enableval} for --enable-flash-hack" "$LINENO" 5 ;; +esac +else + flash_hack=false +fi + + + +# Check whether --enable-mssql was given. +if test "${enable_mssql+set}" = set; then : + enableval=$enable_mssql; case "${enableval}" in + yes) db_type=mssql ;; + no) db_type=generic ;; + *) as_fn_error $? "bad value ${enableval} for --enable-mssql" "$LINENO" 5 ;; +esac +else + db_type=generic +fi + + + +# Check whether --enable-transient_supervisors was given. +if test "${enable_transient_supervisors+set}" = set; then : + enableval=$enable_transient_supervisors; case "${enableval}" in + yes) transient_supervisors=true ;; + no) transient_supervisors=false ;; + *) as_fn_error $? "bad value ${enableval} for --enable-transient_supervisors" "$LINENO" 5 ;; +esac +else + transient_supervisors=true +fi + + + +# Check whether --enable-full_xml was given. +if test "${enable_full_xml+set}" = set; then : + enableval=$enable_full_xml; case "${enableval}" in + yes) full_xml=true ;; + no) full_xml=false ;; + *) as_fn_error $? "bad value ${enableval} for --enable-full-xml" "$LINENO" 5 ;; +esac +else + full_xml=false +fi + + + +# Check whether --enable-nif was given. +if test "${enable_nif+set}" = set; then : + enableval=$enable_nif; case "${enableval}" in + yes) nif=true ;; + no) nif=false ;; + *) as_fn_error $? "bad value ${enableval} for --enable-nif" "$LINENO" 5 ;; +esac +else + nif=false +fi + + + +ac_config_files="$ac_config_files Makefile $make_mod_irc $make_mod_muc $make_mod_pubsub $make_mod_proxy65 $make_eldap $make_pam $make_web stringprep/Makefile stun/Makefile $make_tls $make_odbc $make_ejabberd_zlib" + +#openssl + +# Check whether --with-openssl was given. +if test "${with_openssl+set}" = set; then : + withval=$with_openssl; +fi + +unset SSL_LIBS; +unset SSL_CFLAGS; +have_openssl=no +if test x"$tls" != x; then + for ssl_prefix in $withval /usr/local/ssl /usr/lib/ssl /usr/ssl /usr/pkg /usr/local /usr; do + printf "looking for openssl in $ssl_prefix...\n" + SSL_CFLAGS="-I$ssl_prefix/include" + SSL_LIBS="-L$ssl_prefix/lib -lcrypto" + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for SSL_new in -lssl" >&5 +$as_echo_n "checking for SSL_new in -lssl... " >&6; } +if test "${ac_cv_lib_ssl_SSL_new+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lssl $SSL_LIBS $SSL_CFLAGS $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char SSL_new (); +int +main () +{ +return SSL_new (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_ssl_SSL_new=yes +else + ac_cv_lib_ssl_SSL_new=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_ssl_SSL_new" >&5 +$as_echo "$ac_cv_lib_ssl_SSL_new" >&6; } +if test "x$ac_cv_lib_ssl_SSL_new" = x""yes; then : + have_openssl=yes +else + have_openssl=no +fi + + if test x"$have_openssl" = xyes; then + save_CPPFLAGS=$CPPFLAGS + CPPFLAGS="-I$ssl_prefix/include $CPPFLAGS" + for ac_header in openssl/ssl.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "openssl/ssl.h" "ac_cv_header_openssl_ssl_h" "$ac_includes_default" +if test "x$ac_cv_header_openssl_ssl_h" = x""yes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_OPENSSL_SSL_H 1 +_ACEOF + have_openssl_h=yes +fi + +done + + CPPFLAGS=$save_CPPFLAGS + if test x"$have_openssl_h" = xyes; then + have_openssl=yes + printf "openssl found in $ssl_prefix\n"; + SSL_LIBS="-L$ssl_prefix/lib -lssl -lcrypto" + CPPFLAGS="-I$ssl_prefix/include $CPPFLAGS" + SSL_CFLAGS="-DHAVE_SSL" + break + fi + else + # Clear this from the autoconf cache, so in the next pass of + # this loop with different -L arguments, it will test again. + unset ac_cv_lib_ssl_SSL_new + fi + done +if test x${have_openssl} != xyes; then + as_fn_error $? "Could not find development files of OpenSSL library. Install them or disable \`tls' with: --disable-tls" "$LINENO" 5 +fi + + +fi + +# If ssl is kerberized it need krb5.h +# On RedHat and OpenBSD, krb5.h is in an unsual place: +KRB5_INCLUDE="`krb5-config --cflags 2>/dev/null`" +if test -n "$KRB5_INCLUDE" ; then + CPPFLAGS="$CPPFLAGS $KRB5_INCLUDE" +else + # For RedHat For BSD + for D in /usr/kerberos/include /usr/include/kerberos /usr/include/kerberosV + do + if test -d $D ; then + CPPFLAGS="$CPPFLAGS -I$D" + fi + done +fi +ac_fn_c_check_header_mongrel "$LINENO" "krb5.h" "ac_cv_header_krb5_h" "$ac_includes_default" +if test "x$ac_cv_header_krb5_h" = x""yes; then : + +fi + + + +ENABLEUSER="" +# Check whether --enable-user was given. +if test "${enable_user+set}" = set; then : + enableval=$enable_user; case "${enableval}" in + yes) ENABLEUSER=`whoami` ;; + no) ENABLEUSER="" ;; + *) ENABLEUSER=$enableval + esac +fi + +if test "$ENABLEUSER" != ""; then + echo "allow this system user to start ejabberd: $ENABLEUSER" + INSTALLUSER=$ENABLEUSER + +fi + +ac_fn_c_check_header_mongrel "$LINENO" "openssl/md2.h" "ac_cv_header_openssl_md2_h" "$ac_includes_default" +if test "x$ac_cv_header_openssl_md2_h" = x""yes; then : + md2=true +else + md2=false +fi + + + + +ac_aux_dir= +for ac_dir in "$srcdir" "$srcdir/.." "$srcdir/../.."; do + if test -f "$ac_dir/install-sh"; then + ac_aux_dir=$ac_dir + ac_install_sh="$ac_aux_dir/install-sh -c" + break + elif test -f "$ac_dir/install.sh"; then + ac_aux_dir=$ac_dir + ac_install_sh="$ac_aux_dir/install.sh -c" + break + elif test -f "$ac_dir/shtool"; then + ac_aux_dir=$ac_dir + ac_install_sh="$ac_aux_dir/shtool install -c" + break + fi +done +if test -z "$ac_aux_dir"; then + as_fn_error $? "cannot find install-sh, install.sh, or shtool in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" "$LINENO" 5 +fi + +# These three variables are undocumented and unsupported, +# and are intended to be withdrawn in a future Autoconf release. +# They can cause serious problems if a builder's source tree is in a directory +# whose full name contains unusual characters. +ac_config_guess="$SHELL $ac_aux_dir/config.guess" # Please don't use this var. +ac_config_sub="$SHELL $ac_aux_dir/config.sub" # Please don't use this var. +ac_configure="$SHELL $ac_aux_dir/configure" # Please don't use this var. + + +# Make sure we can run config.sub. +$SHELL "$ac_aux_dir/config.sub" sun4 >/dev/null 2>&1 || + as_fn_error $? "cannot run $SHELL $ac_aux_dir/config.sub" "$LINENO" 5 + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking build system type" >&5 +$as_echo_n "checking build system type... " >&6; } +if test "${ac_cv_build+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + ac_build_alias=$build_alias +test "x$ac_build_alias" = x && + ac_build_alias=`$SHELL "$ac_aux_dir/config.guess"` +test "x$ac_build_alias" = x && + as_fn_error $? "cannot guess build type; you must specify one" "$LINENO" 5 +ac_cv_build=`$SHELL "$ac_aux_dir/config.sub" $ac_build_alias` || + as_fn_error $? "$SHELL $ac_aux_dir/config.sub $ac_build_alias failed" "$LINENO" 5 + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_build" >&5 +$as_echo "$ac_cv_build" >&6; } +case $ac_cv_build in +*-*-*) ;; +*) as_fn_error $? "invalid value of canonical build" "$LINENO" 5 ;; +esac +build=$ac_cv_build +ac_save_IFS=$IFS; IFS='-' +set x $ac_cv_build +shift +build_cpu=$1 +build_vendor=$2 +shift; shift +# Remember, the first character of IFS is used to create $*, +# except with old shells: +build_os=$* +IFS=$ac_save_IFS +case $build_os in *\ *) build_os=`echo "$build_os" | sed 's/ /-/g'`;; esac + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking host system type" >&5 +$as_echo_n "checking host system type... " >&6; } +if test "${ac_cv_host+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if test "x$host_alias" = x; then + ac_cv_host=$ac_cv_build +else + ac_cv_host=`$SHELL "$ac_aux_dir/config.sub" $host_alias` || + as_fn_error $? "$SHELL $ac_aux_dir/config.sub $host_alias failed" "$LINENO" 5 +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_host" >&5 +$as_echo "$ac_cv_host" >&6; } +case $ac_cv_host in +*-*-*) ;; +*) as_fn_error $? "invalid value of canonical host" "$LINENO" 5 ;; +esac +host=$ac_cv_host +ac_save_IFS=$IFS; IFS='-' +set x $ac_cv_host +shift +host_cpu=$1 +host_vendor=$2 +shift; shift +# Remember, the first character of IFS is used to create $*, +# except with old shells: +host_os=$* +IFS=$ac_save_IFS +case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking target system type" >&5 +$as_echo_n "checking target system type... " >&6; } +if test "${ac_cv_target+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + if test "x$target_alias" = x; then + ac_cv_target=$ac_cv_host +else + ac_cv_target=`$SHELL "$ac_aux_dir/config.sub" $target_alias` || + as_fn_error $? "$SHELL $ac_aux_dir/config.sub $target_alias failed" "$LINENO" 5 +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_target" >&5 +$as_echo "$ac_cv_target" >&6; } +case $ac_cv_target in +*-*-*) ;; +*) as_fn_error $? "invalid value of canonical target" "$LINENO" 5 ;; +esac +target=$ac_cv_target +ac_save_IFS=$IFS; IFS='-' +set x $ac_cv_target +shift +target_cpu=$1 +target_vendor=$2 +shift; shift +# Remember, the first character of IFS is used to create $*, +# except with old shells: +target_os=$* +IFS=$ac_save_IFS +case $target_os in *\ *) target_os=`echo "$target_os" | sed 's/ /-/g'`;; esac + + +# The aliases save the names the user supplied, while $host etc. +# will get canonicalized. +test -n "$target_alias" && + test "$program_prefix$program_suffix$program_transform_name" = \ + NONENONEs,x,x, && + program_prefix=${target_alias}- + +#AC_DEFINE_UNQUOTED(CPU_VENDOR_OS, "$target") +#AC_SUBST(target_os) + + +case "$target_os" in + *darwin10*) + echo "Target OS is 'Darwin10'" + ac_ext=erl +ac_compile='$ERLC $ERLCFLAGS -b beam conftest.$ac_ext >&5' +ac_link='$ERLC $ERLCFLAGS -b beam conftest.$ac_ext >&5 && echo "#!/bin/sh" > conftest$ac_exeext && $as_echo "\"$ERL\" -run conftest start -run init stop -noshell" >> conftest$ac_exeext && chmod +x conftest$ac_exeext' + + if test -n "$ERLC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for erlc" >&5 +$as_echo_n "checking for erlc... " >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ERLC" >&5 +$as_echo "$ERLC" >&6; } +else + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}erlc", so it can be a program name with args. +set dummy ${ac_tool_prefix}erlc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_path_ERLC+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + case $ERLC in + [\\/]* | ?:[\\/]*) + ac_cv_path_ERLC="$ERLC" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_path_ERLC="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ERLC=$ac_cv_path_ERLC +if test -n "$ERLC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ERLC" >&5 +$as_echo "$ERLC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_path_ERLC"; then + ac_pt_ERLC=$ERLC + # Extract the first word of "erlc", so it can be a program name with args. +set dummy erlc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if test "${ac_cv_path_ac_pt_ERLC+set}" = set; then : + $as_echo_n "(cached) " >&6 +else + case $ac_pt_ERLC in + [\\/]* | ?:[\\/]*) + ac_cv_path_ac_pt_ERLC="$ac_pt_ERLC" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then + ac_cv_path_ac_pt_ERLC="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ac_pt_ERLC=$ac_cv_path_ac_pt_ERLC +if test -n "$ac_pt_ERLC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_pt_ERLC" >&5 +$as_echo "$ac_pt_ERLC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_pt_ERLC" = x; then + ERLC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + ERLC=$ac_pt_ERLC + fi +else + ERLC="$ac_cv_path_ERLC" +fi + +fi + + +if test "$cross_compiling" = yes; then : + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot run test program while cross compiling +See \`config.log' for more details" "$LINENO" 5 ; } +else + cat > conftest.$ac_ext <<_ACEOF +-module(conftest). +-export([start/0]). + +start() -> + halt(case erlang:system_info(wordsize) of + 8 -> 0; 4 -> 1 end) +. + +_ACEOF +if ac_fn_erl_try_run "$LINENO"; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: found 64-bit Erlang" >&5 +$as_echo "$as_me: found 64-bit Erlang" >&6;} + CBIT=-m64 +else + { $as_echo "$as_me:${as_lineno-$LINENO}: found 32-bit Erlang" >&5 +$as_echo "$as_me: found 32-bit Erlang" >&6;} + CBIT=-m32 +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + ;; + *) + echo "Target OS is '$target_os'" + CBIT="" + ;; +esac +CFLAGS="$CFLAGS $CBIT" +LD_SHARED="$LD_SHARED $CBIT" +echo "CBIT is set to '$CBIT'" + +cat >confcache <<\_ACEOF +# This file is a shell script that caches the results of configure +# tests run on this system so they can be shared between configure +# scripts and configure runs, see configure's option --config-cache. +# It is not useful on other systems. If it contains results you don't +# want to keep, you may remove or edit it. +# +# config.status only pays attention to the cache file if you give it +# the --recheck option to rerun configure. +# +# `ac_cv_env_foo' variables (set or unset) will be overridden when +# loading this file, other *unset* `ac_cv_foo' will be assigned the +# following values. + +_ACEOF + +# The following way of writing the cache mishandles newlines in values, +# but we know of no workaround that is simple, portable, and efficient. +# So, we kill variables containing newlines. +# Ultrix sh set writes to stderr and can't be redirected directly, +# and sets the high bit in the cache file unless we assign to the vars. +( + for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do + eval ac_val=\$$ac_var + case $ac_val in #( + *${as_nl}*) + case $ac_var in #( + *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 +$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; + esac + case $ac_var in #( + _ | IFS | as_nl) ;; #( + BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( + *) { eval $ac_var=; unset $ac_var;} ;; + esac ;; + esac + done + + (set) 2>&1 | + case $as_nl`(ac_space=' '; set) 2>&1` in #( + *${as_nl}ac_space=\ *) + # `set' does not quote correctly, so add quotes: double-quote + # substitution turns \\\\ into \\, and sed turns \\ into \. + sed -n \ + "s/'/'\\\\''/g; + s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" + ;; #( + *) + # `set' quotes correctly as required by POSIX, so do not add quotes. + sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" + ;; + esac | + sort +) | + sed ' + /^ac_cv_env_/b end + t clear + :clear + s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/ + t end + s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/ + :end' >>confcache +if diff "$cache_file" confcache >/dev/null 2>&1; then :; else + if test -w "$cache_file"; then + test "x$cache_file" != "x/dev/null" && + { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5 +$as_echo "$as_me: updating cache $cache_file" >&6;} + cat confcache >$cache_file + else + { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5 +$as_echo "$as_me: not updating unwritable cache $cache_file" >&6;} + fi +fi +rm -f confcache + +test "x$prefix" = xNONE && prefix=$ac_default_prefix +# Let make expand exec_prefix. +test "x$exec_prefix" = xNONE && exec_prefix='${prefix}' + +# Transform confdefs.h into DEFS. +# Protect against shell expansion while executing Makefile rules. +# Protect against Makefile macro expansion. +# +# If the first sed substitution is executed (which looks for macros that +# take arguments), then branch to the quote section. Otherwise, +# look for a macro that doesn't take arguments. +ac_script=' +:mline +/\\$/{ + N + s,\\\n,, + b mline +} +t clear +:clear +s/^[ ]*#[ ]*define[ ][ ]*\([^ (][^ (]*([^)]*)\)[ ]*\(.*\)/-D\1=\2/g +t quote +s/^[ ]*#[ ]*define[ ][ ]*\([^ ][^ ]*\)[ ]*\(.*\)/-D\1=\2/g +t quote +b any +:quote +s/[ `~#$^&*(){}\\|;'\''"<>?]/\\&/g +s/\[/\\&/g +s/\]/\\&/g +s/\$/$$/g +H +:any +${ + g + s/^\n// + s/\n/ /g + p +} +' +DEFS=`sed -n "$ac_script" confdefs.h` + + +ac_libobjs= +ac_ltlibobjs= +U= +for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue + # 1. Remove the extension, and $U if already installed. + ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' + ac_i=`$as_echo "$ac_i" | sed "$ac_script"` + # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR + # will be set to the directory where LIBOBJS objects are built. + as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext" + as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo' +done +LIBOBJS=$ac_libobjs + +LTLIBOBJS=$ac_ltlibobjs + + + +: ${CONFIG_STATUS=./config.status} +ac_write_fail=0 +ac_clean_files_save=$ac_clean_files +ac_clean_files="$ac_clean_files $CONFIG_STATUS" +{ $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5 +$as_echo "$as_me: creating $CONFIG_STATUS" >&6;} +as_write_fail=0 +cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1 +#! $SHELL +# Generated by $as_me. +# Run this file to recreate the current configuration. +# Compiler output produced by configure, useful for debugging +# configure, is in config.log if it exists. + +debug=false +ac_cs_recheck=false +ac_cs_silent=false + +SHELL=\${CONFIG_SHELL-$SHELL} +export SHELL +_ASEOF +cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1 +## -------------------- ## +## M4sh Initialization. ## +## -------------------- ## + +# Be more Bourne compatible +DUALCASE=1; export DUALCASE # for MKS sh +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; +esac +fi + + +as_nl=' +' +export as_nl +# Printing a long string crashes Solaris 7 /usr/bin/printf. +as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo +# Prefer a ksh shell builtin over an external printf program on Solaris, +# but without wasting forks for bash or zsh. +if test -z "$BASH_VERSION$ZSH_VERSION" \ + && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='print -r --' + as_echo_n='print -rn --' +elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='printf %s\n' + as_echo_n='printf %s' +else + if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then + as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' + as_echo_n='/usr/ucb/echo -n' + else + as_echo_body='eval expr "X$1" : "X\\(.*\\)"' + as_echo_n_body='eval + arg=$1; + case $arg in #( + *"$as_nl"*) + expr "X$arg" : "X\\(.*\\)$as_nl"; + arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; + esac; + expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" + ' + export as_echo_n_body + as_echo_n='sh -c $as_echo_n_body as_echo' + fi + export as_echo_body + as_echo='sh -c $as_echo_body as_echo' +fi + +# The user is always right. +if test "${PATH_SEPARATOR+set}" != set; then + PATH_SEPARATOR=: + (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { + (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || + PATH_SEPARATOR=';' + } +fi + + +# IFS +# We need space, tab and new line, in precisely that order. Quoting is +# there to prevent editors from complaining about space-tab. +# (If _AS_PATH_WALK were called with IFS unset, it would disable word +# splitting by setting IFS to empty value.) +IFS=" "" $as_nl" + +# Find who we are. Look in the path if we contain no directory separator. +case $0 in #(( + *[\\/]* ) as_myself=$0 ;; + *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break + done +IFS=$as_save_IFS + + ;; +esac +# We did not find ourselves, most probably we were run as `sh COMMAND' +# in which case we are not to be found in the path. +if test "x$as_myself" = x; then + as_myself=$0 +fi +if test ! -f "$as_myself"; then + $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + exit 1 +fi + +# Unset variables that we do not need and which cause bugs (e.g. in +# pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" +# suppresses any "Segmentation fault" message there. '((' could +# trigger a bug in pdksh 5.2.14. +for as_var in BASH_ENV ENV MAIL MAILPATH +do eval test x\${$as_var+set} = xset \ + && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : +done +PS1='$ ' +PS2='> ' +PS4='+ ' + +# NLS nuisances. +LC_ALL=C +export LC_ALL +LANGUAGE=C +export LANGUAGE + +# CDPATH. +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH + + +# as_fn_error STATUS ERROR [LINENO LOG_FD] +# ---------------------------------------- +# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are +# provided, also output the error to LOG_FD, referencing LINENO. Then exit the +# script with STATUS, using 1 if that was 0. +as_fn_error () +{ + as_status=$1; test $as_status -eq 0 && as_status=1 + if test "$4"; then + as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 + fi + $as_echo "$as_me: error: $2" >&2 + as_fn_exit $as_status +} # as_fn_error + + +# as_fn_set_status STATUS +# ----------------------- +# Set $? to STATUS, without forking. +as_fn_set_status () +{ + return $1 +} # as_fn_set_status + +# as_fn_exit STATUS +# ----------------- +# Exit the shell with STATUS, even in a "trap 0" or "set -e" context. +as_fn_exit () +{ + set +e + as_fn_set_status $1 + exit $1 +} # as_fn_exit + +# as_fn_unset VAR +# --------------- +# Portably unset VAR. +as_fn_unset () +{ + { eval $1=; unset $1;} +} +as_unset=as_fn_unset +# as_fn_append VAR VALUE +# ---------------------- +# Append the text in VALUE to the end of the definition contained in VAR. Take +# advantage of any shell optimizations that allow amortized linear growth over +# repeated appends, instead of the typical quadratic growth present in naive +# implementations. +if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : + eval 'as_fn_append () + { + eval $1+=\$2 + }' +else + as_fn_append () + { + eval $1=\$$1\$2 + } +fi # as_fn_append + +# as_fn_arith ARG... +# ------------------ +# Perform arithmetic evaluation on the ARGs, and store the result in the +# global $as_val. Take advantage of shells that can avoid forks. The arguments +# must be portable across $(()) and expr. +if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : + eval 'as_fn_arith () + { + as_val=$(( $* )) + }' +else + as_fn_arith () + { + as_val=`expr "$@" || test $? -eq 1` + } +fi # as_fn_arith + + +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then + as_expr=expr +else + as_expr=false +fi + +if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then + as_basename=basename +else + as_basename=false +fi + +if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then + as_dirname=dirname +else + as_dirname=false +fi + +as_me=`$as_basename -- "$0" || +$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ + X"$0" : 'X\(//\)$' \| \ + X"$0" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X/"$0" | + sed '/^.*\/\([^/][^/]*\)\/*$/{ + s//\1/ + q + } + /^X\/\(\/\/\)$/{ + s//\1/ + q + } + /^X\/\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits + +ECHO_C= ECHO_N= ECHO_T= +case `echo -n x` in #((((( +-n*) + case `echo 'xy\c'` in + *c*) ECHO_T=' ';; # ECHO_T is single tab character. + xy) ECHO_C='\c';; + *) echo `echo ksh88 bug on AIX 6.1` > /dev/null + ECHO_T=' ';; + esac;; +*) + ECHO_N='-n';; +esac + +rm -f conf$$ conf$$.exe conf$$.file +if test -d conf$$.dir; then + rm -f conf$$.dir/conf$$.file +else + rm -f conf$$.dir + mkdir conf$$.dir 2>/dev/null +fi +if (echo >conf$$.file) 2>/dev/null; then + if ln -s conf$$.file conf$$ 2>/dev/null; then + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -p'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || + as_ln_s='cp -p' + elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln + else + as_ln_s='cp -p' + fi +else + as_ln_s='cp -p' +fi +rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file +rmdir conf$$.dir 2>/dev/null + + +# as_fn_mkdir_p +# ------------- +# Create "$as_dir" as a directory, including parents if necessary. +as_fn_mkdir_p () +{ + + case $as_dir in #( + -*) as_dir=./$as_dir;; + esac + test -d "$as_dir" || eval $as_mkdir_p || { + as_dirs= + while :; do + case $as_dir in #( + *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( + *) as_qdir=$as_dir;; + esac + as_dirs="'$as_qdir' $as_dirs" + as_dir=`$as_dirname -- "$as_dir" || +$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_dir" : 'X\(//\)[^/]' \| \ + X"$as_dir" : 'X\(//\)$' \| \ + X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_dir" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + test -d "$as_dir" && break + done + test -z "$as_dirs" || eval "mkdir $as_dirs" + } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" + + +} # as_fn_mkdir_p +if mkdir -p . 2>/dev/null; then + as_mkdir_p='mkdir -p "$as_dir"' +else + test -d ./-p && rmdir ./-p + as_mkdir_p=false +fi + +if test -x / >/dev/null 2>&1; then + as_test_x='test -x' +else + if ls -dL / >/dev/null 2>&1; then + as_ls_L_option=L + else + as_ls_L_option= + fi + as_test_x=' + eval sh -c '\'' + if test -d "$1"; then + test -d "$1/."; + else + case $1 in #( + -*)set "./$1";; + esac; + case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in #(( + ???[sx]*):;;*)false;;esac;fi + '\'' sh + ' +fi +as_executable_p=$as_test_x + +# Sed expression to map a string onto a valid CPP name. +as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" + +# Sed expression to map a string onto a valid variable name. +as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" + + +exec 6>&1 +## ----------------------------------- ## +## Main body of $CONFIG_STATUS script. ## +## ----------------------------------- ## +_ASEOF +test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1 + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# Save the log message, to keep $0 and so on meaningful, and to +# report actual input values of CONFIG_FILES etc. instead of their +# values after options handling. +ac_log=" +This file was extended by ejabberd $as_me 2.1.x, which was +generated by GNU Autoconf 2.67. Invocation command line was + + CONFIG_FILES = $CONFIG_FILES + CONFIG_HEADERS = $CONFIG_HEADERS + CONFIG_LINKS = $CONFIG_LINKS + CONFIG_COMMANDS = $CONFIG_COMMANDS + $ $0 $@ + +on `(hostname || uname -n) 2>/dev/null | sed 1q` +" + +_ACEOF + +case $ac_config_files in *" +"*) set x $ac_config_files; shift; ac_config_files=$*;; +esac + + + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +# Files that config.status was made for. +config_files="$ac_config_files" + +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +ac_cs_usage="\ +\`$as_me' instantiates files and other configuration actions +from templates according to the current configuration. Unless the files +and actions are specified as TAGs, all are instantiated by default. + +Usage: $0 [OPTION]... [TAG]... + + -h, --help print this help, then exit + -V, --version print version number and configuration settings, then exit + --config print configuration, then exit + -q, --quiet, --silent + do not print progress messages + -d, --debug don't remove temporary files + --recheck update $as_me by reconfiguring in the same conditions + --file=FILE[:TEMPLATE] + instantiate the configuration file FILE + +Configuration files: +$config_files + +Report bugs to ." + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`" +ac_cs_version="\\ +ejabberd config.status 2.1.x +configured by $0, generated by GNU Autoconf 2.67, + with options \\"\$ac_cs_config\\" + +Copyright (C) 2010 Free Software Foundation, Inc. +This config.status script is free software; the Free Software Foundation +gives unlimited permission to copy, distribute and modify it." + +ac_pwd='$ac_pwd' +srcdir='$srcdir' +test -n "\$AWK" || AWK=awk +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# The default lists apply if the user does not specify any file. +ac_need_defaults=: +while test $# != 0 +do + case $1 in + --*=?*) + ac_option=`expr "X$1" : 'X\([^=]*\)='` + ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'` + ac_shift=: + ;; + --*=) + ac_option=`expr "X$1" : 'X\([^=]*\)='` + ac_optarg= + ac_shift=: + ;; + *) + ac_option=$1 + ac_optarg=$2 + ac_shift=shift + ;; + esac + + case $ac_option in + # Handling of the options. + -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) + ac_cs_recheck=: ;; + --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) + $as_echo "$ac_cs_version"; exit ;; + --config | --confi | --conf | --con | --co | --c ) + $as_echo "$ac_cs_config"; exit ;; + --debug | --debu | --deb | --de | --d | -d ) + debug=: ;; + --file | --fil | --fi | --f ) + $ac_shift + case $ac_optarg in + *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; + '') as_fn_error $? "missing file argument" ;; + esac + as_fn_append CONFIG_FILES " '$ac_optarg'" + ac_need_defaults=false;; + --he | --h | --help | --hel | -h ) + $as_echo "$ac_cs_usage"; exit ;; + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil | --si | --s) + ac_cs_silent=: ;; + + # This is an error. + -*) as_fn_error $? "unrecognized option: \`$1' +Try \`$0 --help' for more information." ;; + + *) as_fn_append ac_config_targets " $1" + ac_need_defaults=false ;; + + esac + shift +done + +ac_configure_extra_args= + +if $ac_cs_silent; then + exec 6>/dev/null + ac_configure_extra_args="$ac_configure_extra_args --silent" +fi + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +if \$ac_cs_recheck; then + set X '$SHELL' '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion + shift + \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6 + CONFIG_SHELL='$SHELL' + export CONFIG_SHELL + exec "\$@" +fi + +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +exec 5>>config.log +{ + echo + sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX +## Running $as_me. ## +_ASBOX + $as_echo "$ac_log" +} >&5 + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 + +# Handling of arguments. +for ac_config_target in $ac_config_targets +do + case $ac_config_target in + "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;; + "$make_mod_irc") CONFIG_FILES="$CONFIG_FILES $make_mod_irc" ;; + "$make_mod_muc") CONFIG_FILES="$CONFIG_FILES $make_mod_muc" ;; + "$make_mod_pubsub") CONFIG_FILES="$CONFIG_FILES $make_mod_pubsub" ;; + "$make_mod_proxy65") CONFIG_FILES="$CONFIG_FILES $make_mod_proxy65" ;; + "$make_eldap") CONFIG_FILES="$CONFIG_FILES $make_eldap" ;; + "$make_pam") CONFIG_FILES="$CONFIG_FILES $make_pam" ;; + "$make_web") CONFIG_FILES="$CONFIG_FILES $make_web" ;; + "stringprep/Makefile") CONFIG_FILES="$CONFIG_FILES stringprep/Makefile" ;; + "stun/Makefile") CONFIG_FILES="$CONFIG_FILES stun/Makefile" ;; + "$make_tls") CONFIG_FILES="$CONFIG_FILES $make_tls" ;; + "$make_odbc") CONFIG_FILES="$CONFIG_FILES $make_odbc" ;; + "$make_ejabberd_zlib") CONFIG_FILES="$CONFIG_FILES $make_ejabberd_zlib" ;; + + *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5 ;; + esac +done + + +# If the user did not use the arguments to specify the items to instantiate, +# then the envvar interface is used. Set only those that are not. +# We use the long form for the default assignment because of an extremely +# bizarre bug on SunOS 4.1.3. +if $ac_need_defaults; then + test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files +fi + +# Have a temporary directory for convenience. Make it in the build tree +# simply because there is no reason against having it here, and in addition, +# creating and moving files from /tmp can sometimes cause problems. +# Hook for its removal unless debugging. +# Note that there is a small window in which the directory will not be cleaned: +# after its creation but before its name has been assigned to `$tmp'. +$debug || +{ + tmp= + trap 'exit_status=$? + { test -z "$tmp" || test ! -d "$tmp" || rm -fr "$tmp"; } && exit $exit_status +' 0 + trap 'as_fn_exit 1' 1 2 13 15 +} +# Create a (secure) tmp directory for tmp files. + +{ + tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` && + test -n "$tmp" && test -d "$tmp" +} || +{ + tmp=./conf$$-$RANDOM + (umask 077 && mkdir "$tmp") +} || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5 + +# Set up the scripts for CONFIG_FILES section. +# No need to generate them if there are no CONFIG_FILES. +# This happens for instance with `./config.status config.h'. +if test -n "$CONFIG_FILES"; then + + +ac_cr=`echo X | tr X '\015'` +# On cygwin, bash can eat \r inside `` if the user requested igncr. +# But we know of no other shell where ac_cr would be empty at this +# point, so we can use a bashism as a fallback. +if test "x$ac_cr" = x; then + eval ac_cr=\$\'\\r\' +fi +ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null` +if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then + ac_cs_awk_cr='\\r' +else + ac_cs_awk_cr=$ac_cr +fi + +echo 'BEGIN {' >"$tmp/subs1.awk" && +_ACEOF + + +{ + echo "cat >conf$$subs.awk <<_ACEOF" && + echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' && + echo "_ACEOF" +} >conf$$subs.sh || + as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 +ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'` +ac_delim='%!_!# ' +for ac_last_try in false false false false false :; do + . ./conf$$subs.sh || + as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 + + ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X` + if test $ac_delim_n = $ac_delim_num; then + break + elif $ac_last_try; then + as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 + else + ac_delim="$ac_delim!$ac_delim _$ac_delim!! " + fi +done +rm -f conf$$subs.sh + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +cat >>"\$tmp/subs1.awk" <<\\_ACAWK && +_ACEOF +sed -n ' +h +s/^/S["/; s/!.*/"]=/ +p +g +s/^[^!]*!// +:repl +t repl +s/'"$ac_delim"'$// +t delim +:nl +h +s/\(.\{148\}\)..*/\1/ +t more1 +s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/ +p +n +b repl +:more1 +s/["\\]/\\&/g; s/^/"/; s/$/"\\/ +p +g +s/.\{148\}// +t nl +:delim +h +s/\(.\{148\}\)..*/\1/ +t more2 +s/["\\]/\\&/g; s/^/"/; s/$/"/ +p +b +:more2 +s/["\\]/\\&/g; s/^/"/; s/$/"\\/ +p +g +s/.\{148\}// +t delim +' >$CONFIG_STATUS || ac_write_fail=1 +rm -f conf$$subs.awk +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +_ACAWK +cat >>"\$tmp/subs1.awk" <<_ACAWK && + for (key in S) S_is_set[key] = 1 + FS = "" + +} +{ + line = $ 0 + nfields = split(line, field, "@") + substed = 0 + len = length(field[1]) + for (i = 2; i < nfields; i++) { + key = field[i] + keylen = length(key) + if (S_is_set[key]) { + value = S[key] + line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3) + len += length(value) + length(field[++i]) + substed = 1 + } else + len += 1 + keylen + } + + print line +} + +_ACAWK +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then + sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g" +else + cat +fi < "$tmp/subs1.awk" > "$tmp/subs.awk" \ + || as_fn_error $? "could not setup config files machinery" "$LINENO" 5 +_ACEOF + +# VPATH may cause trouble with some makes, so we remove sole $(srcdir), +# ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and +# trailing colons and then remove the whole line if VPATH becomes empty +# (actually we leave an empty line to preserve line numbers). +if test "x$srcdir" = x.; then + ac_vpsub='/^[ ]*VPATH[ ]*=[ ]*/{ +h +s/// +s/^/:/ +s/[ ]*$/:/ +s/:\$(srcdir):/:/g +s/:\${srcdir}:/:/g +s/:@srcdir@:/:/g +s/^:*// +s/:*$// +x +s/\(=[ ]*\).*/\1/ +G +s/\n// +s/^[^=]*=[ ]*$// +}' +fi + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +fi # test -n "$CONFIG_FILES" + + +eval set X " :F $CONFIG_FILES " +shift +for ac_tag +do + case $ac_tag in + :[FHLC]) ac_mode=$ac_tag; continue;; + esac + case $ac_mode$ac_tag in + :[FHL]*:*);; + :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5 ;; + :[FH]-) ac_tag=-:-;; + :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; + esac + ac_save_IFS=$IFS + IFS=: + set x $ac_tag + IFS=$ac_save_IFS + shift + ac_file=$1 + shift + + case $ac_mode in + :L) ac_source=$1;; + :[FH]) + ac_file_inputs= + for ac_f + do + case $ac_f in + -) ac_f="$tmp/stdin";; + *) # Look for the file first in the build tree, then in the source tree + # (if the path is not absolute). The absolute path cannot be DOS-style, + # because $ac_f cannot contain `:'. + test -f "$ac_f" || + case $ac_f in + [\\/$]*) false;; + *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; + esac || + as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5 ;; + esac + case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac + as_fn_append ac_file_inputs " '$ac_f'" + done + + # Let's still pretend it is `configure' which instantiates (i.e., don't + # use $as_me), people would be surprised to read: + # /* config.h. Generated by config.status. */ + configure_input='Generated from '` + $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g' + `' by configure.' + if test x"$ac_file" != x-; then + configure_input="$ac_file. $configure_input" + { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5 +$as_echo "$as_me: creating $ac_file" >&6;} + fi + # Neutralize special characters interpreted by sed in replacement strings. + case $configure_input in #( + *\&* | *\|* | *\\* ) + ac_sed_conf_input=`$as_echo "$configure_input" | + sed 's/[\\\\&|]/\\\\&/g'`;; #( + *) ac_sed_conf_input=$configure_input;; + esac + + case $ac_tag in + *:-:* | *:-) cat >"$tmp/stdin" \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; + esac + ;; + esac + + ac_dir=`$as_dirname -- "$ac_file" || +$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$ac_file" : 'X\(//\)[^/]' \| \ + X"$ac_file" : 'X\(//\)$' \| \ + X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$ac_file" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + as_dir="$ac_dir"; as_fn_mkdir_p + ac_builddir=. + +case "$ac_dir" in +.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; +*) + ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` + # A ".." for each directory in $ac_dir_suffix. + ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` + case $ac_top_builddir_sub in + "") ac_top_builddir_sub=. ac_top_build_prefix= ;; + *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; + esac ;; +esac +ac_abs_top_builddir=$ac_pwd +ac_abs_builddir=$ac_pwd$ac_dir_suffix +# for backward compatibility: +ac_top_builddir=$ac_top_build_prefix + +case $srcdir in + .) # We are building in place. + ac_srcdir=. + ac_top_srcdir=$ac_top_builddir_sub + ac_abs_top_srcdir=$ac_pwd ;; + [\\/]* | ?:[\\/]* ) # Absolute name. + ac_srcdir=$srcdir$ac_dir_suffix; + ac_top_srcdir=$srcdir + ac_abs_top_srcdir=$srcdir ;; + *) # Relative name. + ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix + ac_top_srcdir=$ac_top_build_prefix$srcdir + ac_abs_top_srcdir=$ac_pwd/$srcdir ;; +esac +ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix + + + case $ac_mode in + :F) + # + # CONFIG_FILE + # + +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# If the template does not know about datarootdir, expand it. +# FIXME: This hack should be removed a few years after 2.60. +ac_datarootdir_hack=; ac_datarootdir_seen= +ac_sed_dataroot=' +/datarootdir/ { + p + q +} +/@datadir@/p +/@docdir@/p +/@infodir@/p +/@localedir@/p +/@mandir@/p' +case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in +*datarootdir*) ac_datarootdir_seen=yes;; +*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 +$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 + ac_datarootdir_hack=' + s&@datadir@&$datadir&g + s&@docdir@&$docdir&g + s&@infodir@&$infodir&g + s&@localedir@&$localedir&g + s&@mandir@&$mandir&g + s&\\\${datarootdir}&$datarootdir&g' ;; +esac +_ACEOF + +# Neutralize VPATH when `$srcdir' = `.'. +# Shell code in configure.ac might set extrasub. +# FIXME: do we really want to maintain this feature? +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +ac_sed_extra="$ac_vpsub +$extrasub +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +:t +/@[a-zA-Z_][a-zA-Z_0-9]*@/!b +s|@configure_input@|$ac_sed_conf_input|;t t +s&@top_builddir@&$ac_top_builddir_sub&;t t +s&@top_build_prefix@&$ac_top_build_prefix&;t t +s&@srcdir@&$ac_srcdir&;t t +s&@abs_srcdir@&$ac_abs_srcdir&;t t +s&@top_srcdir@&$ac_top_srcdir&;t t +s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t +s&@builddir@&$ac_builddir&;t t +s&@abs_builddir@&$ac_abs_builddir&;t t +s&@abs_top_builddir@&$ac_abs_top_builddir&;t t +$ac_datarootdir_hack +" +eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$tmp/subs.awk" >$tmp/out \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + +test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && + { ac_out=`sed -n '/\${datarootdir}/p' "$tmp/out"`; test -n "$ac_out"; } && + { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' "$tmp/out"`; test -z "$ac_out"; } && + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir' +which seems to be undefined. Please make sure it is defined" >&5 +$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' +which seems to be undefined. Please make sure it is defined" >&2;} + + rm -f "$tmp/stdin" + case $ac_file in + -) cat "$tmp/out" && rm -f "$tmp/out";; + *) rm -f "$ac_file" && mv "$tmp/out" "$ac_file";; + esac \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + ;; + + + + esac + +done # for ac_tag + + +as_fn_exit 0 +_ACEOF +ac_clean_files=$ac_clean_files_save + +test $ac_write_fail = 0 || + as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5 + + +# configure is writing to config.log, and then calls config.status. +# config.status does its own redirection, appending to config.log. +# Unfortunately, on DOS this fails, as config.log is still kept open +# by configure, so config.status won't be able to write to it; its +# output is simply discarded. So we exec the FD to /dev/null, +# effectively closing config.log, so it can be properly (re)opened and +# appended to by config.status. When coming back to configure, we +# need to make the FD available again. +if test "$no_create" != yes; then + ac_cs_success=: + ac_config_status_args= + test "$silent" = yes && + ac_config_status_args="$ac_config_status_args --quiet" + exec 5>/dev/null + $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false + exec 5>>config.log + # Use ||, not &&, to avoid exiting from the if with $? = 1, which + # would make configure fail if this is the last instruction. + $ac_cs_success || as_fn_exit 1 +fi +if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5 +$as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;} +fi + From d07424365dab9208e65b94d737bd73fb6917d05e Mon Sep 17 00:00:00 2001 From: Badlop Date: Mon, 18 Oct 2010 18:41:29 +0200 Subject: [PATCH 85/85] Fix bug in mod_pubsub in_subscription return value --- src/mod_pubsub/mod_pubsub.erl | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/mod_pubsub/mod_pubsub.erl b/src/mod_pubsub/mod_pubsub.erl index 2d95b1fac..78a3b3f6d 100644 --- a/src/mod_pubsub/mod_pubsub.erl +++ b/src/mod_pubsub/mod_pubsub.erl @@ -767,13 +767,15 @@ out_subscription(User, Server, JID, subscribed) -> [] -> user_resources(PUser, PServer); _ -> [PResource] end, - presence(Server, {presence, PUser, PServer, PResources, Owner}); + presence(Server, {presence, PUser, PServer, PResources, Owner}), + true; out_subscription(_,_,_,_) -> - ok. + true. in_subscription(_, User, Server, Owner, unsubscribed, _) -> - unsubscribe_user(jlib:make_jid(User, Server, ""), Owner); + unsubscribe_user(jlib:make_jid(User, Server, ""), Owner), + true; in_subscription(_, _, _, _, _, _) -> - ok. + true. unsubscribe_user(Entity, Owner) -> BJID = jlib:jid_tolower(jlib:jid_remove_resource(Owner)),