./ct_report/coverage/mod_carboncopy.COVER.html

1 %%%----------------------------------------------------------------------
2 %%% File : mod_carboncopy.erl
3 %%% Author : Eric Cestari <ecestari@process-one.net>
4 %%% Purpose : Message Carbons XEP-0280 0.8
5 %%% Created : 5 May 2008 by Mickael Remond <mremond@process-one.net>
6 %%% Usage : Add `mod_carboncopy` to the `modules` section of mongooseim.toml
7 %%%
8 %%%
9 %%% ejabberd, Copyright (C) 2002-2014 ProcessOne
10 %%%
11 %%% This program is free software; you can redistribute it and/or
12 %%% modify it under the terms of the GNU General Public License as
13 %%% published by the Free Software Foundation; either version 2 of the
14 %%% License, or (at your option) any later version.
15 %%%
16 %%% This program is distributed in the hope that it will be useful,
17 %%% but WITHOUT ANY WARRANTY; without even the implied warranty of
18 %%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 %%% General Public License for more details.
20 %%%
21 %%% You should have received a copy of the GNU General Public License along
22 %%% with this program; if not, write to the Free Software Foundation, Inc.,
23 %%% 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 %%%
25 %%%----------------------------------------------------------------------
26 -module (mod_carboncopy).
27 -author ('ecestari@process-one.net').
28 -xep([{xep, 280}, {version, "0.6"}]).
29 -xep([{xep, 280}, {version, "0.13.3"}]).
30 -behaviour(gen_mod).
31 -behaviour(mongoose_module_metrics).
32
33 %% API
34 -export([start/2,
35 stop/1,
36 supported_features/0,
37 config_spec/0,
38 is_carbon_copy/1]).
39
40 %% Hooks
41 -export([disco_local_features/1,
42 user_send_packet/4,
43 user_receive_packet/5,
44 iq_handler2/5,
45 iq_handler1/5,
46 remove_connection/5
47 ]).
48
49 %% Tests
50 -export([should_forward/3]).
51
52 -ignore_xref([disco_local_features/1, is_carbon_copy/1, remove_connection/5,
53 should_forward/3, user_receive_packet/5, user_send_packet/4]).
54
55 -define(CC_KEY, 'cc').
56
57 -include("mongoose.hrl").
58 -include("jlib.hrl").
59 -include("session.hrl").
60 -include("mongoose_config_spec.hrl").
61
62 -type direction() :: sent | received.
63
64 148 supported_features() -> [dynamic_domains].
65
66 is_carbon_copy(Packet) ->
67
:-(
case xml:get_subtag(Packet, <<"sent">>) of
68 #xmlel{name = <<"sent">>, attrs = AAttrs} ->
69
:-(
case xml:get_attr_s(<<"xmlns">>, AAttrs) of
70
:-(
?NS_CC_2 -> true;
71
:-(
?NS_CC_1 -> true;
72
:-(
_ -> false
73 end;
74
:-(
_ -> false
75 end.
76
77 %% Default IQDisc is no_queue:
78 %% executes disable/enable actions in the c2s process itself
79 start(HostType, #{iqdisc := IQDisc}) ->
80 320 ejabberd_hooks:add(hooks(HostType)),
81 320 gen_iq_handler:add_iq_handler_for_domain(HostType, ?NS_CC_2, ejabberd_sm,
82 fun ?MODULE:iq_handler2/5, #{}, IQDisc),
83 320 gen_iq_handler:add_iq_handler_for_domain(HostType, ?NS_CC_1, ejabberd_sm,
84 fun ?MODULE:iq_handler1/5, #{}, IQDisc).
85
86 stop(HostType) ->
87 320 ejabberd_hooks:delete(hooks(HostType)),
88 320 gen_iq_handler:remove_iq_handler_for_domain(HostType, ?NS_CC_1, ejabberd_sm),
89 320 gen_iq_handler:remove_iq_handler_for_domain(HostType, ?NS_CC_2, ejabberd_sm),
90 320 ok.
91
92 hooks(HostType) ->
93 640 [{disco_local_features, HostType, ?MODULE, disco_local_features, 99},
94 {unset_presence_hook, HostType, ?MODULE, remove_connection, 10},
95 {user_send_packet, HostType, ?MODULE, user_send_packet, 89},
96 {user_receive_packet, HostType, ?MODULE, user_receive_packet, 89}].
97
98 -spec config_spec() -> mongoose_config_spec:config_section().
99 config_spec() ->
100 166 #section{items = #{<<"iqdisc">> => mongoose_config_spec:iqdisc()},
101 defaults = #{<<"iqdisc">> => no_queue}}.
102
103 -spec disco_local_features(mongoose_disco:feature_acc()) -> mongoose_disco:feature_acc().
104 disco_local_features(Acc = #{node := <<>>}) ->
105 142 mongoose_disco:add_features([?NS_CC_1, ?NS_CC_2, ?NS_CC_RULES], Acc);
106 disco_local_features(Acc) ->
107 5 Acc.
108
109 iq_handler2(Acc, From, _To, IQ, _Extra) ->
110 43 iq_handler(Acc, From, IQ, ?NS_CC_2).
111 iq_handler1(Acc, From, _To, IQ, _Extra) ->
112
:-(
iq_handler(Acc, From, IQ, ?NS_CC_1).
113
114 iq_handler(Acc, From, #iq{type = set,
115 sub_el = #xmlel{name = Operation,
116 children = []}} = IQ, CC) ->
117 43 ?LOG_DEBUG(#{what => cc_iq_received, acc => Acc}),
118 43 Result = case Operation of
119 <<"enable">> ->
120 42 enable(From, CC);
121 <<"disable">> ->
122 1 disable(From)
123 end,
124 43 case Result of
125 ok ->
126 43 ?LOG_DEBUG(#{what => cc_iq_result, acc => Acc}),
127 43 {Acc, IQ#iq{type = result, sub_el = []}};
128 {error, Reason} ->
129
:-(
?LOG_WARNING(#{what => cc_iq_failed, acc => Acc, reason => Reason}),
130
:-(
{Acc, IQ#iq{type = error, sub_el = [mongoose_xmpp_errors:not_allowed()]}}
131 end;
132
133 iq_handler(Acc, _From, IQ, _CC) ->
134
:-(
{Acc, IQ#iq{type = error, sub_el = [mongoose_xmpp_errors:bad_request()]}}.
135
136 user_send_packet(Acc, From, To, Packet) ->
137 8052 check_and_forward(Acc, From, To, Packet, sent),
138 8052 Acc.
139
140 user_receive_packet(Acc, JID, _From, To, Packet) ->
141 11720 check_and_forward(Acc, JID, To, Packet, received),
142 11720 Acc.
143
144 remove_connection(Acc, LUser, LServer, LResource, _Status) ->
145 3047 JID = jid:make_noprep(LUser, LServer, LResource),
146 3047 disable(JID),
147 3047 Acc.
148
149 % Check if the traffic is local.
150 % Modified from original version:
151 % - registered to the user_send_packet hook, to be called only once even for multicast
152 % - do not support "private" message mode, and do not modify the original packet in any way
153 % - we also replicate "read" notifications
154 -spec check_and_forward(mongoose_acc:t(), jid:jid(), jid:jid(), exml:element(), direction()) -> ok | stop.
155 check_and_forward(Acc, JID, To, #xmlel{name = <<"message">>} = Packet, Direction) ->
156 6190 case should_forward(Packet, To, Direction) of
157 2472 false -> stop;
158 3718 true -> send_copies(Acc, JID, To, Packet, Direction)
159 end;
160 13582 check_and_forward(_Acc, _JID, _To, _Packet, _) -> ok.
161
162 %%%===================================================================
163 %%% Classification
164 %%%===================================================================
165
166 -spec should_forward(exml:element(), jid:jid(), direction()) -> boolean().
167 should_forward(Packet, To, Direction) ->
168 6190 (not is_carbon_private(Packet)) andalso
169 6188 (not has_nocopy_hint(Packet)) andalso
170 6188 (not is_received(Packet)) andalso
171 6179 (not is_sent(Packet)) andalso
172 6171 (is_chat(Packet) orelse is_valid_muc(Packet, To, Direction)).
173
174 -spec is_chat(exml:element()) -> boolean().
175 is_chat(Packet) ->
176 6171 case exml_query:attr(Packet, <<"type">>, <<"normal">>) of
177 1117 <<"normal">> -> contains_body(Packet) orelse
178 1111 contains_receipts(Packet) orelse
179 1111 contains_csn(Packet);
180 3688 <<"chat">> -> true;
181 1366 _ -> false
182 end.
183
184 -spec is_valid_muc(exml:element(), jid:jid(), direction()) -> boolean().
185 is_valid_muc(_, _, sent) ->
186 219 false;
187 is_valid_muc(Packet, To, _) ->
188 2258 is_mediated_invitation(Packet) orelse
189 2247 is_direct_muc_invitation(Packet) orelse
190 2241 is_received_private_muc(Packet, To).
191
192 -spec is_mediated_invitation(exml:element()) -> boolean().
193 is_mediated_invitation(Packet) ->
194 2258 undefined =/= exml_query:path(Packet,
195 [{element_with_ns, <<"x">>, ?NS_MUC_USER},
196 {element, <<"invite">>},
197 {attr, <<"from">>}]).
198
199 -spec is_direct_muc_invitation(exml:element()) -> boolean().
200 is_direct_muc_invitation(Packet) ->
201 2247 undefined =/= exml_query:subelement_with_name_and_ns(Packet, <<"x">>, ?NS_CONFERENCE).
202
203 -spec is_received_private_muc(exml:element(), jid:jid()) -> boolean().
204 is_received_private_muc(_, #jid{lresource = <<>>}) ->
205 437 false;
206 is_received_private_muc(Packet, _) ->
207 1804 undefined =/= exml_query:subelement_with_name_and_ns(Packet, <<"x">>, ?NS_MUC_USER).
208
209 -spec has_nocopy_hint(exml:element()) -> boolean().
210 has_nocopy_hint(Packet) ->
211 6188 undefined =/= exml_query:subelement_with_name_and_ns(Packet, <<"no-copy">>, ?NS_HINTS).
212
213 -spec contains_body(exml:element()) -> boolean().
214 contains_body(Packet) ->
215 1117 undefined =/= exml_query:subelement(Packet, <<"body">>).
216
217 -spec contains_receipts(exml:element()) -> boolean().
218 contains_receipts(Packet) ->
219 1111 undefined =/= exml_query:subelement_with_name_and_ns(Packet, <<"received">>, ?NS_RECEIPTS).
220
221 -spec contains_csn(exml:element()) -> boolean().
222 contains_csn(Packet) ->
223 1111 undefined =/= exml_query:subelement_with_ns(Packet, ?NS_CHATSTATES).
224
225 -spec is_carbon_private(exml:element()) -> boolean().
226 is_carbon_private(Packet) ->
227 6190 [] =/= subelements_with_nss(Packet, <<"private">>, carbon_namespaces()).
228
229 -spec is_received(exml:element()) -> boolean().
230 is_received(Packet) ->
231 6188 [] =/= subelements_with_nss(Packet, <<"received">>, carbon_namespaces()).
232
233 -spec is_sent(exml:element()) -> boolean().
234 is_sent(Packet) ->
235 6179 [] =/= subelements_with_nss(Packet, <<"sent">>, carbon_namespaces()).
236
237 -spec subelements_with_nss(exml:element(), binary(), [binary()]) -> [exml:element()].
238 subelements_with_nss(#xmlel{children = Children}, Name, NSS) ->
239 18557 lists:filter(fun(#xmlel{name = N} = Child) when N =:= Name ->
240 47 NS = exml_query:attr(Child, <<"xmlns">>),
241 47 lists:member(NS, NSS);
242 (_) ->
243 23189 false
244 end, Children).
245
246 18557 carbon_namespaces() -> [?NS_CC_1, ?NS_CC_2].
247
248 %%%===================================================================
249 %%% Internal
250 %%%===================================================================
251
252
253 %%
254 %% Internal
255 %%
256 is_bare_to(Direction, To, _PrioRes) ->
257 3718 case {Direction, To} of
258 172 {received, #jid{lresource = <<>>}} -> true;
259 3546 _ -> false
260 end.
261
262 max_prio(PrioRes) ->
263 12 case catch lists:max(PrioRes) of
264 12 {Prio, _Res} -> Prio;
265
:-(
_ -> 0
266 end.
267
268 is_max_prio(Res, PrioRes) ->
269 12 lists:member({max_prio(PrioRes), Res}, PrioRes).
270
271 jids_minus_max_priority_resource(JID, CCResList, PrioRes) ->
272 172 [ {jid:replace_resource(JID, CCRes), CCVersion}
273 172 || {CCVersion, CCRes} <- CCResList, not is_max_prio(CCRes, PrioRes) ].
274
275 jids_minus_specific_resource(JID, R, CCResList, _PrioRes) ->
276 3546 [ {jid:replace_resource(JID, CCRes), CCVersion}
277 3546 || {CCVersion, CCRes} <- CCResList, CCRes =/= R ].
278
279 %% Direction = received | sent <received xmlns='urn:xmpp:carbons:1'/>
280 send_copies(Acc, JID, To, Packet, Direction) ->
281 3718 #jid{lresource = R} = JID,
282 3718 {PrioRes, CCResList} = get_cc_enabled_resources(JID),
283 3718 Targets = case is_bare_to(Direction, To, PrioRes) of
284 172 true -> jids_minus_max_priority_resource
285 (JID, CCResList, PrioRes);
286 3546 _ -> jids_minus_specific_resource(JID, R, CCResList, PrioRes)
287 end,
288 3718 ?LOG_DEBUG(#{what => cc_send_copies,
289 3718 targets => Targets, resources => PrioRes, ccenabled => CCResList}),
290 3718 lists:foreach(fun({Dest, Version}) ->
291 17 ?LOG_DEBUG(#{what => cc_forwarding,
292 user => JID#jid.luser, server => JID#jid.lserver,
293 17 resource => JID#jid.lresource, exml_packet => Packet}),
294 17 Sender = jid:to_bare(JID),
295 17 New = build_forward_packet(Acc, JID, Packet, Sender, Dest, Direction, Version),
296 17 ejabberd_router:route(Sender, Dest, Acc, New)
297 end, Targets).
298
299 build_forward_packet(Acc, JID, Packet, Sender, Dest, Direction, Version) ->
300 % The wrapping message SHOULD maintain the same 'type' attribute value;
301 17 Type = exml_query:attr(Packet, <<"type">>, <<"normal">>),
302 17 #xmlel{name = <<"message">>,
303 attrs = [{<<"xmlns">>, <<"jabber:client">>},
304 {<<"type">>, Type},
305 {<<"from">>, jid:to_binary(Sender)},
306 {<<"to">>, jid:to_binary(Dest)}],
307 children = carbon_copy_children(Acc, Version, JID, Packet, Direction)}.
308
309 carbon_copy_children(Acc, ?NS_CC_1, JID, Packet, Direction) ->
310
:-(
[ #xmlel{name = atom_to_binary(Direction, utf8),
311 attrs = [{<<"xmlns">>, ?NS_CC_1}]},
312 #xmlel{name = <<"forwarded">>,
313 attrs = [{<<"xmlns">>, ?NS_FORWARD}],
314 children = [complete_packet(Acc, JID, Packet, Direction)]} ];
315 carbon_copy_children(Acc, ?NS_CC_2, JID, Packet, Direction) ->
316 17 [ #xmlel{name = atom_to_binary(Direction, utf8),
317 attrs = [{<<"xmlns">>, ?NS_CC_2}],
318 children = [ #xmlel{name = <<"forwarded">>,
319 attrs = [{<<"xmlns">>, ?NS_FORWARD}],
320 children = [complete_packet(Acc, JID, Packet, Direction)]} ]} ].
321
322 enable(JID, CC) ->
323 42 ?LOG_INFO(#{what => cc_enable,
324 42 user => JID#jid.luser, server => JID#jid.lserver}),
325 42 case ejabberd_sm:store_info(JID, ?CC_KEY, cc_ver_to_int(CC)) of
326 42 {ok, ?CC_KEY} -> ok;
327
:-(
{error, _} = Err -> Err
328 end.
329
330 disable(JID) ->
331 3048 ?LOG_INFO(#{what => cc_disable,
332 3048 user => JID#jid.luser, server => JID#jid.lserver}),
333 3048 case ejabberd_sm:remove_info(JID, ?CC_KEY) of
334 215 ok -> ok;
335 2833 {error, offline} -> ok
336 end.
337
338 complete_packet(Acc, From, #xmlel{name = <<"message">>, attrs = OrigAttrs} = Packet, sent) ->
339 %% if this is a packet sent by user on this host, then Packet doesn't
340 %% include the 'from' attribute. We must add it.
341 8 Attrs = lists:keystore(<<"xmlns">>, 1, OrigAttrs, {<<"xmlns">>, <<"jabber:client">>}),
342 8 Packet2 = set_stanza_id(Acc, From, Packet),
343 8 case proplists:get_value(<<"from">>, Attrs) of
344 undefined ->
345 8 Packet2#xmlel{attrs = [{<<"from">>, jid:to_binary(From)} | Attrs]};
346 _ ->
347
:-(
Packet2#xmlel{attrs = Attrs}
348 end;
349
350 complete_packet(_Acc, _From, #xmlel{name = <<"message">>, attrs = OrigAttrs} = Packet, received) ->
351 9 Attrs = lists:keystore(<<"xmlns">>, 1, OrigAttrs, {<<"xmlns">>, <<"jabber:client">>}),
352 9 Packet#xmlel{attrs = Attrs}.
353
354 get_cc_enabled_resources(JID) ->
355 3718 AllSessions = ejabberd_sm:get_raw_sessions(JID),
356 3718 CCs = filter_cc_enabled_resources(AllSessions),
357 3718 Prios = filter_priority_resources(AllSessions),
358 3718 {Prios, CCs}.
359
360 filter_cc_enabled_resources(AllSessions) ->
361 3718 lists:filtermap(fun fun_filter_cc_enabled_resource/1, AllSessions).
362
363 fun_filter_cc_enabled_resource(Session = #session{usr = {_, _, R}}) ->
364 4070 case mongoose_session:get_info(Session, ?CC_KEY, undefined) of
365 {?CC_KEY, V} when is_integer(V) ->
366 46 {true, {cc_ver_from_int(V), R}};
367 _ ->
368 4024 false
369 end.
370
371 filter_priority_resources(AllSessions) ->
372 3718 lists:filtermap(fun fun_filter_priority_resources/1, AllSessions).
373
374 fun_filter_priority_resources(#session{usr = {_, _, R}, priority = P})
375 when is_integer(P) ->
376 4002 {true, {P, R}};
377 fun_filter_priority_resources(_) ->
378 68 false.
379
380
:-(
cc_ver_to_int(?NS_CC_1) -> 1;
381 42 cc_ver_to_int(?NS_CC_2) -> 2.
382
383
:-(
cc_ver_from_int(1) -> ?NS_CC_1;
384 46 cc_ver_from_int(2) -> ?NS_CC_2.
385
386 %% Servers SHOULD include the element as a child
387 %% of the forwarded message when using Message Carbons (XEP-0280)
388 %% https://xmpp.org/extensions/xep-0313.html#archives_id
389 set_stanza_id(Acc, From, Packet) ->
390 8 MamId = mongoose_acc:get(mam, mam_id, undefined, Acc),
391 8 set_stanza_id(MamId, From, Acc, Packet).
392
393 set_stanza_id(undefined, _From, _Acc, Packet) ->
394 6 Packet;
395 set_stanza_id(MamId, From, _Acc, Packet) ->
396 2 By = jid:to_bare_binary(From),
397 2 mod_mam_utils:replace_arcid_elem(<<"stanza-id">>, By, MamId, Packet).
Line Hits Source