« Previous - Version 33/65 (diff) - Next » - Current version
Adrian Georgescu, 04/12/2010 01:37 pm


= MSRP API =

<acronym title="WikiStart, Sip*, 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).

MSRP library

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.

=== Usage ===

==== 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.

=== Components ===

==== a connector or acceptor ====

{{{msrplib.connect}}} provides 2 connectors (with and without relay) and 2 acceptors (likewise, with or without relay). All of them have the exact same interface,
'''prepare'''(''self'', ''local_uri''={{{None}}})::
Depending on type of the connector, use local_uri to prepare the MSRP connection, which means:
  • connecting and authenticating at the relay if a relay is used ({{{ConnectorRelay}}} and {{{AcceptorRelay}}})
  • starts listening on a local port for DirectAcceptor
''local_uri'' is used to specify the connection parameters, e.g. local port and local ip.
If not provided, suitable ''local_uri'' will be generated.
''local_uri'' maybe updated in place by {{{prepare()}}} method if the real settings used are different from those specified.
{{{prepare}}} returns a full local path - list of {{{protocol.URI}}} instances, suitable to be put in SDP {{{'a:path'}}} attribute.
'''complete'''(''self'', ''full_remote_path'')::
Completes the establishment of the MSRP connection, which means:
  • establishes the connection if it wasn't already established ({{{ConnectorDirect}}})
  • binds the connection, i.e. exchanges empty chunk to verify each other's From-Path and To-Path
''full_remote_path'' should be a list of {{{protocol.URI}}} instances, obtained by parsing {{{'a:path'}}} put in SDP by the remote party.
{{{complete}}} returns {{{transport.MSRPTransport}}} instance, ready to read and send chunks.
'''cleanup'''(''self'')::
Calls this method to cleanup after {{{initialize()}}} if it's impossible to call {{{complete()}}}

==== transport.MSRPTransport ====

Low level access to the MSRP connection.

'''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.

==== session.MSRPSession ====

'''!__init!__'''(''self'', ''msrptransport'', ''accept_types''={{{['*']}}}, ''on_incoming_cb''={{{None}}})::
Initializes MSRPSession instance. Reports the incoming chunks through ''on_incoming_cb'' callback.
'''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 close the connection.

==== session.GreenMSRPSession ====

A subclass of MSRPSession that delivers the incoming messages to the queue.
'''!__init!__'''(''self'', ''msrptransport'', ''accept_types''={{{['*']}}})::
Initializes GreenMSRPSession instance. The messages will be delivered to the queue (available as {{{incoming}}} attribute).
'''receive_chunk'''(''self'')::
Returns a message from the queue.

==== connect.MSRPServer ====
Manages the listening sockets. Binds incoming requests.

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.
'''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.