mod_pep: Handle service discovery queries for bare account JIDs (thanks darkrain).
[prosody.git] / plugins / mod_pep.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 Waqas Hussain
4 -- 
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8
9
10 local jid_bare = require "util.jid".bare;
11 local jid_split = require "util.jid".split;
12 local st = require "util.stanza";
13 local hosts = hosts;
14 local user_exists = require "core.usermanager".user_exists;
15 local is_contact_subscribed = require "core.rostermanager".is_contact_subscribed;
16 local pairs, ipairs = pairs, ipairs;
17 local next = next;
18 local type = type;
19 local load_roster = require "core.rostermanager".load_roster;
20 local sha1 = require "util.hashes".sha1;
21 local base64 = require "util.encodings".base64.encode;
22
23 local NULL = {};
24 local data = {};
25 local recipients = {};
26 local hash_map = {};
27
28 module.save = function()
29         return { data = data, recipients = recipients, hash_map = hash_map };
30 end
31 module.restore = function(state)
32         data = state.data or {};
33         recipients = state.recipients or {};
34         hash_map = state.hash_map or {};
35 end
36
37 module:add_identity("pubsub", "pep", "Prosody");
38 module:add_feature("http://jabber.org/protocol/pubsub#publish");
39
40 local function subscription_presence(user_bare, recipient)
41         local recipient_bare = jid_bare(recipient);
42         if (recipient_bare == user_bare) then return true end
43         local item = load_roster(jid_split(user_bare))[recipient_bare];
44         return item and (item.subscription == 'from' or item.subscription == 'both');
45 end
46
47 local function publish(session, node, id, item)
48         item.attr.xmlns = nil;
49         local disable = #item.tags ~= 1 or #item.tags[1] == 0;
50         if #item.tags == 0 then item.name = "retract"; end
51         local bare = session.username..'@'..session.host;
52         local stanza = st.message({from=bare, type='headline'})
53                 :tag('event', {xmlns='http://jabber.org/protocol/pubsub#event'})
54                         :tag('items', {node=node})
55                                 :add_child(item)
56                         :up()
57                 :up();
58
59         -- store for the future
60         local user_data = data[bare];
61         if disable then
62                 if user_data then
63                         user_data[node] = nil;
64                         if not next(user_data) then data[bare] = nil; end
65                 end
66         else
67                 if not user_data then user_data = {}; data[bare] = user_data; end
68                 user_data[node] = {id or "1", item};
69         end
70
71         -- broadcast
72         for recipient, notify in pairs(recipients[bare] or NULL) do
73                 if notify[node] then
74                         stanza.attr.to = recipient;
75                         core_post_stanza(session, stanza);
76                 end
77         end
78 end
79 local function publish_all(user, recipient, session)
80         local d = data[user];
81         local notify = recipients[user] and recipients[user][recipient];
82         if d and notify then
83                 for node in pairs(notify) do
84                         if d[node] then
85                                 local id, item = unpack(d[node]);
86                                 session.send(st.message({from=user, to=recipient, type='headline'})
87                                         :tag('event', {xmlns='http://jabber.org/protocol/pubsub#event'})
88                                                 :tag('items', {node=node})
89                                                         :add_child(item)
90                                                 :up()
91                                         :up());
92                         end
93                 end
94         end
95 end
96
97 local function get_caps_hash_from_presence(stanza, current)
98         local t = stanza.attr.type;
99         if not t then
100                 for _, child in pairs(stanza.tags) do
101                         if child.name == "c" and child.attr.xmlns == "http://jabber.org/protocol/caps" then
102                                 local attr = child.attr;
103                                 if attr.hash then -- new caps
104                                         if attr.hash == 'sha-1' and attr.node and attr.ver then return attr.ver, attr.node.."#"..attr.ver; end
105                                 else -- legacy caps
106                                         if attr.node and attr.ver then return attr.node.."#"..attr.ver.."#"..(attr.ext or ""), attr.node.."#"..attr.ver; end
107                                 end
108                                 return; -- bad caps format
109                         end
110                 end
111         elseif t == "unavailable" or t == "error" then
112                 return;
113         end
114         return current; -- no caps, could mean caps optimization, so return current
115 end
116
117 module:hook("presence/bare", function(event)
118         -- inbound presence to bare JID recieved
119         local origin, stanza = event.origin, event.stanza;
120         local user = stanza.attr.to or (origin.username..'@'..origin.host);
121
122         if not stanza.attr.to or subscription_presence(user, stanza.attr.from) then
123                 local recipient = stanza.attr.from;
124                 local current = recipients[user] and recipients[user][recipient];
125                 local hash = get_caps_hash_from_presence(stanza, current);
126                 if current == hash then return; end
127                 if not hash then
128                         if recipients[user] then recipients[user][recipient] = nil; end
129                 else
130                         recipients[user] = recipients[user] or {};
131                         if hash_map[hash] then
132                                 recipients[user][recipient] = hash_map[hash];
133                                 publish_all(user, recipient, origin);
134                         else
135                                 recipients[user][recipient] = hash;
136                                 origin.send(
137                                         st.stanza("iq", {from=stanza.attr.to, to=stanza.attr.from, id="disco", type="get"})
138                                                 :query("http://jabber.org/protocol/disco#info")
139                                 );
140                         end
141                 end
142         end
143 end, 10);
144
145 module:hook("iq/bare/http://jabber.org/protocol/pubsub:pubsub", function(event)
146         local session, stanza = event.origin, event.stanza;
147         local payload = stanza.tags[1];
148
149         if stanza.attr.type == 'set' and (not stanza.attr.to or jid_bare(stanza.attr.from) == stanza.attr.to) then
150                 payload = payload.tags[1];
151                 if payload and (payload.name == 'publish' or payload.name == 'retract') and payload.attr.node then -- <publish node='http://jabber.org/protocol/tune'>
152                         local node = payload.attr.node;
153                         payload = payload.tags[1];
154                         if payload and payload.name == "item" then -- <item>
155                                 local id = payload.attr.id;
156                                 session.send(st.reply(stanza));
157                                 publish(session, node, id, st.clone(payload));
158                                 return true;
159                         end
160                 end
161         elseif stanza.attr.type == 'get' then
162                 local user = stanza.attr.to and jid_bare(stanza.attr.to) or session.username..'@'..session.host;
163                 if subscription_presence(user, stanza.attr.from) then
164                         local user_data = data[user];
165                         local node, requested_id;
166                         payload = payload.tags[1];
167                         if payload and payload.name == 'items' then
168                                 node = payload.attr.node;
169                                 local item = payload.tags[1];
170                                 if item and item.name == "item" then
171                                         requested_id = item.attr.id;
172                                 end
173                         end
174                         if node and user_data and user_data[node] then -- Send the last item
175                                 local id, item = unpack(user_data[node]);
176                                 if not requested_id or id == requested_id then
177                                         local stanza = st.reply(stanza)
178                                                 :tag('pubsub', {xmlns='http://jabber.org/protocol/pubsub'})
179                                                         :tag('items', {node=node})
180                                                                 :add_child(item)
181                                                         :up()
182                                                 :up();
183                                         session.send(stanza);
184                                         return true;
185                                 else -- requested item doesn't exist
186                                         local stanza = st.reply(stanza)
187                                                 :tag('pubsub', {xmlns='http://jabber.org/protocol/pubsub'})
188                                                         :tag('items', {node=node})
189                                                 :up();
190                                         session.send(stanza);
191                                         return true;
192                                 end
193                         elseif node then -- node doesn't exist
194                                 session.send(st.error_reply(stanza, 'cancel', 'item-not-found'));
195                                 return true;
196                         else --invalid request
197                                 session.send(st.error_reply(stanza, 'modify', 'bad-request'));
198                                 return true;
199                         end
200                 else --no presence subscription
201                         session.send(st.error_reply(stanza, 'auth', 'not-authorized')
202                                 :tag('presence-subscription-required', {xmlns='http://jabber.org/protocol/pubsub#errors'}));
203                         return true;
204                 end
205         end
206 end);
207
208 local function calculate_hash(disco_info)
209         local identities, features, extensions = {}, {}, {};
210         for _, tag in pairs(disco_info) do
211                 if tag.name == "identity" then
212                         table.insert(identities, (tag.attr.category or "").."\0"..(tag.attr.type or "").."\0"..(tag.attr["xml:lang"] or "").."\0"..(tag.attr.name or ""));
213                 elseif tag.name == "feature" then
214                         table.insert(features, tag.attr.var or "");
215                 elseif tag.name == "x" and tag.attr.xmlns == "jabber:x:data" then
216                         local form = {};
217                         local FORM_TYPE;
218                         for _, field in pairs(tag.tags) do
219                                 if field.name == "field" and field.attr.var then
220                                         local values = {};
221                                         for _, val in pairs(field.tags) do
222                                                 val = #val.tags == 0 and table.concat(val); -- FIXME use get_text?
223                                                 if val then table.insert(values, val); end
224                                         end
225                                         table.sort(values);
226                                         if field.attr.var == "FORM_TYPE" then
227                                                 FORM_TYPE = values[1];
228                                         elseif #values > 0 then
229                                                 table.insert(form, field.attr.var.."\0"..table.concat(values, "<"));
230                                         else
231                                                 table.insert(form, field.attr.var);
232                                         end
233                                 end
234                         end
235                         table.sort(form);
236                         form = table.concat(form, "<");
237                         if FORM_TYPE then form = FORM_TYPE.."\0"..form; end
238                         table.insert(extensions, form);
239                 end
240         end
241         table.sort(identities);
242         table.sort(features);
243         table.sort(extensions);
244         if #identities > 0 then identities = table.concat(identities, "<"):gsub("%z", "/").."<"; else identities = ""; end
245         if #features > 0 then features = table.concat(features, "<").."<"; else features = ""; end
246         if #extensions > 0 then extensions = table.concat(extensions, "<"):gsub("%z", "<").."<"; else extensions = ""; end
247         local S = identities..features..extensions;
248         local ver = base64(sha1(S));
249         return ver, S;
250 end
251
252 module:hook("iq/bare/disco", function(event)
253         local session, stanza = event.origin, event.stanza;
254         if stanza.attr.type == "result" then
255                 local disco = stanza.tags[1];
256                 if disco and disco.name == "query" and disco.attr.xmlns == "http://jabber.org/protocol/disco#info" then
257                         -- Process disco response
258                         local user = stanza.attr.to or (session.username..'@'..session.host);
259                         local contact = stanza.attr.from;
260                         local current = recipients[user] and recipients[user][contact];
261                         if type(current) ~= "string" then return; end -- check if waiting for recipient's response
262                         local ver = current;
263                         if not string.find(current, "#") then
264                                 ver = calculate_hash(disco.tags); -- calculate hash
265                         end
266                         local notify = {};
267                         for _, feature in pairs(disco.tags) do
268                                 if feature.name == "feature" and feature.attr.var then
269                                         local nfeature = feature.attr.var:match("^(.*)%+notify$");
270                                         if nfeature then notify[nfeature] = true; end
271                                 end
272                         end
273                         hash_map[ver] = notify; -- update hash map
274                         recipients[user][contact] = notify; -- set recipient's data to calculated data
275                         -- send messages to recipient
276                         publish_all(user, contact, session);
277                 end
278         end
279 end);
280
281 module:hook("account-disco-info", function(event)
282         local stanza = event.stanza;
283         stanza:tag('identity', {category='pubsub', type='pep'}):up();
284         stanza:tag('feature', {var='http://jabber.org/protocol/pubsub#publish'}):up();
285 end);
286
287 module:hook("account-disco-items", function(event)
288         local session, stanza = event.session, event.stanza;
289         local bare = session.username..'@'..session.host;
290         local user_data = data[bare];
291
292         if user_data then
293                 for node, _ in pairs(user_data) do
294                         stanza:tag('item', {jid=bare, node=node}):up();
295                 end
296         end
297 end);