forked from processone/ejabberd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod_pubsub.erl
4378 lines (4145 loc) · 146 KB
/
mod_pubsub.erl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
%%% ====================================================================
%%% ``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 via the world wide web 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.
%%%
%%%
%%% The Initial Developer of the Original Code is ProcessOne.
%%% Portions created by ProcessOne are Copyright 2006-2015, ProcessOne
%%% All Rights Reserved.''
%%% This software is copyright 2006-2015, ProcessOne.
%%%
%%% @copyright 2006-2015 ProcessOne
%%% @author Christophe Romain <[email protected]>
%%% [http://www.process-one.net/]
%%% @version {@vsn}, {@date} {@time}
%%% @end
%%% ====================================================================
%%% @doc The module <strong>{@module}</strong> is the core of the PubSub
%%% extension. It relies on PubSub plugins for a large part of its functions.
%%%
%%% @headerfile "pubsub.hrl"
%%%
%%% @reference See <a href="http://www.xmpp.org/extensions/xep-0060.html">XEP-0060: Pubsub</a> for
%%% the latest version of the PubSub specification.
%%% This module uses version 1.12 of the specification as a base.
%%% Most of the specification is implemented.
%%% Functions concerning configuration should be rewritten.
%%%
%%% Support for subscription-options and multi-subscribe features was
%%% added by Brian Cully (bjc AT kublai.com). Subscriptions and options are
%%% stored in the pubsub_subscription table, with a link to them provided
%%% by the subscriptions field of pubsub_state. For information on
%%% subscription-options and mulit-subscribe see XEP-0060 sections 6.1.6,
%%% 6.2.3.1, 6.2.3.5, and 6.3. For information on subscription leases see
%%% XEP-0060 section 12.18.
-module(mod_pubsub).
-behaviour(gen_mod).
-behaviour(gen_server).
-author('[email protected]').
-protocol({xep, 60, '1.13-1'}).
-protocol({xep, 163, '1.2'}).
-protocol({xep, 248, '0.2'}).
-include("ejabberd.hrl").
-include("logger.hrl").
-include("adhoc.hrl").
-include("jlib.hrl").
-include("pubsub.hrl").
-define(STDTREE, <<"tree">>).
-define(STDNODE, <<"flat">>).
-define(PEPNODE, <<"pep">>).
%% exports for hooks
-export([presence_probe/3, caps_add/3, caps_update/3,
in_subscription/6, out_subscription/4,
on_user_offline/3, remove_user/2,
disco_local_identity/5, disco_local_features/5,
disco_local_items/5, disco_sm_identity/5,
disco_sm_features/5, disco_sm_items/5]).
%% exported iq handlers
-export([iq_sm/3]).
%% exports for console debug manual use
-export([create_node/5, create_node/7, delete_node/3,
subscribe_node/5, unsubscribe_node/5, publish_item/6,
delete_item/4, send_items/7, get_items/2, get_item/3,
get_cached_item/2, get_configure/5, set_configure/5,
tree_action/3, node_action/4, node_call/4]).
%% general helpers for plugins
-export([subscription_to_string/1, affiliation_to_string/1,
string_to_subscription/1, string_to_affiliation/1,
extended_error/2, extended_error/3, service_jid/1,
tree/1, tree/2, plugin/2, config/3, host/1, serverhost/1]).
%% API and gen_server callbacks
-export([start_link/2, start/2, stop/1, init/1,
handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-export([send_loop/1, mod_opt_type/1]).
-define(PROCNAME, ejabberd_mod_pubsub).
-define(LOOPNAME, ejabberd_mod_pubsub_loop).
%%====================================================================
%% API
%%====================================================================
%%--------------------------------------------------------------------
%% Function: start_link() -> {ok,Pid} | ignore | {error,Error}
%% Description: Starts the server
%%--------------------------------------------------------------------
-export_type([
host/0,
hostPubsub/0,
hostPEP/0,
%%
nodeIdx/0,
nodeId/0,
itemId/0,
subId/0,
payload/0,
%%
nodeOption/0,
nodeOptions/0,
subOption/0,
subOptions/0,
%%
affiliation/0,
subscription/0,
accessModel/0,
publishModel/0
]).
%% -type payload() defined here because the -type xmlel() is not accessible
%% from pubsub.hrl
-type(payload() :: [] | [xmlel(),...]).
-export_type([
pubsubNode/0,
pubsubState/0,
pubsubItem/0,
pubsubSubscription/0,
pubsubLastItem/0
]).
-type(pubsubNode() ::
#pubsub_node{
nodeid :: {Host::mod_pubsub:host(), Node::mod_pubsub:nodeId()},
id :: Nidx::mod_pubsub:nodeIdx(),
parents :: [Node::mod_pubsub:nodeId()],
type :: Type::binary(),
owners :: [Owner::ljid(),...],
options :: Opts::mod_pubsub:nodeOptions()
}
).
-type(pubsubState() ::
#pubsub_state{
stateid :: {Entity::ljid(), Nidx::mod_pubsub:nodeIdx()},
items :: [ItemId::mod_pubsub:itemId()],
affiliation :: Affs::mod_pubsub:affiliation(),
subscriptions :: [{Sub::mod_pubsub:subscription(), SubId::mod_pubsub:subId()}]
}
).
-type(pubsubItem() ::
#pubsub_item{
itemid :: {ItemId::mod_pubsub:itemId(), Nidx::mod_pubsub:nodeIdx()},
creation :: {erlang:timestamp(), ljid()},
modification :: {erlang:timestamp(), ljid()},
payload :: mod_pubsub:payload()
}
).
-type(pubsubSubscription() ::
#pubsub_subscription{
subid :: SubId::mod_pubsub:subId(),
options :: [] | mod_pubsub:subOptions()
}
).
-type(pubsubLastItem() ::
#pubsub_last_item{
nodeid :: mod_pubsub:nodeIdx(),
itemid :: mod_pubsub:itemId(),
creation :: {erlang:timestamp(), ljid()},
payload :: mod_pubsub:payload()
}
).
-record(state,
{
server_host,
host,
access,
pep_mapping = [],
ignore_pep_from_offline = true,
last_item_cache = false,
max_items_node = ?MAXITEMS,
nodetree = <<"nodetree_", (?STDTREE)/binary>>,
plugins = [?STDNODE],
db_type
}).
-type(state() ::
#state{
server_host :: binary(),
host :: mod_pubsub:hostPubsub(),
access :: atom(),
pep_mapping :: [{binary(), binary()}],
ignore_pep_from_offline :: boolean(),
last_item_cache :: boolean(),
max_items_node :: non_neg_integer(),
nodetree :: binary(),
plugins :: [binary(),...],
db_type :: atom()
}
).
start_link(Host, Opts) ->
Proc = gen_mod:get_module_proc(Host, ?PROCNAME),
gen_server:start_link({local, Proc}, ?MODULE, [Host, Opts], []).
start(Host, Opts) ->
Proc = gen_mod:get_module_proc(Host, ?PROCNAME),
ChildSpec = {Proc, {?MODULE, start_link, [Host, Opts]},
transient, 1000, worker, [?MODULE]},
supervisor:start_child(ejabberd_sup, ChildSpec).
stop(Host) ->
Proc = gen_mod:get_module_proc(Host, ?PROCNAME),
gen_server:call(Proc, stop),
supervisor:delete_child(ejabberd_sup, Proc).
%%====================================================================
%% gen_server callbacks
%%====================================================================
%%--------------------------------------------------------------------
%% Function: init(Args) -> {ok, State} |
%% {ok, State, Timeout} |
%% ignore |
%% {stop, Reason}
%% Description: Initiates the server
%%--------------------------------------------------------------------
-spec(init/1 ::
(
[binary() | [{_,_}],...])
-> {'ok',state()}
).
init([ServerHost, Opts]) ->
?DEBUG("pubsub init ~p ~p", [ServerHost, Opts]),
Host = gen_mod:get_opt_host(ServerHost, Opts, <<"pubsub.@HOST@">>),
Access = gen_mod:get_opt(access_createnode, Opts,
fun(A) when is_atom(A) -> A end, all),
PepOffline = gen_mod:get_opt(ignore_pep_from_offline, Opts,
fun(A) when is_boolean(A) -> A end, true),
IQDisc = gen_mod:get_opt(iqdisc, Opts,
fun gen_iq_handler:check_type/1, one_queue),
LastItemCache = gen_mod:get_opt(last_item_cache, Opts,
fun(A) when is_boolean(A) -> A end, false),
MaxItemsNode = gen_mod:get_opt(max_items_node, Opts,
fun(A) when is_integer(A) andalso A >= 0 -> A end, ?MAXITEMS),
pubsub_index:init(Host, ServerHost, Opts),
ets:new(gen_mod:get_module_proc(ServerHost, config), [set, named_table]),
{Plugins, NodeTree, PepMapping} = init_plugins(Host, ServerHost, Opts),
mnesia:create_table(pubsub_last_item,
[{ram_copies, [node()]},
{attributes, record_info(fields, pubsub_last_item)}]),
mod_disco:register_feature(ServerHost, ?NS_PUBSUB),
ets:insert(gen_mod:get_module_proc(ServerHost, config), {nodetree, NodeTree}),
ets:insert(gen_mod:get_module_proc(ServerHost, config), {plugins, Plugins}),
ets:insert(gen_mod:get_module_proc(ServerHost, config), {last_item_cache, LastItemCache}),
ets:insert(gen_mod:get_module_proc(ServerHost, config), {max_items_node, MaxItemsNode}),
ets:insert(gen_mod:get_module_proc(ServerHost, config), {pep_mapping, PepMapping}),
ets:insert(gen_mod:get_module_proc(ServerHost, config), {ignore_pep_from_offline, PepOffline}),
ets:insert(gen_mod:get_module_proc(ServerHost, config), {host, Host}),
ets:insert(gen_mod:get_module_proc(ServerHost, config), {access, Access}),
ejabberd_hooks:add(sm_remove_connection_hook, ServerHost,
?MODULE, on_user_offline, 75),
ejabberd_hooks:add(disco_local_identity, ServerHost,
?MODULE, disco_local_identity, 75),
ejabberd_hooks:add(disco_local_features, ServerHost,
?MODULE, disco_local_features, 75),
ejabberd_hooks:add(disco_local_items, ServerHost,
?MODULE, disco_local_items, 75),
ejabberd_hooks:add(presence_probe_hook, ServerHost,
?MODULE, presence_probe, 80),
ejabberd_hooks:add(roster_in_subscription, ServerHost,
?MODULE, in_subscription, 50),
ejabberd_hooks:add(roster_out_subscription, ServerHost,
?MODULE, out_subscription, 50),
ejabberd_hooks:add(remove_user, ServerHost,
?MODULE, remove_user, 50),
ejabberd_hooks:add(anonymous_purge_hook, ServerHost,
?MODULE, remove_user, 50),
case lists:member(?PEPNODE, Plugins) of
true ->
ejabberd_hooks:add(caps_add, ServerHost,
?MODULE, caps_add, 80),
ejabberd_hooks:add(caps_update, ServerHost,
?MODULE, caps_update, 80),
ejabberd_hooks:add(disco_sm_identity, ServerHost,
?MODULE, disco_sm_identity, 75),
ejabberd_hooks:add(disco_sm_features, ServerHost,
?MODULE, disco_sm_features, 75),
ejabberd_hooks:add(disco_sm_items, ServerHost,
?MODULE, disco_sm_items, 75),
gen_iq_handler:add_iq_handler(ejabberd_sm, ServerHost,
?NS_PUBSUB, ?MODULE, iq_sm, IQDisc),
gen_iq_handler:add_iq_handler(ejabberd_sm, ServerHost,
?NS_PUBSUB_OWNER, ?MODULE, iq_sm, IQDisc);
false ->
ok
end,
ejabberd_router:register_route(Host),
pubsub_migrate:update_node_database(Host, ServerHost),
pubsub_migrate:update_state_database(Host, ServerHost),
pubsub_migrate:update_lastitem_database(Host, ServerHost),
{_, State} = init_send_loop(ServerHost),
{ok, State}.
init_send_loop(ServerHost) ->
NodeTree = config(ServerHost, nodetree),
Plugins = config(ServerHost, plugins),
LastItemCache = config(ServerHost, last_item_cache),
MaxItemsNode = config(ServerHost, max_items_node),
PepMapping = config(ServerHost, pep_mapping),
PepOffline = config(ServerHost, ignore_pep_from_offline),
Host = config(ServerHost, host),
Access = config(ServerHost, access),
DBType = gen_mod:db_type(ServerHost, ?MODULE),
State = #state{host = Host, server_host = ServerHost,
access = Access, pep_mapping = PepMapping,
ignore_pep_from_offline = PepOffline,
last_item_cache = LastItemCache,
max_items_node = MaxItemsNode, nodetree = NodeTree,
plugins = Plugins, db_type = DBType},
Proc = gen_mod:get_module_proc(ServerHost, ?LOOPNAME),
Pid = case whereis(Proc) of
undefined ->
SendLoop = spawn(?MODULE, send_loop, [State]),
register(Proc, SendLoop),
SendLoop;
Loop ->
Loop
end,
{Pid, State}.
%% @doc Call the init/1 function for each plugin declared in the config file.
%% The default plugin module is implicit.
%% <p>The Erlang code for the plugin is located in a module called
%% <em>node_plugin</em>. The 'node_' prefix is mandatory.</p>
%% <p>The modules are initialized in alphetical order and the list is checked
%% and sorted to ensure that each module is initialized only once.</p>
%% <p>See {@link node_hometree:init/1} for an example implementation.</p>
init_plugins(Host, ServerHost, Opts) ->
TreePlugin = tree(Host, gen_mod:get_opt(nodetree, Opts,
fun(A) when is_binary(A) -> A end,
?STDTREE)),
?DEBUG("** tree plugin is ~p", [TreePlugin]),
TreePlugin:init(Host, ServerHost, Opts),
Plugins = gen_mod:get_opt(plugins, Opts,
fun(A) when is_list(A) -> A end, [?STDNODE]),
PepMapping = gen_mod:get_opt(pep_mapping, Opts,
fun(A) when is_list(A) -> A end, []),
?DEBUG("** PEP Mapping : ~p~n", [PepMapping]),
PluginsOK = lists:foldl(
fun (Name, Acc) ->
Plugin = plugin(Host, Name),
case catch apply(Plugin, init, [Host, ServerHost, Opts]) of
{'EXIT', _Error} ->
Acc;
_ ->
?DEBUG("** init ~s plugin", [Name]),
[Name | Acc]
end
end,
[], Plugins),
{lists:reverse(PluginsOK), TreePlugin, PepMapping}.
terminate_plugins(Host, ServerHost, Plugins, TreePlugin) ->
lists:foreach(
fun (Name) ->
?DEBUG("** terminate ~s plugin", [Name]),
Plugin = plugin(Host, Name),
Plugin:terminate(Host, ServerHost)
end,
Plugins),
TreePlugin:terminate(Host, ServerHost),
ok.
send_loop(State) ->
receive
{presence, JID, Pid} ->
Host = State#state.host,
ServerHost = State#state.server_host,
DBType = State#state.db_type,
LJID = jlib:jid_tolower(JID),
BJID = jlib:jid_remove_resource(LJID),
lists:foreach(
fun(PType) ->
Subs = get_subscriptions_for_send_last(Host, PType, DBType, JID, LJID, BJID),
lists:foreach(
fun({NodeRec, _, _, SubJID}) ->
{_, Node} = NodeRec#pubsub_node.nodeid,
Nidx = NodeRec#pubsub_node.id,
Options = NodeRec#pubsub_node.options,
send_items(Host, Node, Nidx, PType, Options, SubJID, last)
end,
lists:usort(Subs))
end,
State#state.plugins),
if not State#state.ignore_pep_from_offline ->
{User, Server, Resource} = LJID,
case catch ejabberd_c2s:get_subscribed(Pid) of
Contacts when is_list(Contacts) ->
lists:foreach(
fun({U, S, R}) when S == ServerHost ->
case user_resources(U, S) of
[] -> %% offline
PeerJID = jlib:make_jid(U, S, R),
self() ! {presence, User, Server, [Resource], PeerJID};
_ -> %% online
% this is already handled by presence probe
ok
end;
(_) ->
% we can not do anything in any cases
ok
end,
Contacts);
_ ->
ok
end;
true ->
ok
end,
send_loop(State);
{presence, User, Server, Resources, JID} ->
spawn(fun() ->
Host = State#state.host,
Owner = jlib:jid_remove_resource(jlib:jid_tolower(JID)),
lists:foreach(fun(#pubsub_node{nodeid = {_, Node}, type = Type, id = Nidx, options = Options}) ->
case match_option(Options, send_last_published_item, on_sub_and_presence) of
true ->
lists:foreach(fun(Resource) ->
LJID = {User, Server, Resource},
Subscribed = case get_option(Options, access_model) of
open -> true;
presence -> true;
whitelist -> false; % subscribers are added manually
authorize -> false; % likewise
roster ->
Grps = get_option(Options, roster_groups_allowed, []),
{OU, OS, _} = Owner,
element(2, get_roster_info(OU, OS, LJID, Grps))
end,
if Subscribed -> send_items(Owner, Node, Nidx, Type, Options, LJID, last);
true -> ok
end
end,
Resources);
_ ->
ok
end
end,
tree_action(Host, get_nodes, [Owner, JID]))
end),
send_loop(State);
stop ->
ok
end.
%% -------
%% disco hooks handling functions
%%
-spec(disco_local_identity/5 ::
(
Acc :: [xmlel()],
_From :: jid(),
To :: jid(),
Node :: <<>> | mod_pubsub:nodeId(),
Lang :: binary())
-> [xmlel()]
).
disco_local_identity(Acc, _From, To, <<>>, _Lang) ->
case lists:member(?PEPNODE, plugins(To#jid.lserver)) of
true ->
[#xmlel{name = <<"identity">>,
attrs = [{<<"category">>, <<"pubsub">>},
{<<"type">>, <<"pep">>}]}
| Acc];
false ->
Acc
end;
disco_local_identity(Acc, _From, _To, _Node, _Lang) ->
Acc.
-spec(disco_local_features/5 ::
(
Acc :: [xmlel()],
_From :: jid(),
To :: jid(),
Node :: <<>> | mod_pubsub:nodeId(),
Lang :: binary())
-> [binary(),...]
).
disco_local_features(Acc, _From, To, <<>>, _Lang) ->
Host = To#jid.lserver,
Feats = case Acc of
{result, I} -> I;
_ -> []
end,
{result, Feats ++ [feature(F) || F <- features(Host, <<>>)]};
disco_local_features(Acc, _From, _To, _Node, _Lang) ->
Acc.
disco_local_items(Acc, _From, _To, <<>>, _Lang) -> Acc;
disco_local_items(Acc, _From, _To, _Node, _Lang) -> Acc.
%disco_sm_identity(Acc, From, To, Node, Lang)
% when is_binary(Node) ->
% disco_sm_identity(Acc, From, To, iolist_to_binary(Node),
% Lang);
-spec(disco_sm_identity/5 ::
(
Acc :: empty | [xmlel()],
From :: jid(),
To :: jid(),
Node :: mod_pubsub:nodeId(),
Lang :: binary())
-> [xmlel()]
).
disco_sm_identity(empty, From, To, Node, Lang) ->
disco_sm_identity([], From, To, Node, Lang);
disco_sm_identity(Acc, From, To, Node, _Lang) ->
disco_identity(jlib:jid_tolower(jlib:jid_remove_resource(To)), Node, From)
++ Acc.
disco_identity(_Host, <<>>, _From) ->
[#xmlel{name = <<"identity">>,
attrs = [{<<"category">>, <<"pubsub">>},
{<<"type">>, <<"pep">>}]}];
disco_identity(Host, Node, From) ->
Action = fun (#pubsub_node{id = Nidx, type = Type, options = Options, owners = O}) ->
Owners = node_owners_call(Host, Type, Nidx, O),
case get_allowed_items_call(Host, Nidx, From, Type, Options, Owners) of
{result, _} ->
{result, [#xmlel{name = <<"identity">>,
attrs = [{<<"category">>, <<"pubsub">>},
{<<"type">>, <<"pep">>}]},
#xmlel{name = <<"identity">>,
attrs = [{<<"category">>, <<"pubsub">>},
{<<"type">>, <<"leaf">>}
| case get_option(Options, title) of
false -> [];
[Title] -> [{<<"name">>, Title}]
end]}]};
_ ->
{result, []}
end
end,
case transaction(Host, Node, Action, sync_dirty) of
{result, {_, Result}} -> Result;
_ -> []
end.
-spec(disco_sm_features/5 ::
(
Acc :: empty | {result, Features::[Feature::binary()]},
From :: jid(),
To :: jid(),
Node :: mod_pubsub:nodeId(),
Lang :: binary())
-> {result, Features::[Feature::binary()]}
).
%disco_sm_features(Acc, From, To, Node, Lang)
% when is_binary(Node) ->
% disco_sm_features(Acc, From, To, iolist_to_binary(Node),
% Lang);
disco_sm_features(empty, From, To, Node, Lang) ->
disco_sm_features({result, []}, From, To, Node, Lang);
disco_sm_features({result, OtherFeatures} = _Acc, From, To, Node, _Lang) ->
{result,
OtherFeatures ++
disco_features(jlib:jid_tolower(jlib:jid_remove_resource(To)), Node, From)};
disco_sm_features(Acc, _From, _To, _Node, _Lang) -> Acc.
disco_features(Host, <<>>, _From) ->
[?NS_PUBSUB | [feature(F) || F <- plugin_features(Host, <<"pep">>)]];
disco_features(Host, Node, From) ->
Action = fun (#pubsub_node{id = Nidx, type = Type, options = Options, owners = O}) ->
Owners = node_owners_call(Host, Type, Nidx, O),
case get_allowed_items_call(Host, Nidx, From, Type, Options, Owners) of
{result, _} -> {result, [?NS_PUBSUB | [feature(F) || F <- plugin_features(Host, <<"pep">>)]]};
_ -> {result, []}
end
end,
case transaction(Host, Node, Action, sync_dirty) of
{result, {_, Result}} -> Result;
_ -> []
end.
-spec(disco_sm_items/5 ::
(
Acc :: empty | {result, [xmlel()]},
From :: jid(),
To :: jid(),
Node :: mod_pubsub:nodeId(),
Lang :: binary())
-> {result, [xmlel()]}
).
%disco_sm_items(Acc, From, To, Node, Lang)
% when is_binary(Node) ->
% disco_sm_items(Acc, From, To, iolist_to_binary(Node),
% Lang);
disco_sm_items(empty, From, To, Node, Lang) ->
disco_sm_items({result, []}, From, To, Node, Lang);
disco_sm_items({result, OtherItems}, From, To, Node, _Lang) ->
{result, lists:usort(OtherItems ++
disco_items(jlib:jid_tolower(jlib:jid_remove_resource(To)), Node, From))};
disco_sm_items(Acc, _From, _To, _Node, _Lang) -> Acc.
-spec(disco_items/3 ::
(
Host :: mod_pubsub:host(),
Node :: mod_pubsub:nodeId(),
From :: jid())
-> [xmlel()]
).
disco_items(Host, <<>>, From) ->
Action = fun (#pubsub_node{nodeid = {_, Node},
options = Options, type = Type, id = Nidx, owners = O},
Acc) ->
Owners = node_owners_call(Host, Type, Nidx, O),
case get_allowed_items_call(Host, Nidx, From, Type, Options, Owners) of
{result, _} ->
[#xmlel{name = <<"item">>,
attrs = [{<<"node">>, (Node)},
{<<"jid">>, jlib:jid_to_string(Host)}
| case get_option(Options, title) of
false -> [];
[Title] -> [{<<"name">>, Title}]
end]}
| Acc];
_ ->
Acc
end
end,
NodeBloc = fun() ->
{result,
lists:foldl(Action, [], tree_call(Host, get_nodes, [Host]))}
end,
case transaction(Host, NodeBloc, sync_dirty) of
{result, Items} -> Items;
_ -> []
end;
disco_items(Host, Node, From) ->
Action = fun (#pubsub_node{id = Nidx, type = Type, options = Options, owners = O}) ->
Owners = node_owners_call(Host, Type, Nidx, O),
case get_allowed_items_call(Host, Nidx, From, Type, Options, Owners) of
{result, Items} ->
{result, [#xmlel{name = <<"item">>,
attrs = [{<<"jid">>, jlib:jid_to_string(Host)},
{<<"name">>, ItemId}]}
|| #pubsub_item{itemid = {ItemId, _}} <- Items]};
_ ->
{result, []}
end
end,
case transaction(Host, Node, Action, sync_dirty) of
{result, {_, Result}} -> Result;
_ -> []
end.
%% -------
%% presence hooks handling functions
%%
caps_add(#jid{luser = U, lserver = S, lresource = R}, #jid{lserver = Host} = JID, _Features)
when Host =/= S ->
%% When a remote contact goes online while the local user is offline, the
%% remote contact won't receive last items from the local user even if
%% ignore_pep_from_offline is set to false. To work around this issue a bit,
%% we'll also send the last items to remote contacts when the local user
%% connects. That's the reason to use the caps_add hook instead of the
%% presence_probe_hook for remote contacts: The latter is only called when a
%% contact becomes available; the former is also executed when the local
%% user goes online (because that triggers the contact to send a presence
%% packet with CAPS).
presence(Host, {presence, U, S, [R], JID});
caps_add(_From, _To, _Feature) ->
ok.
caps_update(#jid{luser = U, lserver = S, lresource = R}, #jid{lserver = Host} = JID, _Features) ->
presence(Host, {presence, U, S, [R], JID}).
presence_probe(#jid{luser = U, lserver = S, lresource = R} = JID, JID, Pid) ->
presence(S, {presence, JID, Pid}),
presence(S, {presence, U, S, [R], JID});
presence_probe(#jid{luser = U, lserver = S}, #jid{luser = U, lserver = S}, _Pid) ->
%% ignore presence_probe from my other ressources
%% to not get duplicated last items
ok;
presence_probe(#jid{luser = U, lserver = S, lresource = R}, #jid{lserver = S} = JID, _Pid) ->
presence(S, {presence, U, S, [R], JID});
presence_probe(_Host, _JID, _Pid) ->
%% ignore presence_probe from remote contacts,
%% those are handled via caps_add
ok.
presence(ServerHost, Presence) ->
{SendLoop, _} = case whereis(gen_mod:get_module_proc(ServerHost, ?LOOPNAME)) of
undefined -> init_send_loop(ServerHost);
Pid -> {Pid, undefined}
end,
SendLoop ! Presence.
%% -------
%% subscription hooks handling functions
%%
out_subscription(User, Server, JID, subscribed) ->
Owner = jlib:make_jid(User, Server, <<>>),
{PUser, PServer, PResource} = jlib:jid_tolower(JID),
PResources = case PResource of
<<>> -> user_resources(PUser, PServer);
_ -> [PResource]
end,
presence(Server, {presence, PUser, PServer, PResources, Owner}),
true;
out_subscription(_, _, _, _) ->
true.
in_subscription(_, User, Server, Owner, unsubscribed, _) ->
unsubscribe_user(jlib:make_jid(User, Server, <<>>), Owner),
true;
in_subscription(_, _, _, _, _, _) ->
true.
unsubscribe_user(Entity, Owner) ->
spawn(fun () ->
[unsubscribe_user(ServerHost, Entity, Owner) ||
ServerHost <- lists:usort(lists:foldl(
fun(UserHost, Acc) ->
case gen_mod:is_loaded(UserHost, mod_pubsub) of
true -> [UserHost|Acc];
false -> Acc
end
end, [], [Entity#jid.lserver, Owner#jid.lserver]))]
end).
unsubscribe_user(Host, Entity, Owner) ->
BJID = jlib:jid_tolower(jlib:jid_remove_resource(Owner)),
lists:foreach(fun (PType) ->
{result, Subs} = node_action(Host, PType,
get_entity_subscriptions,
[Host, Entity]),
lists:foreach(fun
({#pubsub_node{options = Options,
owners = O,
id = Nidx},
subscribed, _, JID}) ->
Unsubscribe = match_option(Options, access_model, presence)
andalso lists:member(BJID, node_owners_action(Host, PType, Nidx, O)),
case Unsubscribe of
true ->
node_action(Host, PType,
unsubscribe_node, [Nidx, Entity, JID, all]);
false ->
ok
end;
(_) ->
ok
end,
Subs)
end,
plugins(Host)).
%% -------
%% user remove hook handling function
%%
remove_user(User, Server) ->
LUser = jlib:nodeprep(User),
LServer = jlib:nameprep(Server),
Entity = jlib:make_jid(LUser, LServer, <<>>),
Host = host(LServer),
HomeTreeBase = <<"/home/", LServer/binary, "/", LUser/binary>>,
spawn(fun () ->
lists:foreach(fun (PType) ->
{result, Subs} = node_action(Host, PType,
get_entity_subscriptions,
[Host, Entity]),
lists:foreach(fun
({#pubsub_node{id = Nidx}, _, _, JID}) ->
node_action(Host, PType,
unsubscribe_node,
[Nidx, Entity, JID, all]);
(_) ->
ok
end,
Subs),
{result, Affs} = node_action(Host, PType,
get_entity_affiliations,
[Host, Entity]),
lists:foreach(fun
({#pubsub_node{nodeid = {H, N}, parents = []}, owner}) ->
delete_node(H, N, Entity);
({#pubsub_node{nodeid = {H, N}, type = Type}, owner})
when N == HomeTreeBase, Type == <<"hometree">> ->
delete_node(H, N, Entity);
({#pubsub_node{id = Nidx}, publisher}) ->
node_action(Host, PType,
set_affiliation,
[Nidx, Entity, none]);
(_) ->
ok
end,
Affs)
end,
plugins(Host))
end).
handle_call(server_host, _From, State) ->
{reply, State#state.server_host, State};
handle_call(plugins, _From, State) ->
{reply, State#state.plugins, State};
handle_call(pep_mapping, _From, State) ->
{reply, State#state.pep_mapping, State};
handle_call(nodetree, _From, State) ->
{reply, State#state.nodetree, State};
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
%%--------------------------------------------------------------------
%% @private
handle_cast(_Msg, State) -> {noreply, State}.
-spec(handle_info/2 ::
(
_ :: {route, From::jid(), To::jid(), Packet::xmlel()},
State :: state())
-> {noreply, state()}
).
%%--------------------------------------------------------------------
%% Function: handle_info(Info, State) -> {noreply, State} |
%% {noreply, State, Timeout} |
%% {stop, Reason, State}
%% Description: Handling all non call/cast messages
%%--------------------------------------------------------------------
%% @private
handle_info({route, From, To, Packet},
#state{server_host = ServerHost, access = Access, plugins = Plugins} = State) ->
case catch do_route(ServerHost, Access, Plugins, To#jid.lserver, From, To, Packet) of
{'EXIT', Reason} -> ?ERROR_MSG("~p", [Reason]);
_ -> ok
end,
{noreply, State};
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.
%%--------------------------------------------------------------------
%% @private
terminate(_Reason,
#state{host = Host, server_host = ServerHost, nodetree = TreePlugin, plugins = Plugins}) ->
ejabberd_router:unregister_route(Host),
case lists:member(?PEPNODE, Plugins) of
true ->
ejabberd_hooks:delete(caps_add, ServerHost,
?MODULE, caps_add, 80),
ejabberd_hooks:delete(caps_update, ServerHost,
?MODULE, caps_update, 80),
ejabberd_hooks:delete(disco_sm_identity, ServerHost,
?MODULE, disco_sm_identity, 75),
ejabberd_hooks:delete(disco_sm_features, ServerHost,
?MODULE, disco_sm_features, 75),
ejabberd_hooks:delete(disco_sm_items, ServerHost,
?MODULE, disco_sm_items, 75),
gen_iq_handler:remove_iq_handler(ejabberd_sm,
ServerHost, ?NS_PUBSUB),
gen_iq_handler:remove_iq_handler(ejabberd_sm,
ServerHost, ?NS_PUBSUB_OWNER);
false ->
ok
end,
ejabberd_hooks:delete(sm_remove_connection_hook, ServerHost,
?MODULE, on_user_offline, 75),
ejabberd_hooks:delete(disco_local_identity, ServerHost,
?MODULE, disco_local_identity, 75),
ejabberd_hooks:delete(disco_local_features, ServerHost,
?MODULE, disco_local_features, 75),
ejabberd_hooks:delete(disco_local_items, ServerHost,
?MODULE, disco_local_items, 75),
ejabberd_hooks:delete(presence_probe_hook, ServerHost,
?MODULE, presence_probe, 80),
ejabberd_hooks:delete(roster_in_subscription, ServerHost,
?MODULE, in_subscription, 50),
ejabberd_hooks:delete(roster_out_subscription, ServerHost,
?MODULE, out_subscription, 50),
ejabberd_hooks:delete(remove_user, ServerHost,
?MODULE, remove_user, 50),
ejabberd_hooks:delete(anonymous_purge_hook, ServerHost,
?MODULE, remove_user, 50),
mod_disco:unregister_feature(ServerHost, ?NS_PUBSUB),
case whereis(gen_mod:get_module_proc(ServerHost, ?LOOPNAME)) of
undefined ->
?ERROR_MSG("~s process is dead, pubsub was broken", [?LOOPNAME]);
Pid ->
Pid ! stop
end,
terminate_plugins(Host, ServerHost, Plugins, TreePlugin).
%%--------------------------------------------------------------------
%% Func: code_change(OldVsn, State, Extra) -> {ok, NewState}
%% Description: Convert process state when code is changed
%%--------------------------------------------------------------------
%% @private
code_change(_OldVsn, State, _Extra) -> {ok, State}.
-spec(do_route/7 ::
(
ServerHost :: binary(),
Access :: atom(),
Plugins :: [binary(),...],
Host :: mod_pubsub:hostPubsub(),
From :: jid(),
To :: jid(),
Packet :: xmlel())
-> ok
).
%%--------------------------------------------------------------------
%%% Internal functions
%%--------------------------------------------------------------------
do_route(ServerHost, Access, Plugins, Host, From, To, Packet) ->
#xmlel{name = Name, attrs = Attrs} = Packet,
case To of
#jid{luser = <<>>, lresource = <<>>} ->
case Name of
<<"iq">> ->
case jlib:iq_query_info(Packet) of
#iq{type = get, xmlns = ?NS_DISCO_INFO, sub_el = SubEl, lang = Lang} = IQ ->
#xmlel{attrs = QAttrs} = SubEl,
Node = xml:get_attr_s(<<"node">>, QAttrs),
Info = ejabberd_hooks:run_fold(disco_info, ServerHost,
[],
[ServerHost, ?MODULE, <<>>, <<>>]),
Res = case iq_disco_info(Host, Node, From, Lang) of
{result, IQRes} ->
jlib:iq_to_xml(IQ#iq{type = result,
sub_el =
[#xmlel{name = <<"query">>,
attrs = QAttrs,
children = IQRes ++ Info}]});
{error, Error} ->
jlib:make_error_reply(Packet, Error)
end,
ejabberd_router:route(To, From, Res);
#iq{type = get, xmlns = ?NS_DISCO_ITEMS, sub_el = SubEl} = IQ ->
#xmlel{attrs = QAttrs} = SubEl,
Node = xml:get_attr_s(<<"node">>, QAttrs),
Res = case iq_disco_items(Host, Node, From, jlib:rsm_decode(IQ)) of
{result, IQRes} ->
jlib:iq_to_xml(IQ#iq{type = result,
sub_el =
[#xmlel{name = <<"query">>,
attrs = QAttrs,
children = IQRes}]})
%{error, Error} ->
% jlib:make_error_reply(Packet, Error)
end,
ejabberd_router:route(To, From, Res);
#iq{type = IQType, xmlns = ?NS_PUBSUB, lang = Lang, sub_el = SubEl} = IQ ->
Res = case iq_pubsub(Host, ServerHost, From, IQType,
SubEl, Lang, Access, Plugins)
of
{result, IQRes} ->
jlib:iq_to_xml(IQ#iq{type = result, sub_el = IQRes});
{error, Error} ->
jlib:make_error_reply(Packet, Error)
end,
ejabberd_router:route(To, From, Res);
#iq{type = IQType, xmlns = ?NS_PUBSUB_OWNER, lang = Lang, sub_el = SubEl} = IQ ->
Res = case iq_pubsub_owner(Host, ServerHost, From,
IQType, SubEl, Lang)
of
{result, IQRes} ->
jlib:iq_to_xml(IQ#iq{type = result, sub_el = IQRes});
{error, Error} ->