API Reference

Srf
Class

Srf stands for signaling resource framework. You create an instance of Srf to create and manage SIP dialogs and messages on a drachtio server. This class provides the high-level API through which you will gain access to other classes such as Dialogs, Requests, and Responses.

Constructor

Srf([tags])

Create an Srf instance.

ParametersTypeDescription
tags
optional
Array|String
An array of tags or a single tag to assign to this application. Tags can be used with inbound connections to a drachtio server as part of the routing decision to determine which application should be used to handle an incoming request.

Examples

Create an Srf instance and connect to a drachtio server
  const Srf = require('drachtio-srf');
  const srf = new Srf() ;

  srf.connect({
    host: '192.168.32.5',
    port: 9022,
    secret: 'cymru'
  }) ;
Create an Srf instance and listen for outbound connections
  const Srf = require('drachtio-srf');
  const srf = new Srf() ;

  srf.listen({
    port: 3000,
    secret: 'cymru'
  }) ;
Create an Srf instance specifying a tag for routing requests
  const Srf = require('drachtio-srf');
  const srf = new Srf('conference-app') ;

  srf.connect({
    host: '192.168.32.5',
    port: 9022,
    secret: 'cymru'
  }) ;

Methods

connect(opts)

make an inbound connection to a drachtio server. Note that as of drachtio-srf 4.4.0 and drachtio server 0.8.0 TLS connections are supported.

Returns:

Reference to the Srf instance.

ParametersTypeDescription
opts
Object
Configuration options
opts.host
string
IP address or DNS name of server to connect to
opts.port
optional
number
port to connect to. Default: 9022
opts.secret
string
shared secret
opts.tls
Object
options for establishing a TLS connection. See here for full list of options.

createUAS(req, res, opts, [callback])

create a SIP dialog, acting as a UAS (user agent server); i.e. respond to an incoming SIP INVITE with a 200 OK (or to a SUBSCRIBE request with a 202 Accepted).

ParametersTypeDescription
req
The incoming sip request object.
res
The sip response object.
opts
Object
Configuration options.
opts.localSdp
optional
string
The local session description protocol to include in the SIP response.
opts.headers
optional
Object
SIP headers to include on the SIP response to the INVITE.
opts.dialogStateEmitter
optional
EventEmitter
emits "stateChange" events for the dialog, per RFC 4235.
callback
optional
function
If provided, callback with signature (err, dialog).
Returns:

a Promise if no callback is provided, otherwise a reference to the Srf instance.


Examples

Returning a Promise
  srf.invite((req, res) => {
    let mySdp; // populated somehow with SDP we want to answer in 200 OK
    srf.createUas(req, res, {localSdp: mySdp})
      .then((uas) => {
        console.log(`dialog established, remote uri is ${uas.remote.uri}`);
        uas.on('destroy', () => {
          console.log('caller hung up');
        });
        return;
      })
      .catch((err) => {
        console.log(`Error establishing dialog: ${err}`);
      });
  });
Using a callback and populating custom headers
  srf.invite((req, res) => {
    let mySdp; // populated somehow with SDP we want to answer in 200 OK
    srf.createUas(req, res, {
      localSdp: mySdp,
      headers: {
        'User-Agent': 'drachtio/iechyd-da',
        'X-Linked-UUID': '1e2587c'
      }
    }, (err, uas) => {
      if (err) return console.log(`Error creating dialog: ${err}`);
      console.log(`dialog established, local tag is ${uas.sip.localTag}`);

      uas.on('destroy', () => console.log('caller hung up'));
    });
  });

createUAC(uri, opts, [progressCallbacks], [callback])

create a SIP dialog, acting as a UAC (user agent client)

ParametersTypeDescription
uri
string
request uri to send to.
opts
Object
Configuration options.
opts.method
optional
string
method of request. (Default: INVITE)
opts.localSdp
optional
string
the local session description protocol to include in the SIP INVITE request
opts.proxy
optional
string
send the request through an outbound proxy, specified as full sip uri or address[:port]
opts.headers
optional
Object
SIP headers to include on the SIP request.
opts.dialogStateEmitter
optional
EventEmitter
emits "stateChange" events for the dialog, per RFC 4235.
opts.auth
optional
Object | Function
Object containing sip credentials to use if challenged, or a function that returns the same. If a function is provided, it will be called with (req, res, callback) - the request that was sent as well as the response received; the function must invoke the callback with signature (err, username, password)
opts.auth.username
optional
string
sip username
opts.auth.password
optional
string
sip password
progressCallbacks
optional
Object
callbacks providing call progress notification.
progressCallbacks.cbRequest
optional
function
callback that provides request sent over the wire, with signature (err, req)
progressCallbacks.cbProvisional
optional
function
callback that provides a provisional response with signature (provisionalRes)
callback
optional
function
If provided, callback with signature (err, dialog).
Returns:

a Promise if no callback is provided, otherwise a reference to the Srf instance.


Examples

Returning a Promise
  let mySdp; // populated somehow with SDP we want to offer
  srf.createUAC('sip:1234@10.10.100.1', {localSdp: mySdp})
    .then((uac) => {
      console.log(`dialog established, call-id is ${uac.sip.callId}`);
      uac.on('destroy', () => console.log('called party hung up'));
      return;
    })
    .catch((err) => {
      console.error(`INVITE rejected with status: ${err}`);
      console.log(err.stack);
    });
Using a callback
  let mySdp; // populated somehow with SDP we want to offer
  srf.createUac('sip:1234@10.10.100.1', {localSdp: mySdp},
     (err, uac) => {
       if (err) return console.log(`INVITE rejected with status: ${err.status}`);
      
      uac.on('destroy', () => console.log('called party hung up'));
    });
Canceling a request after sending it
  const Srf = require('drachtio-srf');
  const srf = new Srf();
  const assert = require('assert');

  let mySdp; // populated somehow with SDP we want to offer
  let inviteSent;
  srf.createUAC('sip:1234@10.10.100.1', {localSdp: mySdp},
    {
      cbRequest: (err, reqSent) => { inviteSent = reqSent; }
    })
    .then((uac) => {
      // unexpected, in this case
      return console.log('dialog established before we could cancel');
    })
    .catch((err) => {
      assert(err.status === 487); // expected sip response to a CANCEL
    });

  // cancel the request after 0.5s
  setTimeout(() => {
    if (inviteSent) inviteSent.cancel();
  }, 500);

createB2BUA(req, res, uri, opts, [progressCallbacks], [callback])

create back-to-back dialogs; i.e. act as a back-to-back user agent (B2BUA), creating a pair of dialogs {uas, uac} -- a UAS dialog facing the caller or A party, and a UAC dialog facing the callee or B party such that media flows between them.

ParametersTypeDescription
req
The incoming sip request object.
res
The sip response object.
uri
string
request uri to send to.
opts
optional
Object
Configuration options.
opts.localSdpB
optional
string
the local session description protocol to offer in the SIP INVITE request on the B leg. Default: the sdp received on A leg.
opts.localSdpA
optional
string | function
the local session description protocol to offer in the response to the SIP INVITE request on the A leg; either a string or a function may be provided. If a function is provided, it will be invoked with two parameters (sdp, res) correspnding to the SDP received from the B party, and the sip response object received on the response from B. The function must return either the SDP (as a string) or a Promise that resolves to the SDP. Default: the SDP returned by the B party in the provisional/final response on the UAC leg.
opts.proxy
optional
string
send the request through an outbound proxy, specified as full sip uri or address[:port]
opts.headers
optional
Object
SIP headers to include on the SIP INVITE request on the B leg.
opts.dialogStateEmitter
optional
EventEmitter
emits "stateChange" events for the dialog, per RFC 4235.
opts.auth
optional
Object | Function
Object containing sip credentials to use if challenged, or a function that returns the same. If a function is provided, it will be called with (req, res, callback) - the request that was sent as well as the response received; the function must invoke the callback with signature (err, username, password)
opts.auth.username
optional
string
sip username
opts.auth.password
optional
string
sip password
opts.responseHeaders
optional
Object | function
SIP headers to include on all responses sent on the A leg (except for 100 Trying).

If a function is provided, it must return an object containing the headers to apply; the function will be called with the signature (uacResponse, headers) where uacResponse represents the associated response received from the A party and headers represents the headers that have already been set on the response (e.g. through the use of 'opts.proxyResponseHeaders').
opts.proxyRequestHeaders
optional
Array
an array of header names which, if they appear in the INVITE request on the A leg, should be included unchanged on the generated B leg INVITE
opts.proxyResponseHeaders
optional
Array
an array of header names which, if they appear in the response to the outgoing INVITE, should be included unchanged on the generated response to the A leg
opts.passFailure
optional
boolean
specifies whether to pass a failure returned from B leg back to the A leg. Default: true
opts.passProvisionalResponses
optional
boolean
specifies whether to pass provisional responses from B leg back to the A leg. Default: true
progressCallbacks
optional
Object
callbacks providing call progress notification.
progressCallbacks.cbRequest
optional
function
callback that provides request sent over the wire, with signature (err, req)
progressCallbacks.cbProvisional
optional
function
callback that provides a provisional response with signature (provisionalRes)
progressCallbacks.cbFinalizedUac
optional
function
callback that provides the UAC dialog as soon as the 200 OK is received from the B party. Since the UAC dialog is also returned when the B2B has been completely constructed, this is mainly useful if there is some need to be notified as soon as the B party answers. The callback signature is (uac).
callback
optional
function
If provided, callback with signature (err, {uac, uas}).
Returns:

a Promise that resolves to {uac, uas} if no callback is provided, otherwise a reference to the Srf instance.


Examples

simple B2BUA
  const Srf = require('drachtio-srf');
  const srf = new Srf();

  srf.connect({..});

  srf.invite((req, res) => {
    srf.createB2BUA(req, res, 'sip:1234@10.10.100.1', {localSdpB: req.body})
      .then(({uas, uac}) => {
        console.log('call connected');

        // when one side terminates, hang up the other
        uas.on('destroy', () => { uac.destroy(); });
        uac.on('destroy', () => { uas.destroy(); });
        return;
      })
      .catch((err) => {
        console.log(`call failed to connect: ${err}`);
      });
  });
use opts.passFailure to attempt a fallback URI on failure
  const Srf = require('drachtio-srf');
  const srf = new Srf();

  srf.connect({..});

  function endCall(dlg1, dlg2) {
    dlg1.on('destroy', () => dlg2.destroy());
    dlg2.on('destroy', () => dlg1.destroy());
  }
  srf.invite((req, res) => {
    srf.createB2BUA(req, res, 'sip:1234@10.10.100.1', {localSdpB: req.body, passFailure: false})
      .catch((err) => {
        // try backup if we got a sip non-success response and the caller did not hang up
        if (err instanceof Srf.SipError && err.status !== 487) {
          console.log(`failed connecting to primary, will try backup: ${err}`);
          return {};
        }
        throw err;
      })
      .then(({uas, uac}) => {
        if (!uas) return srf.createB2BUA(req, res, 'sip:1234@10.10.100.2', {localSdpB: req.body});
        return {uas, uac};
      })
      .then(({uas, uac}) => {
        return endCall({uas, uac});
      })
      .catch((err) => {
        console.log(`failed connecting to backup uri: ${err}`);
      });
  });
B2BUA with media proxy using rtpengine
  const Srf = require('drachtio-srf');
  const srf = new Srf();
  const config = require('config');
  const Client = require('rtpengine-client').Client;
  const rtpengine = new Client();

  srf.connect(config.get('drachtio'));

  // clean up and free rtpengine resources when either side hangs up
  function endCall(dlg1, dlg2, details) {
    [dlg1, dlg2].each((dlg) => dlg.on('destroy', () => (dlg === dlg1 ? dlg2 : dlg1).destroy()));
    rtpengine.delete(config.get('rtpengine'), details);
  }

  // function returning a Promise that resolves with the SDP to offer A leg in 18x/200 answer
  function getSdpA(details, remoteSdp, res) {
    return rtpengine.answer(config.get('rtpengine'), Object.assign(details, {
      'sdp': remoteSdp,
      'to-tag': res.getParsedHeader('To').params.tag
    }))
      .then((response) => {
        if (response.result !== 'ok') throw new Error(`Error calling answer: ${response['error-reason']}`);
        return response.sdp;
      });
  }

  // handle incoming invite
  srf.invite((req, res) => {
    const from = req.getParsedHeader('From');
    const details = {'call-id': req.get('Call-Id'), 'from-tag': from.params.tag};

    rtpengine.offer(config.get('rtpengine'), Object.assign(details, {'sdp': req.body}))
      .then((rtpResponse) => {
        if (rtpResponse && rtpResponse.result === 'ok') return rtpResponse.sdp;
        throw new Error('rtpengine failure');
      })
      .then((sdpB) => {
        return srf.createB2BUA(req, res, config.get('uri'), {
          localSdpB: sdpB,
          localSdpA: getSdpA.bind(null, details)
        });
      })
      .then(({uas, uac}) => {
        console.log('call connected with media proxy');
        return endCall(uas, uac, details);
      })
      .catch((err) => {
        console.log(`Error proxying call with media: ${err}`);
      });
  });

endSession(msg)

release outbound connection from the server.

Note: this is intended to be used with outbound connections; the method is a no-op if the underlying connection is an inbound connection.

ParametersTypeDescription
msg
A SIP request or response message received through a method event handler
Returns:

undefined.

listen(opts)

listen for outbound connections from a drachtio server. Note that as of drachtio-srf 4.4.0 and drachtio server 0.8.0 TLS connections are supported.

Returns:

Reference to the Srf instance.

ParametersTypeDescription
opts
Object
Configuration options
opts.host
optional
string
IP address or DNS name of server to connect to. Default: 0.0.0.0
opts.port
number
tcp port to listen on
opts.secret
string
shared secret
opts.tls
Object
options for establishing a TLS connection. See here for full list of options.

proxyRequest(req, [destination], [opts], [callback])

proxy an incoming request

ParametersTypeDescription
req
drachtio request object representing an incoming SIP request.
destination
optional
Array | string
an IP address[:port], or list of same, to proxy the request to
opts
optional
Object
Configuration options.
opts.forking
optional
string
when multiple destinations are provided,this option governs whether they are attempted sequentially or in parallel. Valid values are 'sequential' or 'parallel'. Default: sequential
opts.remainInDialog
optional
string
if true, add Record-Route header and remain in the SIP dialog (i.e. receiving futher SIP messaging for the dialog, including the terminating BYE request). Alias: 'recordRoute'. Default: false
opts.proxy
optional
string
send the request through an outbound proxy, specified as full sip uri or address[:port]
opts.provisionalTimeout
optional
string
timeout after which to attempt the next destination if no 100 Trying response has been received. Examples of valid syntax for this property are '1500ms', or '2s'
opts.finalTimeout
optional
string
timeout, in milliseconds, after which to cancel the current request and attempt the next destination if no final response has been received. Syntax is the same as for the provisionalTimeout property.
opts.followRedirects
optional
boolean
if true, handle 3XX redirect responses by generating a new request as per the Contact header; otherwise, proxy the 3XX response back upstream without generating a new response. Default: false
callback
optional
function
If provided, callback with signature (err, results), where `results` is a JSON object describing the individual sip call attempts and results
Returns:

a Promise if no callback is provided, otherwise a reference to the Srf instance.


Examples

simple proxy
  const Srf = require('drachtio-srf');
  const srf = new Srf();
  
  srf.invite((req, res) => {
    srf.proxyRequest(req, ['sip.example1.com', 'sip.example2.com'], {
      recordRoute: true,
      followRedirects: true,
      provisionalTimeout: '2s'
    }).then((results) => {
      console.log(JSON.stringify(result)); 
      // {finalStatus: 200, finalResponse:{..}, responses: [..]}
    });
  });

request(uri, opts, [callback])

send a SIP request message

ParametersTypeDescription
uri
string
sip uri to send the request to.
opts
Object
Configuration options.
opts.method
string
SIP method to send
opts.body
optional
string
the body of the request
opts.headers
optional
Object
SIP headers to include on the SIP request.
opts.auth
optional
Object
Used for digest authentication.
opts.auth.username
optional
string
Username to provide if challenged.
opts.auth.password
optional
string
password to provide if challenged.
callback
optional
function
If provided, callback with signature (err, req), where `req` represents the SIP request sent over the wire
Returns:

undefined.


Examples

send an OPTIONS ping
  const Srf = require('drachtio-srf');
  const srf = new Srf();

  srf.connect({host: '127.0.0.1', port: 9022, secret: 'cymru'});

  srf.on('connect', (err, hp) => {
    if (err) return console.log(`Error connecting: ${err}`);
    console.log(`connected to server listening on ${hp}`);

    setInterval(optionsPing, 10000);
  });

  function optionsPing() {
    srf.request('sip:tighthead.drachtio.org', {
      method: 'OPTIONS',
      headers: {
        'Subject': 'OPTIONS Ping'
      }
    }, (err, req) => {
      if (err) return console.log(`Error sending OPTIONS: ${err}`);
      req.on('response', (res) => {
        console.log(`Response to OPTIONS ping: ${res.status}`);
      });
    });
  }

use([method], handler)

installs sip middleware, optionally invoked only for a specific method type.

ParametersTypeDescription
method
string
a method for which the middleware is installed. Default: all methods
handler
function
a SIP middleware function with signature (req, res, next)
Returns:

undefined.


Examples

install middleware to authenticate incoming requests
  const Srf = require('drachtio-srf');
  const srf = new Srf() ;
  const digestAuth = require('drachtio-mw-digest-auth');
  const regParser = require('drachtio-mw-registration-parser');

  srf.connect({...}) ;
  
  const challenge = digestAuth({
    realm: 'sip.drachtio.org',
    passwordLookup: function(username, realm, callback) {
      // ..lookup password for username in realm
      return callback(null, password) ;
    }
  }) ;

  srf.use('register', challenge) ;
  srf.use('register', regParser) ;
  srf.register((req, res) => {
    // if we reach here we have an authenticated request
    // and 'registration' property added to 'req'

    res.send(200, {
      headers: {
        'Expires': req.registration.expires
      }
    });
  });

Events

"cdr:attempt" (source, time, msg)

a cdr:attempt event is emitted by an Srf instance when a a call attempt has been received (inbound) or initiated (outbound)

ParametersTypeDescription
source
string
'network'|'application', depending on whether the INVITE is inbound (received), or outbound (sent), respectively
time
string
the time (UTC) recorded by the SIP stack corresponding to the attempt
msg
Object
the actual message sent or received

"cdr:start" (source, time, role, msg)

a cdr:start event is emitted by an Srf instance when a call attempt has been connected successfully; i.e., a call has started

ParametersTypeDescription
source
string
'network'|'application', depending on whether the INVITE is inbound (received), or outbound (sent), respectively
time
string
the time (UTC) recorded by the SIP stack corresponding to the attempt
role
string
'uac'|'uas'|'uac-proxy'|'uas-proxy' indicating whether the application is acting as a user agent client, user agent server, proxy (sending message), or proxy (receiving message) for this cdr
msg
Object
the actual message sent or received

"cdr:stop" (source, time, reason, msg)

a cdr:stop event is emitted by an Srf instance when a connected call has ended.
This could either be a connected call that hangs up, or an attempt that rejected with a final non-success response.

ParametersTypeDescription
source
string
'network'|'application', depending on whether the INVITE is inbound (received), or outbound (sent), respectively
time
string
the time (UTC) recorded by the SIP stack corresponding to the attempt
reason
string
the reason the call was ended
msg
Object
the actual message sent or received

"connect" (err, hostport)

a connect event is emitted by an Srf instance when a connect method completes with either success or failure

ParametersTypeDescription
err
Error
Error encountered when attempting to authorize after connecting.
hostport
Array
An Array of SIP endpoints that the connected drachtio server is listening on for incoming SIP messages. The format of each endpoint is protcocol/adress:port, e.g udp/127.0.0.1:5060.

"connecting"

a connecting event is emitted by an Srf instance when it is attempting to reconnect to a server

"error" (err)

an error event is emitted by an Srf instance when when an inbound connection is lost.

Note: the srf instance will try to automatically reconnect if (and only if) the app has established a listener for the 'error' event.

ParametersTypeDescription
err
Error
specific error information.

Properties

Srf.parseUri

Static property returning a function that parses a SIP uri into components.


Returns:

function - a function that parses a SIP uri and returns an object


Examples

parse a uri
  const Srf = require('drachtio-srf');
  const srf = new Srf();
  const config = require('config');
  const parseUri = Srf.parseUri;

  srf.connect(config.get('drachtio'));

  srf.invite((req, res) => {
    //INVITE sip:5083084809@127.0.0.1:5060;tgrp=NYC-2 SIP/2.0

    console.log(JSON.stringify(parseUri(req.uri)));
    // {
    //   "family": "ipv4",
    //   "schema": "sip",
    //   "user": "5083084809",
    //   "host": "127.0.0.1",
    //   "port": 5060,
    //    "params": {
    //      "tgrp": "NYC-2"
    //    },
    //    "headers": {}
    // }
    //
    res.send(480);
  });

Srf.SipError

Static property returning a SipError class. A SipError has `status` and `reason` properties corresponding to the sip non-success result.


Returns:

SipError - a SipError object

Dialog
Class

A SIP Dialog represents a session between two SIP endpoints.
You do not create a Dialog explicitly (it has no public constructor); rather, calling srf.createUAS, srf.createUAC, or srf.createB2BUA will return you a Dialog upon success.

Methods

destroy(opts, [callback])

destroy the sip dialog by generating a BYE request (in the case of INVITE dialog), or NOTIFY (in the case of SUBSCRIBE)

ParametersTypeDescription
opts
optional
Object
Configuration options.
opts.headers
optional
Object
SIP headers to add to the outgoing BYE or NOTIFY.
callback
optional
function
If provided, callback with signature (err, msg) where msg provides the BYE or NOTIFY message that was sent over the wire.
Returns:

a Promise that resolves with the SIP request sent if no callback is provided, otherwise a reference to the Dialog instance.


modify([sdp], [opts], [callback])

modify a SIP session by changing attributes of the media connection

ParametersTypeDescription
sdp
string
'hold', 'unhold', or a session description protocol
opts.noAck
optional
object
if provided, and no sdp is provided this will be a 3pcc re-invite; and the Promise returned will resolve with {res, ack}; i.e. the 200 OK received and a function to call that generates the ACK. You must provide the sdp to send as a parameter to the ack function.
callback
optional
function
If provided, callback with signature (err) when operation has completed.
Returns:

a Promise that resolves when the operation is complete if no callback is provided, otherwise a reference to the Dialog instance.


request(opts, [callback])

send a SIP request within a dialog.

ParametersTypeDescription
opts
Object
Configuration options
opts.method
string
SIP method to use for the request
opts.headers
optional
Object
SIP headers to apply on the request
opts.body
optional
string
body of the SIP request
callback
optional
function
If provided, callback with signature (err, req) when request has been sent.
Returns:

a Promise that resolves with the request that has been sent if no callback is provided, otherwise a reference to the Dialog instance.


Events

"destroy" (msg, reason)

a destroy event is emitted when the Dialog has been torn down from the far end

ParametersTypeDescription
msg
the SIP request that tore down the Dialog
reason
optional
string
a reason the dialog was destroyed (this is populated only for error cases; e.g. an ACK timeout)

"info" (req, res)

an info event is emitted when a SIP INFO request is received within the Dialog. When an application adds a handler for this event it must generate the SIP response by calling res.send on the provided drachtio response object. When no handler is found for this event a 200 OK will be automatically generated.

ParametersTypeDescription
req
a SIP request
res
a SIP response

"message" (req, res)

a message event is emitted when a SIP MESSAGE request is received within the Dialog. When an application adds a handler for this event it must generate the SIP response by calling res.send on the provided drachtio response object. When no handler is found for this event a 200 OK will be automatically generated.

ParametersTypeDescription
req
a SIP request
res
a SIP response

"modify" (req, res)

a modify event is triggered when the far end modifies the session by sending a re-INVITE. When an application adds a handler for this event it must generate the SIP response by calling res.send on the provided drachtio response object. When no handler is found for this event a 200 OK with the current local SDP.

ParametersTypeDescription
req
a SIP request
res
a SIP response

"notify" (req, res)

a notify event is emitted when a SIP NOTIFY request is received within the Dialog. When an application adds a handler for this event it must generate the SIP response by calling res.send on the provided drachtio response object. When no handler is found for this event a 200 OK will be automatically generated.

ParametersTypeDescription
req
a SIP request
res
a SIP response

"options" (req, res)

an options event is emitted when a SIP OPTIONS request is received within the Dialog. When an application adds a handler for this event it must generate the SIP response by calling res.send on the provided drachtio response object. When no handler is found for this event a 200 OK will be automatically generated.

ParametersTypeDescription
req
a SIP request
res
a SIP response

"refer" (req, res)

a refer event is emitted when a SIP REFER request is received within the Dialog. When an application adds a handler for this event it must generate the SIP response by calling res.send on the provided drachtio response object. When no handler is found for this event a 200 OK will be automatically generated.

ParametersTypeDescription
req
a SIP request
res
a SIP response

"refresh" (req)

a refresh event is emitted when a SIP refreshing re-INVITE is received within the Dialog. There is no need for the application to respond to this event; this is purely a notification.

ParametersTypeDescription
req
a SIP request

"update" (req, res)

an update event is emitted when a SIP UPDATE request is received within the Dialog. When an application adds a handler for this event it must generate the SIP response by calling res.send on the provided drachtio response object. When no handler is found for this event a 200 OK will be automatically generated.

ParametersTypeDescription
req
a SIP request
res
a SIP response

Properties

dialogType

'INVITE' or 'SUBSCRIBE' depending on the Dialog type.


id

String that provides a unique internal id for the Dialog.


local

Object containing information about the local side of the Dialog.

ParametersTypeDescription
uri
string
local sip uri
sdp
string
local sdp
contact
string
local contact header

remote

Object containing information about the remote side of the Dialog.

ParametersTypeDescription
uri
string
remote sip uri
sdp
string
remote sdp
contact
string
remote contact header

sip

Object containing information about the SIP details relating to the Dialog.

ParametersTypeDescription
callId
string
SIP Call-ID for the dialog
localTag
string
tag generated by local side of the Dialog
remoteTag
string
tag generated by remote side of the Dialog

subscribeEvent

string that indicates the Event subscribed for in a SUBSCRIBE Dialog


SipMessage
Class

This is a mix-in class containing common methods and properties for Request and Response objects.
You generally do not work directly with SipMessage objects, rather with Request or Response objects provided via callbacks or Promises.

Methods

get(hdr)

returns a header value as a string

ParametersTypeDescription
hdr
string
header name.
Returns:

a string containing the header value, or undefined if no such header exists.


Examples

Getting a header value
  srf.invite((req, res) => {
    console.log(req.get('Via'));
    // SIP/2.0/UDP 172.16.0.129:5061;branch=z9hG4bK-1859-1-0;received=127.0.0.1;rport=5061

getParsedHeader(hdr)

returns a header value as an Object containing individual information elements.

ParametersTypeDescription
hdr
string
header name.
Returns:

an Object containing the parsed header elements, or undefined if no such header exists.


Examples

Getting a parsed header
  srf.invite((req, res) => {
    console.log(JSON.stringify(req.getParsedHeader('Via')));
    /*
    [{
      "version": "2.0",
      "protocol": "UDP",
      "host": "172.16.0.129",
      "port": 5061,
      "params": {
        "branch": "z9hG4bK-2070-1-0",
        "received": "127.0.0.1",
        "rport": "5061"
      }
    }]
    */

has(hdr)

returns a boolean indicating if a header is present

ParametersTypeDescription
hdr
string
header name.
Returns:

boolean indicating presence of header in the message.


Properties

body

string providing the body of the message, if any.


calledNumber

string providing the phone number in the request-uri (request only).


callingNumber

string providing the calling phone number found in the P-Asserted-Identity or From header (request only).


headers

Object containing all of the SIP headers for this message.


method

string providing the method (request only).


payload

Array containing the body of the message organized into parts.

The payload property is similar to the body property, in that both provide access to the information carried in the body of the request.
However, whereas req.body provides the raw utf-8 string as carried on the wire, req.payload structures the information into parts.
This is primarily useful when dealing with multipart bodies.

Examples

using req.payload to work with multipart content
  // e.g., siprec INVITE has multipart content
  srf.invite((req, res) => {
    if (req.payload.length > 1) {
      console.log(`we have multipart content: ${JSON.stringify(req.payload)}`);
    }
    /*
    we have multipart content: 
    [{
      "type": "application/sdp",
      "content": "v=0\r\no=Sonus_UAC 328001 655768 .."
    }, {
      "type": "application/rs-metadata+xml",
      "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<tns:recording ..."
    }]                  
    */

protcol

string indicating the transport protocol used (e.g. "udp", "tcp").


reason

string that is the SIP reason code (response only).


source

string that indicates source of message: "network" or "application".


source_address

string that indicates the sending IP address.


Example

accessing IP address and port of sender
  srf.invite((req, res) => {
    console.log(`received INVITE from ${req.source_address}:${req.source_port}`);
    .. etc
  });

source_port

string that indicates the sending IP port.


stackTime

string that indicates the time the SIP stack handled the message.


stackDialogId

string that indicates the unique id assigned to the Dialog by the SIP stack (INVITE or SUBSCRIBE only).


stackTxnId

string that indicates the unique id assigned to the transaction by the SIP stack.


status

number that is the SIP status code (response only).


type

'request' or 'response'


uri

string containing the request-uri (request only).


Request
Class

Represents a SIP request that is either received by or sent from an application.
Note that SipMessage is mixed into this class, so all of those methods and properties are available as well.

Methods

cancel([callback])

cancels a request that was sent by the application.

ParametersTypeDescription
callback
optional
function
Callback that is invoked with signature (err, cancel), where 'cancel' is the SIP CANCEL request that was sent over the wire
Returns:

undefined.


proxy([opts], [callback])

Proxy an incoming request.

Note: it is generally preferred to call srf.proxyRequest.

ParametersTypeDescription
opts
Object
proxy options, as defined in srf.proxyRequest
callback
optional
function
Callback that is invoked with the results of the proxy operation
Returns:

A Promise that resolves with the proxy results if no callback is provided, otherwise a reference to the Request.


Properties

isNewInvite

boolean indicating if this is an INVITE that is not part of an existing Dialog.


Events

"cancel"

a cancel event is emitted when an incoming Request has been canceled by the sender

"response(msg)"

a response event is emitted when a response has been received for the request which has been sent by the application.

ParametersTypeDescription
msg
a SIP response message that was received in response to a request sent by the app

Response
Class

Represents a SIP response that is either received by or sent from an application.
Note that SipMessage is mixed into this class, so all of those methods and properties are available as well.

Methods

send(status, [reason], [opts], [callback], [fnAck])

sends a SIP response.

ParametersTypeDescription
status
number
SIP status code to send
reason
optional
string
SIP reason code to send. Default: the predefined reason code associated with the provided status
opts
optional
Object
Configuration options
opts.headers
optional
Object
SIP headers to send with response
opts.body
optional
string
body send with response
callback
optional
function
callback invoked with signature (err, response), where 'response' is the SIP response sent over the wire
fnAck
optional
function
function to be executed upon receipt of ACK or PRACK
Returns:

undefined.


Properties

finalResponseSent

boolean indicating if a final response has been sent (alias: 'headersSent').


statusCode

number indicating the SIP status code that was sent or received.