util/jid.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
 
11
local match = string.match;
12
local nodeprep = require "util.encodings".stringprep.nodeprep;
13
local nameprep = require "util.encodings".stringprep.nameprep;
14
local resourceprep = require "util.encodings".stringprep.resourceprep;
15
 
16
module "jid"
17
 
18
local function _split(jid)
19
	if not jid then return; end
20
	local node, nodepos = match(jid, "^([^@/]+)@()");
21
	local host, hostpos = match(jid, "^([^@/]+)()", nodepos)
22
	if node and not host then return nil, nil, nil; end
23
	local resource = match(jid, "^/(.+)$", hostpos);
24
	if (not host) or ((not resource) and #jid >= hostpos) then return nil, nil, nil; end
25
	return node, host, resource;
26
end
27
split = _split;
28
 
29
function bare(jid)
30
	local node, host = _split(jid);
31
	if node and host then
32
		return node.."@"..host;
33
	end
34
	return host;
35
end
36
 
37
local function _prepped_split(jid)
38
	local node, host, resource = _split(jid);
39
	if host then
40
		host = nameprep(host);
41
		if not host then return; end
42
		if node then
43
			node = nodeprep(node);
44
			if not node then return; end
45
		end
46
		if resource then
47
			resource = resourceprep(resource);
48
			if not resource then return; end
49
		end
50
		return node, host, resource;
51
	end
52
end
53
prepped_split = _prepped_split;
54
 
55
function prep(jid)
56
	local node, host, resource = _prepped_split(jid);
57
	if host then
58
		if node then
59
			host = node .. "@" .. host;
60
		end
61
		if resource then
62
			host = host .. "/" .. resource;
63
		end
64
	end
65
	return host;
66
end
67
 
68
function join(node, host, resource)
69
	if node and host and resource then
70
		return node.."@"..host.."/"..resource;
71
	elseif node and host then
72
		return node.."@"..host;
73
	elseif host and resource then
74
		return host.."/"..resource;
75
	elseif host then
76
		return host;
77
	end
78
	return nil; -- Invalid JID
79
end
80
 
81
function compare(jid, acl)
82
	-- compare jid to single acl rule
83
	-- TODO compare to table of rules?
84
	local jid_node, jid_host, jid_resource = _split(jid);
85
	local acl_node, acl_host, acl_resource = _split(acl);
86
	if ((acl_node ~= nil and acl_node == jid_node) or acl_node == nil) and
87
		((acl_host ~= nil and acl_host == jid_host) or acl_host == nil) and
88
		((acl_resource ~= nil and acl_resource == jid_resource) or acl_resource == nil) then
89
		return true
90
	end
91
	return false
92
end
93
 
94
return _M;