下面是我使用自己的 SIP 服务器使用的基本节点脚本。您需要为自己的测试替换凭据和 IP 地址。
代理脚本不会向客户端发送重定向响应,而是代表客户端向服务器发起新事务。在这种模式下运行的 SIP 服务器更准确地称为背对背用户代理 (B2BUA)。我还没有添加所有需要的功能,例如匹配并将响应传回原始客户端;这涉及到相当多的工作。
var sip = require('sip');
var digest = require('sip/digest');
var util = require('util');
var os = require('os');
var proxy = require('sip/proxy');
var registry = {
'user': { user: "user", password: "password", realm: "sipserver.com"},
};
function rstring() { return Math.floor(Math.random()*1e6).toString(); }
sip.start({
address: "192.168.33.116", // If the IP is not specified here the proxy uses a hostname in the Via header which will causes an issue if it's not fully qualified.
logger: {
send: function(message, address) { debugger; util.debug("send\n" + util.inspect(message, false, null)); },
recv: function(message, address) { debugger; util.debug("recv\n" + util.inspect(message, false, null)); }
}
},
function(rq) {
try {
if(rq.method === 'INVITE') {
proxy.send(sip.makeResponse(rq, 100, 'Trying'));
//looking up user info
var username = sip.parseUri(rq.headers.to.uri).user;
var creds = registry[username];
if(!creds) {
proxy.send(sip.makeResponse(rq, 404, 'User not found'));
}
else {
proxy.send(rq, function(rs) {
if(rs.status === 401) {
// Update the original request so that it's not treated as a duplicate.
rq.headers['cseq'].seq++;
rq.headers.via.shift ();
rq.headers['call-id'] = rstring();
digest.signRequest(creds, rq, rs, creds);
proxy.send(rq);
}
});
}
}
else {
proxy.send(sip.makeResponse(rq, 405, 'Method Not Allowed'));
}
} catch(e) {
util.debug(e);
util.debug(e.stack);
proxy.send(sip.makeResponse(rq, 500, "Server Internal Error"));
}
});