'Notify the peer about stream closure.
Ensure that xmlstream is not brokes - i.e. if the stream isn\'t opened yet -
open it before closure.
If the error condition is specified than create a stream error and send it along with
closing stream tag.
Emulate receiving \'unavailable\' type presence just before stream closure.'

def terminate_stream(self, error=None, unregister=1):

    if (self._stream_state >= STREAM__CLOSING):
        return
    if (self._stream_state < STREAM__OPENED):
        self.set_stream_state(STREAM__CLOSING)
        self._stream_open()
    else:
        self.set_stream_state(STREAM__CLOSING)
        p = Presence(typ='unavailable')
        p.setNamespace(NS_CLIENT)
        self._dispatch(p, trusted=1)
    if error:
        if isinstance(error, Node):
            self.sendnow(error)
        else:
            self.sendnow(ErrorNode(error))
    self._stream_close(unregister=unregister)
    if self.slave_session:
        self.slave_session.terminate_stream(STREAM_REMOTE_CONNECTION_FAILED)
