« Previous - Version 41/65 (diff) - Next » - Current version
Luci Stanescu, 04/15/2010 01:36 pm


= MSRP API =

<acronym title="SipMSRPApi, SipDeveloperGuide, depth=3">TOC</acronym>

Message Session Relay Protocol (MSRP) is a protocol for transmitting a series of related Instant Messages in the context of a session. Message sessions are treated like any other media stream when set up via a rendezvous or session creation protocol such as the Session Initiation Protocol (SIP).

The MSRP protocol stack is implemented by [http://devel.ag-projects.com/cgi-bin/darcsweb.cgi?r=python-msrplib;a=summary msrplib] Python package.

{{{msrplib}}} is based upon [http://twistedmatrix.com twisted] and [http://download.ag-projects.com/SipClient/ eventlet] and provides a set of classes for establishing and managing MSRP connections.

The library consists of the following modules:

'''msrplib.transport'''::
Defines {{{MSRPTransport}}} class, which provides low level control over MSRP connections.
'''msrplib.connect'''::
Defines means to establish a connection, bind it, and provide an initialized {{{MSRPTransport}}} instance.
'''msrplib.session'''::
Defines {{{MSRPSession}}} class, which provides high level control over a MSRP connection.
'''msrplib.protocol'''::
Provides representation and parsing of MSRP entities - chunks and MSRP URIs.
'''msrplib.trafficlog'''::
Defines {{{Logger}}} class that is used through out the library to log the connection state.
Classes

=== URI ===

This class is implemented in the {{{msrplib.protocol}}} module and is used to represent an MSRP URI.

==== Methods ====

'''!__init!__'''(''self'', '''host'''={{{None}}}, '''use_tls'''={{{False}}}, '''user'''={{{None}}}, '''port'''={{{None}}}, '''session_id'''={{{None}}}, '''parameters'''={{{None}}}, '''credentials'''={{{None}}})::
Constructs a new {{{URI}}}. All the arguments specified here are also attributes on the object. For more information on these attributes, see RFC4975.
[[BR]]''host'':[[BR]]
The hostname or IP address which forms the URI.
[[BR]]''use_tls'':[[BR]]
Whether this identifies an msrps or msrp URI.
[[BR]]''user'':[[BR]]
The user part of the URI.
[[BR]]''port'':[[BR]]
The port in the URI.
[[BR]]''session_id'':[[BR]]
The session identifier part of the URI.
[[BR]]''parameters'':[[BR]]
A {{{dict}}} containing the parameters which will be appended to the URI.
[[BR]]''credentials'':[[BR]]
A {{{gnutls.interfaces.twisted.X509Credentials}}} object which will be used if this identifies a TLS URI to authenticate to the other endpoint.

=== MSRPRelaySettings ===

This class is used to specify the MSRP relay which will be used when connecting via a relay (using the {{{ConnectorRelay}}} or {{{AcceptorRelay}}} classes).

==== Methods ====

'''!__init!__'''(''self'', '''domain''', '''username''', '''password''', '''host'''={{{None}}}, '''use_tls'''={{{False}}}, '''port'''={{{None}}}, '''credentials'''={{{None}}})::
Constructs a new {{{URI}}}. All the arguments specified here are also attributes on the object. For more information on these attributes, see RFC4975.
[[BR]]''domain'':[[BR]]
The DNS domain in which to search for a MSRP relay using SRV queries.
[[BR]]''username'':[[BR]]
The username which will be used to authenticate to the relay.
[[BR]]''password'':[[BR]]
The password which will be used to authenticate to the relay.
[[BR]]''host'':[[BR]]
The hostname or IP address of the MSRP relay.
[[BR]]''use_tls'':[[BR]]
Whether this identifies an msrps or msrp URI.
[[BR]]''port'':[[BR]]
The port in the URI.
[[BR]]''credentials'':[[BR]]
A {{{gnutls.interfaces.twisted.X509Credentials}}} object which will be used to authenticate to the relay if TLS is used.

=== ConnectorDirect ===

This class is implemented in the {{{msrplib.connect}}} module and is used for outbound MSRP connections without a relay.

==== Methods ====

'''!__init!__'''(''self'', '''loger'''={{{None}}})::
Constructs a new ConnectorDirect.
[[BR]]''logger'':[[BR]]
The logger which will be used for this MSRP connection. See the [wiki:SipMSRPApi#Logging Logging] section for more information.
'''prepare'''(''self'', '''local_uri'''={{{None}}})::
This method returns a full local path - list of {{{protocol.URI}}} instances, suitable to be put in SDP {{{'a:path'}}} attribute.
[[BR]]''local_uri'':[[BR]]
This attribute will be used to construct the local path, but other than that it is not used anywhere else in case of the ConnectorDirect. If not provided, one
will be automatically generated
'''complete'''(''self'', '''full_remote_path''')::
This method establishes the connection and binds it (sends an empty chunk to verify each other's From-Path and To-Path). It returns {{{transport.MSRPTransport}}} instance, ready to read and send chunks.
[[BR]]''full_remote_path'':[[BR]]
A list of {{{protocol.URI}}} instances, obtained by parsing {{{'a:path'}}} put in SDP by the remote party.
'''cleanup'''(''self'')::
This method cleans up after {{{prepare()}}}; it should be called if {{{complete()}}} will not be called for whatever reason.

=== ConnectorRelay ===

This class is implemented in the {{{msrplib.connect}}} module and is used for outbound MSRP connections using a relay.

==== Methods ====

'''!__init!__'''(''self'', '''relay''', '''loger'''={{{None}}})::
Constructs a new ConnectorRelay.
[[BR]]''relay'':[[BR]]
An instance of {{{MSRPRelaySettings}}} which identifies the relay which is to be used.
[[BR]]''logger'':[[BR]]
The logger which will be used for this MSRP connection. See the [wiki:SipMSRPApi#Logging Logging] section for more information.
'''prepare'''(''self'', '''local_uri'''={{{None}}})::
This method returns a full local path - list of {{{protocol.URI}}} instances, suitable to be put in SDP {{{'a:path'}}} attribute.
[[BR]]''local_uri'':[[BR]]
This attribute will be used to construct the local path, but other than that it is not used anywhere else in case of the ConnectorRelay. If not provided, one
will be automatically generated
'''complete'''(''self'', '''full_remote_path''')::
This method establishes the connection to the relay and binds it (sends an empty chunk to verify each other's From-Path and To-Path). It returns {{{transport.MSRPTransport}}} instance, ready to read and send chunks.
[[BR]]''full_remote_path'':[[BR]]
A list of {{{protocol.URI}}} instances, obtained by parsing {{{'a:path'}}} put in SDP by the remote party.
'''cleanup'''(''self'')::
This method cleans up after {{{prepare()}}}; it should be called if {{{complete()}}} will not be called for whatever reason.

=== AcceptorDirect ===

This class is implemented in the {{{msrplib.connect}}} module and is used for inbound MSRP connections without using a relay.

==== Methods ====

'''!__init!__'''(''self'', '''loger'''={{{None}}})::
Constructs a new AcceptorDirect.
[[BR]]''logger'':[[BR]]
The logger which will be used for this MSRP connection. See the [wiki:SipMSRPApi#Logging Logging] section for more information.
'''prepare'''(''self'', '''local_uri'''={{{None}}})::
This method starts listening on a socket identified by the parameters in the {{{local_uri}}} argument. It returns a full local path - list of {{{protocol.URI}}} instances, suitable to be put in SDP {{{'a:path'}}} attribute.
[[BR]]''local_uri'':[[BR]]
This attribute will be used to construct the local path and to listen for incomming connections. If not provided, one
will be automatically generated
'''complete'''(''self'', '''full_remote_path''')::
This method waits for an incoming connection and a chunk sent by the other party. It returns {{{transport.MSRPTransport}}} instance, ready to read and send chunks.
[[BR]]''full_remote_path'':[[BR]]
A list of {{{protocol.URI}}} instances, obtained by parsing {{{'a:path'}}} put in SDP by the remote party. This is checked agains the From-Path header in the binding chunk.
'''cleanup'''(''self'')::
This method cleans up after {{{prepare()}}}; it should be called if {{{complete()}}} will not be called for whatever reason.

=== AcceptorRelay ===

This class is implemented in the {{{msrplib.connect}}} module and is used for inbound MSRP connections using a relay.

==== Methods ====

'''!__init!__'''(''self'', '''relay''', '''loger'''={{{None}}})::
Constructs a new AcceptorRelay.
[[BR]]''relay'':[[BR]]
An instance of {{{MSRPRelaySettings}}} which identifies the relay which is to be used.
[[BR]]''logger'':[[BR]]
The logger which will be used for this MSRP connection. See the [wiki:SipMSRPApi#Logging Logging] section for more information.
'''prepare'''(''self'', '''local_uri'''={{{None}}})::
This method connects to the relay specified in {{{__init__}}}. It returns a full local path - list of {{{protocol.URI}}} instances, suitable to be put in SDP {{{'a:path'}}} attribute.
[[BR]]''local_uri'':[[BR]]
This attribute will be used to construct the local path. If not provided, one will be automatically generated
'''complete'''(''self'', '''full_remote_path''')::
This method waits for an incoming chunk sent by the other party. It returns {{{transport.MSRPTransport}}} instance, ready to read and send chunks.
[[BR]]''full_remote_path'':[[BR]]
A list of {{{protocol.URI}}} instances, obtained by parsing {{{'a:path'}}} put in SDP by the remote party. This is checked agains the From-Path header in the binding chunk.
'''cleanup'''(''self'')::
This method cleans up after {{{prepare()}}}; it should be called if {{{complete()}}} will not be called for whatever reason.

=== MSRPTransport ===

This class is implemented in the {{{msrplib.transport}}} module and provies low level access to the MSRP connection. This class should not be constructed directly, but rather its intances should be obtained by using the various connector/acceptor classes documented above

==== Methods ====

'''make_chunk'''(''self'', '''transaction_id'''={{{None}}}, '''method'''={{{'SEND'}}}, '''code'''={{{None}}}, '''comment'''={{{None}}}, '''data'''={{{''}}}, '''contflag'''={{{None}}}, '''start'''={{{1}}}, '''end'''={{{None}}}, '''length'''={{{None}}}, '''message_id'''={{{None}}})::
Makes a new chunk ({{{protocol.MSRPData}}} instance) with proper {{{From-Path}}}, {{{To-Path}}}, {{{Byte-Range}}} and {{{Message-ID}}} headers set up based on MSRPTransport's state and the parameters provided. Use ''data'' for payload, and ''start''/''end''/''length'' to generate {{{Byte-Range}}} header. Generate new random strings for default values of ''transaction_id'' and ''message_id''.
[[BR]]''contflag'':[[BR]]
MSRP chunk's continuation flag ({{{'$'}}}, {{{'+'}}} or {{{'#'}}}). Default is {{{'$'}}}, unless you have a partial {{{SEND}}} chunk, in which case it is {{{'+'}}}
'''write'''(''self'', '''bytes''', '''sync'''={{{True}}})::
Writes ''bytes'' to the socket. If ''sync'' is true, waits for an operation to complete.
'''read_chunk'''(''self'', '''size'''={{{None}}})::
Waits for a new chunk and returns it.
If there was an error, closes the connection and raises {{{ChunkParseError}}}.
In case of unintelligible input, loses the connection and returns {{{None}}}.
When the connection is closed, raises the reason of the closure (e.g. {{{ConnectionDone}}}).
If the data already read exceeds ''size'', stops reading the data and returns
a "virtual" chunk, i.e. the one that does not actually correspond the the real
MSRP chunk. Such chunks have Byte-Range header changed to match the number of
bytes read and continuation that is {{{'+'}}}; they also possess {{{segment}}} attribute,
an integer, starting with 1 and increasing with every new segment of the chunk.
Note, that ''size'' only hints when to interrupt the segment but does not affect
how the data is read from socket. You may have segments bigger than ''size'' and it's
legal to set ''size'' to zero (which would mean return a chunk as long as you get
some data, regardless how small).
'''check_incoming_SEND_chunk'''(''self'', '''chunk''')::
Checks the 'To-Path' and 'From-Path' of the incoming SEND chunk.
Returns None is the paths are valid for this connection.
If an error is detected an MSRPError is created and returned.

=== MSRPSession ===

This class is implemented in the {{{msrplib.session}}} module and provides a high level API for MSRP sessions.

==== Methods ====

'''!__init!__'''(''self'', '''msrptransport''', '''accept_types'''={{{['*']}}}, '''on_incoming_cb'''={{{None}}})::
Initializes MSRPSession instance. The incoming chunks are reported through the ''on_incoming_cb'' callback, which must be a function which receives two arguments, both optional with default values of {{{None}}}: ''chunk'' and ''error''.
'''send_chunk'''(''self'', '''chunk''', '''response_cb'''={{{None}}})::
Sends ''chunk''. Report the result via ''response_cb''.
When ''response_cb'' argument is present, it will be used to report
the transaction response to the caller. When a response is received or generated
locally, ''response_cb'' is called with one argument. The function must do something
quickly and must not block, because otherwise it would block the reader greenlet.
If no response was received after {{{RESPONSE_TIMEOUT}}} seconds,
  • 408 response is generated if Failure-Report was {{{'yes'}}} or absent
  • 200 response is generated if Failure-Report was {{{'partial'}}} or {{{'no'}}}
Note that it's rather wasteful to provide ''response_cb'' argument other than {{{None}}}
for chunks with Failure-Report='no' since it will always fire 30 seconds later
with 200 result (unless the other party is broken and ignores Failure-Report header)
If sending is impossible raise {{{MSRPSessionError}}}.
'''deliver_chunk'''(''self'', '''chunk''', '''event'''={{{None}}})::
Sends the chunk, waits for the transaction response (if Failure-Report header is not {{{'no'}}}).
Returns the transaction response if it's a success, raise {{{MSRPTransactionError}}} if it's not.
If chunk's Failure-Report is {{{'no'}}}, returns {{{None}}} immediately.
'''shutdown'''(''self'', '''sync'''={{{True}}})::
Sends the messages already in queue then closes the connection.

=== MSRPServer ===

This class is implemented in the {{{msrplib.connect}}} module.
MSRPServer solves the problem with AcceptorDirect: concurrent using of 2
or more AcceptorDirect instances on the same non-zero port is not possible.
If you initialize() those instances, one after another, one will listen on
the socket and another will get BindError.
MSRPServer avoids the problem by sharing the listening socket between multiple connections.
It has a slightly different interface from AcceptorDirect, so it cannot be considered a drop-in
replacement.
It manages the listening sockets and binds incoming requests.

==== Methods ====

'''prepare'''(''self'', ''local_uri''={{{None}}}, ''logger''={{{None}}})::
Starts a listening port specified by ''local_uri'' if there isn't one on that port/interface already.
Adds ''local_uri'' to the list of expected URIs, so that incoming connections featuring this URI won't be rejected.
If ''logger'' is provided, it uses it for this connection instead of the default one.
'''complete'''(''self'', ''full_remote_path'')::
Waits until one of the incoming connections binds using provided ''full_remote_path''.
Returns connected and bounds the {{{MSRPTransport}}} instance.
If no such binding was made within {{{MSRPBindSessionTimeout.seconds}}}, raise {{{MSRPBindSessionTimeout}}}.
''full_remote_path'' should be a list of {{{protocol.URI}}} instances, obtained by parsing {{{'a:path'}}} put in SDP by the remote party.
'''cleanup'''(''self'', ''local_uri'')::
Removes ''local_uri'' from the list of expected URIs.
Example

=== Establish a connection ===

{{{msrplib.connect}}} provides a number of classes to establish a connection, so the first
thing to do is to select which one applies to your situation:

1. Calling endpoint, not using a relay ({{{ConnectorDirect}}})
2. Answering endpoint, not using a relay ({{{AcceptorDirect}}})
3. Calling endpoint, using a relay ({{{ConnectorRelay}}})
4. Answering endpoint, using a relay ({{{AcceptorRelay}}})

The answering endpoint may skip using the relay if sure that it's accessible directly, e.g is not behind a NAT. To be sure it works in any network topology a called end-point should always use a relay.

The calling endpoint does not need a relay as the protocol mandates that it is establishing an outbound connection which always work from behind a NAT.

Once you have an instance of the right class (use the convenience functions {{{get_connector()}}} and {{{get_acceptor()}}} to get one), the procedure to establish the
connection is the same:

{{{
full_local_path = connector.prepare()
try:
... put full_local_path in SDP 'a:path' attribute
... get full_remote_path from remote's 'a:path: attribute
... (the order of the above steps is reversed if you're the
... answering party, but that does not affect connector's usage)
msrptransport = connector.complete(full_remote_path)
finally:
connector.cleanup()
}}}

To customize connection's parameters, creates a new {{{protocol.URI}}} object and passes
it to prepare() function, e.g. {{{
local_uri = protocol.URI
connector.prepare(local_uri)
}}}

{{{prepare()}}} may update {{{local_uri}}} in place with the actual connection parameters
used (e.g. if you specified port=0). 'port' attribute of {{{local_uri}}} is currently
only respected by {{{AcceptorDirect}}}.

Note that, acceptors and connectors are one-use only. Which means, that {{{AcceptorDirect}}}
will open a port just to handle one incoming connection and close it right after.
If your application behaves more like a server, i.e. opens a port and listens on it
constantly, use {{{MSRPServer}}} class.