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