function request_route()
local method = KSR.pv.get("$rm")
KSR.log(LOG_NOTICE, "Received " .. method .. " request")
if KSR.maxfwd.process_maxfwd(10) < 0 then
KSR.sl.send_reply(483, "Too Many Hops")
return
end
if KSR.pv.is_method("REGISTER") then
if KSR.registrar.save("location") < 0 then
KSR.sl.reply_error()
end
return
end
if KSR.pv.is_method("INVITE") then
if KSR.registrar.lookup("location") < 0 then
KSR.sl.send_reply(404, "User Not Found")
return
end
KSR.tm.t_relay()
end
KSR.sl.send_reply(405, "Method Not Allowed")
end
注释说明
1. 函数定义
function request_route()
- 定义了一个名为
request_route
的函数,这是 Kamailio 调用 Lua 脚本的入口函数。
2. 获取 SIP 方法
local method = KSR.pv.get("$rm")
- 使用
KSR.pv.get("$rm")
获取 SIP 请求的方法(如 INVITE
、REGISTER
等)。
$rm
是 Kamailio 的伪变量,表示 SIP 请求方法。
3. 记录日志
KSR.log(LOG_NOTICE, "Received " .. method .. " request")
- 使用
KSR.log()
记录日志,输出接收到的 SIP 方法。
LOG_NOTICE
是日志级别,表示普通信息。
4. 检查最大跳数
if KSR.maxfwd.process_maxfwd(10) < 0 then
KSR.sl.send_reply(483, "Too Many Hops")
return
end
- 调用
KSR.maxfwd.process_maxfwd(10)
检查并递减 Max-Forwards
的值。
- 如果
Max-Forwards
的值小于 10,发送 483 Too Many Hops
响应并终止脚本执行。
5. 处理 REGISTER 请求
if KSR.pv.is_method("REGISTER") then
if KSR.registrar.save("location") < 0 then
KSR.sl.reply_error()
end
return
end
- 使用
KSR.pv.is_method("REGISTER")
检查是否为 REGISTER
请求。
- 如果是
REGISTER
请求,调用 KSR.registrar.save("location")
保存用户位置信息。
- 如果保存失败,发送错误响应并终止脚本执行。
6. 处理 INVITE 请求
if KSR.pv.is_method("INVITE") then
if KSR.registrar.lookup("location") < 0 then
KSR.sl.send_reply(404, "User Not Found")
return
end
KSR.tm.t_relay()
end
- 使用
KSR.pv.is_method("INVITE")
检查是否为 INVITE
请求。
- 如果是
INVITE
请求,调用 KSR.registrar.lookup("location")
查找被叫用户的位置。
- 如果查找失败,发送
404 User Not Found
响应并终止脚本执行。
- 如果查找成功,调用
KSR.tm.t_relay()
转发请求。
7. 处理其他请求
KSR.sl.send_reply(405, "Method Not Allowed")
- 如果不是
REGISTER
或 INVITE
请求,发送 405 Method Not Allowed
响应。