You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mod_jibri_queue_component.lua 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. local st = require "util.stanza";
  2. local jid = require "util.jid";
  3. local http = require "net.http";
  4. local json = require "cjson";
  5. local inspect = require('inspect');
  6. local socket = require "socket";
  7. local uuid_gen = require "util.uuid".generate;
  8. local jwt = require "luajwtjitsi";
  9. local it = require "util.iterators";
  10. local neturl = require "net.url";
  11. local parse = neturl.parseQuery;
  12. local get_room_from_jid = module:require "util".get_room_from_jid;
  13. local room_jid_match_rewrite = module:require "util".room_jid_match_rewrite;
  14. local is_healthcheck_room = module:require "util".is_healthcheck_room;
  15. local room_jid_split_subdomain = module:require "util".room_jid_split_subdomain;
  16. local internal_room_jid_match_rewrite = module:require "util".internal_room_jid_match_rewrite;
  17. local async_handler_wrapper = module:require "util".async_handler_wrapper;
  18. -- this basically strips the domain from the conference.domain address
  19. local parentHostName = string.gmatch(tostring(module.host), "%w+.(%w.+)")();
  20. if parentHostName == nil then
  21. log("error", "Failed to start - unable to get parent hostname");
  22. return;
  23. end
  24. local parentCtx = module:context(parentHostName);
  25. if parentCtx == nil then
  26. log("error",
  27. "Failed to start - unable to get parent context for host: %s",
  28. tostring(parentHostName));
  29. return;
  30. end
  31. local token_util = module:require "token/util".new(parentCtx);
  32. local ASAPKeyPath
  33. = module:get_option_string("asap_key_path", '/etc/prosody/certs/asap.key');
  34. local ASAPKeyId
  35. = module:get_option_string("asap_key_id", 'jitsi');
  36. local ASAPIssuer
  37. = module:get_option_string("asap_issuer", 'jitsi');
  38. local ASAPAudience
  39. = module:get_option_string("asap_audience", 'jibriqueue');
  40. local ASAPTTL
  41. = module:get_option_number("asap_ttl", 3600);
  42. local ASAPTTL_THRESHOLD
  43. = module:get_option_number("asap_ttl_threshold", 600);
  44. local ASAPKey;
  45. local queueServiceURL
  46. = module:get_option_string("jibri_queue_url");
  47. if queueServiceURL == nil then
  48. log("error", "No jibri_queue_url specified. No service to contact!");
  49. return;
  50. end
  51. -- option to enable/disable token verifications
  52. local disableTokenVerification
  53. = module:get_option_boolean("disable_jibri_queue_token_verification", false);
  54. local http_headers = {
  55. ["User-Agent"] = "Prosody ("..prosody.version.."; "..prosody.platform..")",
  56. ["Content-Type"] = "application/json"
  57. };
  58. -- we use async to detect Prosody 0.10 and earlier
  59. local have_async = pcall(require, "util.async");
  60. if not have_async then
  61. module:log("warn", "conference duration will not work with Prosody version 0.10 or less.");
  62. return;
  63. end
  64. local muc_component_host = module:get_option_string("muc_component");
  65. if muc_component_host == nil then
  66. log("error", "No muc_component specified. No muc to operate on for jibri queue!");
  67. return;
  68. end
  69. log("info", "Starting jibri queue handling for %s", muc_component_host);
  70. -- Read ASAP key once on module startup
  71. local f = io.open(ASAPKeyPath, "r");
  72. if f then
  73. ASAPKey = f:read("*all");
  74. f:close();
  75. if not ASAPKey then
  76. module:log("warn", "No ASAP Key read, disabling muc_events plugin");
  77. return
  78. end
  79. else
  80. module:log("warn", "Error reading ASAP Key, disabling muc_events plugin");
  81. return
  82. end
  83. -- TODO: Figure out a less arbitrary default cache size.
  84. local jwtKeyCacheSize = module:get_option_number("jwt_pubkey_cache_size", 128);
  85. local jwtKeyCache = require"util.cache".new(jwtKeyCacheSize);
  86. local function round(num, numDecimalPlaces)
  87. local mult = 10^(numDecimalPlaces or 0)
  88. return math.floor(num * mult + 0.5) / mult
  89. end
  90. local function generateToken(audience)
  91. audience = audience or ASAPAudience
  92. local t = os.time()
  93. local err
  94. local exp_key = 'asap_exp.'..audience
  95. local token_key = 'asap_token.'..audience
  96. local exp = jwtKeyCache:get(exp_key)
  97. local token = jwtKeyCache:get(token_key)
  98. --if we find a token and it isn't too far from expiry, then use it
  99. if token ~= nil and exp ~= nil then
  100. exp = tonumber(exp)
  101. if (exp - t) > ASAPTTL_THRESHOLD then
  102. return token
  103. end
  104. end
  105. --expiry is the current time plus TTL
  106. exp = t + ASAPTTL
  107. local payload = {
  108. iss = ASAPIssuer,
  109. aud = audience,
  110. nbf = t,
  111. exp = exp,
  112. }
  113. -- encode
  114. local alg = "RS256"
  115. token, err = jwt.encode(payload, ASAPKey, alg, {kid = ASAPKeyId})
  116. if not err then
  117. token = 'Bearer '..token
  118. jwtKeyCache:set(exp_key,exp)
  119. jwtKeyCache:set(token_key,token)
  120. return token
  121. else
  122. return ''
  123. end
  124. end
  125. local function cb(content_, code_, response_, request_)
  126. if code_ == 200 or code_ == 204 then
  127. module:log("debug", "URL Callback: Code %s, Content %s, Request (host %s, path %s, body %s), Response: %s",
  128. code_, content_, request_.host, request_.path, inspect(request_.body), inspect(response_));
  129. else
  130. module:log("warn", "URL Callback non successful: Code %s, Content %s, Request (%s), Response: %s",
  131. code_, content_, inspect(request_), inspect(response_));
  132. end
  133. end
  134. local function sendEvent(type,room_address,participant)
  135. local event_ts = round(socket.gettime()*1000);
  136. local node, host, resource, target_subdomain = room_jid_split_subdomain(room_address);
  137. local room_param = '';
  138. if target_subdomain then
  139. room_param = target_subdomain..'/'..node;
  140. else
  141. room_param = node;
  142. end
  143. local out_event = {
  144. ["conference"] = room_address,
  145. ["room_param"] = room_param,
  146. ["event_type"] = type,
  147. ["participant"] = participant,
  148. }
  149. module:log("debug","Sending event %s",inspect(out_event));
  150. local headers = http_headers or {}
  151. headers['Authorization'] = generateToken()
  152. module:log("debug","Sending headers %s",inspect(headers));
  153. local request = http.request(queueServiceURL, {
  154. headers = headers,
  155. method = "POST",
  156. body = json.encode(out_event)
  157. }, cb);
  158. end
  159. -- receives iq from client currently connected to the room
  160. function on_iq(event)
  161. -- Check the type of the incoming stanza to avoid loops:
  162. if event.stanza.attr.type == "error" then
  163. return; -- We do not want to reply to these, so leave.
  164. end
  165. if event.stanza.attr.to == module:get_host() then
  166. if event.stanza.attr.type == "set" then
  167. log("info", "Jibri Queue Messsage Event found: %s ",inspect(event.stanza));
  168. local jibriQueue
  169. = event.stanza:get_child('jibri-queue', 'http://jitsi.org/protocol/jibri-queue');
  170. if jibriQueue then
  171. module:log("info", "Jibri Queue Join Request: %s ",inspect(jibriQueue));
  172. local roomAddress = jibriQueue.attr.room;
  173. local room = get_room_from_jid(room_jid_match_rewrite(roomAddress));
  174. if not room then
  175. module:log("warn", "No room found %s", roomAddress);
  176. return false;
  177. end
  178. local from = event.stanza.attr.from;
  179. local occupant = room:get_occupant_by_real_jid(from);
  180. if not occupant then
  181. module:log("warn", "No occupant %s found for %s", from, roomAddress);
  182. return false;
  183. end
  184. -- now handle new jibri queue message
  185. room.jibriQueue[occupant.jid] = true;
  186. module:log("Sending JoinQueue event for jid %s occupant %s",roomAddress,occupant.jid)
  187. sendEvent('JoinQueue',roomAddress,occupant.jid)
  188. else
  189. module:log("Jibri Queue Stanza missing child %s",inspect(event.stanza))
  190. end
  191. end
  192. end
  193. return true
  194. end
  195. -- create recorder queue cache for the room
  196. function room_created(event)
  197. local room = event.room;
  198. if is_healthcheck_room(room.jid) then
  199. return;
  200. end
  201. room.jibriQueue = {};
  202. end
  203. -- Conference ended, clear all queue cache jids
  204. function room_destroyed(event)
  205. local room = event.room;
  206. if is_healthcheck_room(room.jid) then
  207. return;
  208. end
  209. for jid, x in pairs(room.jibriQueue) do
  210. if x then
  211. sendEvent('LeaveQueue',internal_room_jid_match_rewrite(room.jid),jid);
  212. end
  213. end
  214. end
  215. -- Occupant left remove it from the queue if it joined the queue
  216. function occupant_leaving(event)
  217. local room = event.room;
  218. if is_healthcheck_room(room.jid) then
  219. return;
  220. end
  221. local occupant = event.occupant;
  222. -- check if user has cached queue request
  223. if room.jibriQueue[occupant.jid] then
  224. -- remove occupant from queue cache, signal backend
  225. room.jibriQueue[occupant.jid] = nil;
  226. sendEvent('LeaveQueue',internal_room_jid_match_rewrite(room.jid),occupant.jid);
  227. end
  228. end
  229. module:hook("iq/host", on_iq);
  230. -- executed on every host added internally in prosody, including components
  231. function process_host(host)
  232. if host == muc_component_host then -- the conference muc component
  233. module:log("info","Hook to muc events on %s", host);
  234. local muc_module = module:context(host);
  235. muc_module:hook("muc-room-created", room_created, -1);
  236. -- muc_module:hook("muc-occupant-joined", occupant_joined, -1);
  237. muc_module:hook("muc-occupant-pre-leave", occupant_leaving, -1);
  238. muc_module:hook("muc-room-destroyed", room_destroyed, -1);
  239. end
  240. end
  241. if prosody.hosts[muc_component_host] == nil then
  242. module:log("info","No muc component found, will listen for it: %s", muc_component_host)
  243. -- when a host or component is added
  244. prosody.events.add_handler("host-activated", process_host);
  245. else
  246. process_host(muc_component_host);
  247. end
  248. module:log("info", "Loading jibri_queue_component");
  249. --- Verifies room name, domain name with the values in the token
  250. -- @param token the token we received
  251. -- @param room_name the room name
  252. -- @param group name of the group (optional)
  253. -- @param session the session to use for storing token specific fields
  254. -- @return true if values are ok or false otherwise
  255. function verify_token(token, room_name, session)
  256. if disableTokenVerification then
  257. return true;
  258. end
  259. -- if not disableTokenVerification and we do not have token
  260. -- stop here, cause the main virtual host can have guest access enabled
  261. -- (allowEmptyToken = true) and we will allow access to rooms info without
  262. -- a token
  263. if token == nil then
  264. log("warn", "no token provided");
  265. return false;
  266. end
  267. session.auth_token = token;
  268. local verified, reason = token_util:process_and_verify_token(session);
  269. if not verified then
  270. log("warn", "not a valid token %s", tostring(reason));
  271. return false;
  272. end
  273. local room_address = jid.join(room_name, module:get_host());
  274. -- if there is a group we are in multidomain mode and that group is not
  275. -- our parent host
  276. if group and group ~= "" and group ~= parentHostName then
  277. room_address = "["..group.."]"..room_address;
  278. end
  279. if not token_util:verify_room(session, room_address) then
  280. log("warn", "Token %s not allowed to join: %s",
  281. tostring(token), tostring(room_address));
  282. return false;
  283. end
  284. return true;
  285. end
  286. --- Handles request for updating jibri queue status
  287. -- @param event the http event, holds the request query
  288. -- @return GET response, containing a json with response details
  289. function handle_update_jibri_queue(event)
  290. if (not event.request.url.query) then
  291. return { status_code = 400; };
  292. end
  293. local params = parse(event.request.url.query);
  294. local user_jid = params["user"];
  295. local roomAddress = params["room"];
  296. if not verify_token(params["token"], roomAddress, {}) then
  297. return { status_code = 403; };
  298. end
  299. local room = get_room_from_jid(room_jid_match_rewrite(roomAddress));
  300. if (not room) then
  301. log("error", "no room found %s", roomAddress);
  302. return { status_code = 404; };
  303. end
  304. local occupant = room:get_occupant_by_real_jid(user_jid);
  305. if not occupant then
  306. log("warn", "No occupant %s found for %s", user_jid, roomAddress);
  307. return { status_code = 404; };
  308. end
  309. -- TODO: actually implement udpate code here
  310. return { status_code = 200; };
  311. end
  312. module:depends("http");
  313. module:provides("http", {
  314. default_path = "/";
  315. name = "jibriqueue";
  316. route = {
  317. ["GET /jibriqueue/update"] = function (event) return async_handler_wrapper(event,handle_update_jibri_queue) end;
  318. };
  319. });