Search code examples
twiliotwilio-functions

Twilio SRV lookup while forwarding to SIP URI


I am trying to forward calls to my sip device from my twilio number. However this is currently not working as expected because Twilio does not like SIP providers using a load balanced url. In my case the sip uri ends with @in.callcentric.com which in turn sends requests to three servers. If I directly use one of the servers, i.e. @alpha11.callcentric.com:5070 instead of @in.callcentric.com it works. However this is not ideal imo.

I have found a node module that does SRV lookups. Is this something I could use with twilio functions to solve the problem?

Is there a way to force twilio to lookup the SRV record and automatically use that to forward the calls?

Relevant link


Solution

  • Using NPM's inbuilt dns module I was able to get things working. This is how my function looks now. Seems to be working okay.

    const dns = require('dns');
    
    let sipUri = '1777xxxxxxxxxx@in.callcentric.com';
    let protocol = 'udp';
    let region = 'us2' ;
    
    exports.handler = function(context, event, callback) {    
      var user =   sipUri.split('@')[0];  
      var host =   sipUri.split('@')[1];  
    
      // generate the TwiML to tell Twilio how to forward this call
      let twiml = new Twilio.twiml.VoiceResponse();
    
      const dial = twiml.dial();
    
      dns.resolveSrv('_sip._'+protocol+'.'+host, (err, addresses) => {
        var resolvedhost = addresses[0].name+':'+addresses[0].port;
        dial.sip('sip:'+user+'@'+resolvedhost+';region='+region);
        console.log(twiml.toString());
        // return the TwiML
        callback(null, twiml);
      });
    };
    

    This manually queries the hostname for SRV records and then uses the first result returned. Does not take weight and priorities into account.

    Gist