./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 138 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 297 ejabberd_hooks:add(hooks(HostType)),
81 297 gen_iq_handler:add_iq_handler_for_domain(HostType, ?NS_CC_2, ejabberd_sm,
82 fun ?MODULE:iq_handler2/5, #{}, IQDisc),
83 297 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 297 ejabberd_hooks:delete(hooks(HostType)),
88 297 gen_iq_handler:remove_iq_handler_for_domain(HostType, ?NS_CC_1, ejabberd_sm),
89 297 gen_iq_handler:remove_iq_handler_for_domain(HostType, ?NS_CC_2, ejabberd_sm),
90 297 ok.
91
92 hooks(HostType) ->
93 594 [{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 152 #section{
101 format_items = map,
102 items = #{<<"iqdisc">> => mongoose_config_spec:iqdisc()},
103 defaults = #{<<"iqdisc">> => no_queue}}.
104
105 -spec disco_local_features(mongoose_disco:feature_acc()) -> mongoose_disco:feature_acc().
106 disco_local_features(Acc = #{node := <<>>}) ->
107 72 mongoose_disco:add_features([?NS_CC_1, ?NS_CC_2, ?NS_CC_RULES], Acc);
108 disco_local_features(Acc) ->
109 5 Acc.
110
111 iq_handler2(Acc, From, _To, IQ, _Extra) ->
112 74 iq_handler(Acc, From, IQ, ?NS_CC_2).
113 iq_handler1(Acc, From, _To, IQ, _Extra) ->
114
:-(
iq_handler(Acc, From, IQ, ?NS_CC_1).
115
116 iq_handler(Acc, From, #iq{type = set,
117 sub_el = #xmlel{name = Operation,
118 children = []}} = IQ, CC) ->
119 74 ?LOG_DEBUG(#{what => cc_iq_received, acc => Acc}),
120 74 Result = case Operation of
121 <<"enable">> ->
122 73 enable(From, CC);
123 <<"disable">> ->
124 1 disable(From)
125 end,
126 74 case Result of
127 ok ->
128 74 ?LOG_DEBUG(#{what => cc_iq_result, acc => Acc}),
129 74 {Acc, IQ#iq{type = result, sub_el = []}};
130 {error, Reason} ->
131
:-(
?LOG_WARNING(#{what => cc_iq_failed, acc => Acc, reason => Reason}),
132
:-(
{Acc, IQ#iq{type = error, sub_el = [mongoose_xmpp_errors:not_allowed()]}}
133 end;
134
135 iq_handler(Acc, _From, IQ, _CC) ->
136
:-(
{Acc, IQ#iq{type = error, sub_el = [mongoose_xmpp_errors:bad_request()]}}.
137
138 user_send_packet(Acc, From, To, Packet) ->
139 11767 check_and_forward(Acc, From, To, Packet, sent),
140 11767 Acc.
141
142 user_receive_packet(Acc, JID, _From, To, Packet) ->
143 21449 check_and_forward(Acc, JID, To, Packet, received),
144 21449 Acc.
145
146 remove_connection(Acc, LUser, LServer, LResource, _Status) ->
147 3936 JID = jid:make_noprep(LUser, LServer, LResource),
148 3936 disable(JID),
149 3936 Acc.
150
151 % Check if the traffic is local.
152 % Modified from original version:
153 % - registered to the user_send_packet hook, to be called only once even for multicast
154 % - do not support "private" message mode, and do not modify the original packet in any way
155 % - we also replicate "read" notifications
156 -spec check_and_forward(mongoose_acc:t(), jid:jid(), jid:jid(), exml:element(), direction()) -> ok | stop.
157 check_and_forward(Acc, JID, To, #xmlel{name = <<"message">>} = Packet, Direction) ->
158 13956 case should_forward(Packet, To, Direction) of
159 8937 false -> stop;
160 5019 true -> send_copies(Acc, JID, To, Packet, Direction)
161 end;
162 19260 check_and_forward(_Acc, _JID, _To, _Packet, _) -> ok.
163
164 %%%===================================================================
165 %%% Classification
166 %%%===================================================================
167
168 -spec should_forward(exml:element(), jid:jid(), direction()) -> boolean().
169 should_forward(Packet, To, Direction) ->
170 13956 (not is_carbon_private(Packet)) andalso
171 13954 (not has_nocopy_hint(Packet)) andalso
172 13954 (not is_received(Packet)) andalso
173 13938 (not is_sent(Packet)) andalso
174 13926 (is_chat(Packet) orelse is_valid_muc(Packet, To, Direction)).
175
176 -spec is_chat(exml:element()) -> boolean().
177 is_chat(Packet) ->
178 13926 case exml_query:attr(Packet, <<"type">>, <<"normal">>) of
179 5695 <<"normal">> -> contains_body(Packet) orelse
180 5689 contains_receipts(Packet) orelse
181 5689 contains_csn(Packet);
182 4989 <<"chat">> -> true;
183 3242 _ -> false
184 end.
185
186 -spec is_valid_muc(exml:element(), jid:jid(), direction()) -> boolean().
187 is_valid_muc(_, _, sent) ->
188 749 false;
189 is_valid_muc(Packet, To, _) ->
190 8182 is_mediated_invitation(Packet) orelse
191 8171 is_direct_muc_invitation(Packet) orelse
192 8165 is_received_private_muc(Packet, To).
193
194 -spec is_mediated_invitation(exml:element()) -> boolean().
195 is_mediated_invitation(Packet) ->
196 8182 undefined =/= exml_query:path(Packet,
197 [{element_with_ns, <<"x">>, ?NS_MUC_USER},
198 {element, <<"invite">>},
199 {attr, <<"from">>}]).
200
201 -spec is_direct_muc_invitation(exml:element()) -> boolean().
202 is_direct_muc_invitation(Packet) ->
203 8171 undefined =/= exml_query:subelement_with_name_and_ns(Packet, <<"x">>, ?NS_CONFERENCE).
204
205 -spec is_received_private_muc(exml:element(), jid:jid()) -> boolean().
206 is_received_private_muc(_, #jid{lresource = <<>>}) ->
207 1185 false;
208 is_received_private_muc(Packet, _) ->
209 6980 undefined =/= exml_query:subelement_with_name_and_ns(Packet, <<"x">>, ?NS_MUC_USER).
210
211 -spec has_nocopy_hint(exml:element()) -> boolean().
212 has_nocopy_hint(Packet) ->
213 13954 undefined =/= exml_query:subelement_with_name_and_ns(Packet, <<"no-copy">>, ?NS_HINTS).
214
215 -spec contains_body(exml:element()) -> boolean().
216 contains_body(Packet) ->
217 5695 undefined =/= exml_query:subelement(Packet, <<"body">>).
218
219 -spec contains_receipts(exml:element()) -> boolean().
220 contains_receipts(Packet) ->
221 5689 undefined =/= exml_query:subelement_with_name_and_ns(Packet, <<"received">>, ?NS_RECEIPTS).
222
223 -spec contains_csn(exml:element()) -> boolean().
224 contains_csn(Packet) ->
225 5689 undefined =/= exml_query:subelement_with_ns(Packet, ?NS_CHATSTATES).
226
227 -spec is_carbon_private(exml:element()) -> boolean().
228 is_carbon_private(Packet) ->
229 13956 [] =/= subelements_with_nss(Packet, <<"private">>, carbon_namespaces()).
230
231 -spec is_received(exml:element()) -> boolean().
232 is_received(Packet) ->
233 13954 [] =/= subelements_with_nss(Packet, <<"received">>, carbon_namespaces()).
234
235 -spec is_sent(exml:element()) -> boolean().
236 is_sent(Packet) ->
237 13938 [] =/= subelements_with_nss(Packet, <<"sent">>, carbon_namespaces()).
238
239 -spec subelements_with_nss(exml:element(), binary(), [binary()]) -> [exml:element()].
240 subelements_with_nss(#xmlel{children = Children}, Name, NSS) ->
241 41848 lists:filter(fun(#xmlel{name = N} = Child) when N =:= Name ->
242 158 NS = exml_query:attr(Child, <<"xmlns">>),
243 158 lists:member(NS, NSS);
244 (_) ->
245 52087 false
246 end, Children).
247
248 41848 carbon_namespaces() -> [?NS_CC_1, ?NS_CC_2].
249
250 %%%===================================================================
251 %%% Internal
252 %%%===================================================================
253
254
255 %%
256 %% Internal
257 %%
258 is_bare_to(Direction, To, _PrioRes) ->
259 5019 case {Direction, To} of
260 264 {received, #jid{lresource = <<>>}} -> true;
261 4755 _ -> false
262 end.
263
264 max_prio(PrioRes) ->
265 48 case catch lists:max(PrioRes) of
266 48 {Prio, _Res} -> Prio;
267
:-(
_ -> 0
268 end.
269
270 is_max_prio(Res, PrioRes) ->
271 48 lists:member({max_prio(PrioRes), Res}, PrioRes).
272
273 jids_minus_max_priority_resource(JID, CCResList, PrioRes) ->
274 264 [ {jid:replace_resource(JID, CCRes), CCVersion}
275 264 || {CCVersion, CCRes} <- CCResList, not is_max_prio(CCRes, PrioRes) ].
276
277 jids_minus_specific_resource(JID, R, CCResList, _PrioRes) ->
278 4755 [ {jid:replace_resource(JID, CCRes), CCVersion}
279 4755 || {CCVersion, CCRes} <- CCResList, CCRes =/= R ].
280
281 %% Direction = received | sent <received xmlns='urn:xmpp:carbons:1'/>
282 send_copies(Acc, JID, To, Packet, Direction) ->
283 5019 #jid{lresource = R} = JID,
284 5019 {PrioRes, CCResList} = get_cc_enabled_resources(JID),
285 5019 Targets = case is_bare_to(Direction, To, PrioRes) of
286 264 true -> jids_minus_max_priority_resource
287 (JID, CCResList, PrioRes);
288 4755 _ -> jids_minus_specific_resource(JID, R, CCResList, PrioRes)
289 end,
290 5019 ?LOG_DEBUG(#{what => cc_send_copies,
291 5019 targets => Targets, resources => PrioRes, ccenabled => CCResList}),
292 5019 lists:foreach(fun({Dest, Version}) ->
293 28 ?LOG_DEBUG(#{what => cc_forwarding,
294 user => JID#jid.luser, server => JID#jid.lserver,
295 28 resource => JID#jid.lresource, exml_packet => Packet}),
296 28 Sender = jid:to_bare(JID),
297 28 New = build_forward_packet(Acc, JID, Packet, Sender, Dest, Direction, Version),
298 28 ejabberd_router:route(Sender, Dest, Acc, New)
299 end, Targets).
300
301 build_forward_packet(Acc, JID, Packet, Sender, Dest, Direction, Version) ->
302 % The wrapping message SHOULD maintain the same 'type' attribute value;
303 28 Type = exml_query:attr(Packet, <<"type">>, <<"normal">>),
304 28 #xmlel{name = <<"message">>,
305 attrs = [{<<"xmlns">>, <<"jabber:client">>},
306 {<<"type">>, Type},
307 {<<"from">>, jid:to_binary(Sender)},
308 {<<"to">>, jid:to_binary(Dest)}],
309 children = carbon_copy_children(Acc, Version, JID, Packet, Direction)}.
310
311 carbon_copy_children(Acc, ?NS_CC_1, JID, Packet, Direction) ->
312
:-(
[ #xmlel{name = atom_to_binary(Direction, utf8),
313 attrs = [{<<"xmlns">>, ?NS_CC_1}]},
314 #xmlel{name = <<"forwarded">>,
315 attrs = [{<<"xmlns">>, ?NS_FORWARD}],
316 children = [complete_packet(Acc, JID, Packet, Direction)]} ];
317 carbon_copy_children(Acc, ?NS_CC_2, JID, Packet, Direction) ->
318 28 [ #xmlel{name = atom_to_binary(Direction, utf8),
319 attrs = [{<<"xmlns">>, ?NS_CC_2}],
320 children = [ #xmlel{name = <<"forwarded">>,
321 attrs = [{<<"xmlns">>, ?NS_FORWARD}],
322 children = [complete_packet(Acc, JID, Packet, Direction)]} ]} ].
323
324 enable(JID, CC) ->
325 73 ?LOG_INFO(#{what => cc_enable,
326 73 user => JID#jid.luser, server => JID#jid.lserver}),
327 73 case ejabberd_sm:store_info(JID, ?CC_KEY, cc_ver_to_int(CC)) of
328 73 {ok, ?CC_KEY} -> ok;
329
:-(
{error, _} = Err -> Err
330 end.
331
332 disable(JID) ->
333 3937 ?LOG_INFO(#{what => cc_disable,
334 3937 user => JID#jid.luser, server => JID#jid.lserver}),
335 3937 case ejabberd_sm:remove_info(JID, ?CC_KEY) of
336 134 ok -> ok;
337 3803 {error, offline} -> ok
338 end.
339
340 complete_packet(Acc, From, #xmlel{name = <<"message">>, attrs = OrigAttrs} = Packet, sent) ->
341 %% if this is a packet sent by user on this host, then Packet doesn't
342 %% include the 'from' attribute. We must add it.
343 12 Attrs = lists:keystore(<<"xmlns">>, 1, OrigAttrs, {<<"xmlns">>, <<"jabber:client">>}),
344 12 Packet2 = set_stanza_id(Acc, From, Packet),
345 12 case proplists:get_value(<<"from">>, Attrs) of
346 undefined ->
347 12 Packet2#xmlel{attrs = [{<<"from">>, jid:to_binary(From)} | Attrs]};
348 _ ->
349
:-(
Packet2#xmlel{attrs = Attrs}
350 end;
351
352 complete_packet(_Acc, _From, #xmlel{name = <<"message">>, attrs = OrigAttrs} = Packet, received) ->
353 16 Attrs = lists:keystore(<<"xmlns">>, 1, OrigAttrs, {<<"xmlns">>, <<"jabber:client">>}),
354 16 Packet#xmlel{attrs = Attrs}.
355
356 get_cc_enabled_resources(JID) ->
357 5019 AllSessions = ejabberd_sm:get_raw_sessions(JID),
358 5019 CCs = filter_cc_enabled_resources(AllSessions),
359 5019 Prios = filter_priority_resources(AllSessions),
360 5019 {Prios, CCs}.
361
362 filter_cc_enabled_resources(AllSessions) ->
363 5019 lists:filtermap(fun fun_filter_cc_enabled_resource/1, AllSessions).
364
365 fun_filter_cc_enabled_resource(Session = #session{usr = {_, _, R}}) ->
366 5412 case mongoose_session:get_info(Session, ?CC_KEY, undefined) of
367 {?CC_KEY, V} when is_integer(V) ->
368 107 {true, {cc_ver_from_int(V), R}};
369 _ ->
370 5305 false
371 end.
372
373 filter_priority_resources(AllSessions) ->
374 5019 lists:filtermap(fun fun_filter_priority_resources/1, AllSessions).
375
376 fun_filter_priority_resources(#session{usr = {_, _, R}, priority = P})
377 when is_integer(P) ->
378 5387 {true, {P, R}};
379 fun_filter_priority_resources(_) ->
380 25 false.
381
382
:-(
cc_ver_to_int(?NS_CC_1) -> 1;
383 73 cc_ver_to_int(?NS_CC_2) -> 2.
384
385
:-(
cc_ver_from_int(1) -> ?NS_CC_1;
386 107 cc_ver_from_int(2) -> ?NS_CC_2.
387
388 %% Servers SHOULD include the element as a child
389 %% of the forwarded message when using Message Carbons (XEP-0280)
390 %% https://xmpp.org/extensions/xep-0313.html#archives_id
391 set_stanza_id(Acc, From, Packet) ->
392 12 MamId = mongoose_acc:get(mam, mam_id, undefined, Acc),
393 12 set_stanza_id(MamId, From, Acc, Packet).
394
395 set_stanza_id(undefined, _From, _Acc, Packet) ->
396 5 Packet;
397 set_stanza_id(MamId, From, _Acc, Packet) ->
398 7 By = jid:to_binary(jid:to_bare(From)),
399 7 mod_mam_utils:replace_arcid_elem(<<"stanza-id">>, By, MamId, Packet).
Line Hits Source