Ejemplo n.º 1
0
def send_session_and_block_len(client, data):
    # init session
    global __S
    s_id = __new_session(client)

    if s_id == None:
        LOG.error('Can not open new session for sending')
        return 0

    count, size = __calculate_blocksize(s_id, len(data.encode()))
    blocks = split_data_to_blocks(data)
    LOG.debug("splitted data %s" % str(blocks))

    LOG.debug("Block count: %d" % count)
    LOG.debug("Block count splited: %d" % len(blocks))
    assert count == len(blocks)

    __S[s_id] = blocks

    LOG.debug("Send session and block session id %s" % s_id)
    LOG.debug("Send session and block session count %s" % count)

    response_data = [__RSP_OK, str(s_id), str(count)]
    r = __MSG_FIELD_SEP.join(response_data)
    return r
Ejemplo n.º 2
0
def get(sock, srv, m_id):
    '''Get message by iD
    @param sock: UDP socket, used to send/receive
    @param src: tuple ( IP, port ), server socket address
    @param m_id: int, message unique id
    @returns tuple ( int: time seconds since UNIX epoch,
                     str:IP, int:port, str:message )
    '''
    err, m = __request(sock, srv, __REQ_GET, [m_id])
    m = m[:3] + [__MSG_FIELD_SEP.join(m[3:])]
    return m if err == __RSP_OK else None
Ejemplo n.º 3
0
def __request(sock, srv, r_type, args, download=False):
    '''Send request to server, receive response
    @param sock: UDP socket, used to send/receive
    @param src: tuple ( IP, port ), server socket address
    @param r_type: string, request type
    @param args: list, request parameters/data
    '''

    # Envelope request (prepare data unit)
    m = __MSG_FIELD_SEP.join([r_type] + map(str, args))
    # Send/Receive using sessions
    print 'Sending data'
    n = send_data(sock, srv, m)
    # @TODO: Receive using sessions
    #     source = None
    #     while source != srv:
    #         try:
    #             # Try receive a response
    #             r,source = s.recvfrom(protocol.MAX_DATAUNIT_SIZE)
    #         except KeyboardInterrupt:
    #             __err('Ctrl+C issued, terminating ...')
    #             sock.close()
    #             exit(0)
    #         # In case unexpected message was received
    #         if source != srv:
    #             print 'Unknown message origin %s:%d' % source
    #             print 'Expected %s:%d' % srv
    # Check error code
    # @TODO: When sessions receive is implemented, rewrite this properly
    #     r_data = r.split(protocol.__MSG_FIELD_SEP)
    #     err,r_args = r_data[0],r_data[1:] if len(r_data) > 1 else []
    #     if err != protocol.__RSP_OK:
    #         if err in protocol.__ERR_MSGS.keys():
    #             __err('Error: server response code [%s]' % err)
    #             __err(protocol.__ERR_MSGS[err])
    #         else:
    #             __err('Malformed server response [%s]' % err)

    err, r = receive_data(sock, srv)

    if download:
        r = download_blocks(sock, srv, r[0], r[1])
    # err = __RSP_OK if n > 0 else __RSP_ERRTRANSM
    return err, r
Ejemplo n.º 4
0
def server_process(board, message, source, oldprotocol=False):
    '''Process the client's message, modify the board if needed
        @param board: active message board (static lib.)
        @param message: string, protocol data unit received from client
        @param source: tuple ( ip, port ), client's socket address
        @param oldprotocol: backward compatibility flag (for 0.0.0.x clients)
        @returns string, response to send to client
    '''
    LOG.debug('Received message length %d' % len(message))
    if len(message) < 2:
        LOG.degug('Not enough data received from %s ' % message)
        return __RSP_BADFORMAT
    LOG.debug('Message control code (%s) '\
              '%s ' % (message[0],__CTR_MSGS[message[0]]))
    if message.startswith(__REQ_PUBLISH + __MSG_FIELD_SEP):
        msg = message[2:]
        LOG.debug('New message to publish from %s:%d, '\
            'msg: %s' % (source+((msg[:60]+'...' if len(msg) > 60 else msg),)))
        m_id = board.publish(msg, source)
        LOG.info('Published new message, uuid: %d' % m_id)
        return __RSP_OK
    elif message.startswith(__REQ_LAST + __MSG_FIELD_SEP):
        s = message[2:]
        try:
            n = int(s)
            LOG.debug('New message listing request from %s:%d, '\
                      'messages %d' % (source+(n,)))
        except ValueError:
            LOG.debug('Integer required, %s received' % s)
            return __RSP_BADFORMAT
        ids = board.last(n)
        LOG.debug('Last %d ids: %s ' % (n, ','.join(map(str, ids))))
        return __MSG_FIELD_SEP.join((__RSP_OK, ) + tuple(map(str, ids)))
    elif message.startswith(__REQ_GET + __MSG_FIELD_SEP):
        s = message[2:]
        try:
            m_id = int(s)
            LOG.debug('New message request by id from %s:%d, '\
                      'id %d' % (source+(m_id,)))
        except ValueError:
            LOG.debug('Integer required, %s received' % s)
            return __RSP_BADFORMAT
        m = board.get(m_id)
        m = map(str, m)
        if oldprotocol:
            # too bad here will lose some of the message trail in
            # respect of the header, but this only affects long messages
            # client should be aware of it and not let publishing messages
            # which are close to maximal PDU size

            msg_info_size = sum(map(len, m[:3])) + len(m[:3])
            # +2 For control code
            if (len(m[3]) + msg_info_size + 2) > MAX_PDU_SIZE_OLD_PROTO:
                offset = MAX_PDU_SIZE_OLD_PROTO - (msg_info_size + 2)
                m = m[:3] + [m[3][:offset]]
                LOG.info('Big message was cut, %d trailing bytes removed' %
                         offset)
                LOG.info('Upgrade client code to protocol 0.0.1.x!')
        LOG.debug('Message id %d, msg size: [%d]' % (m_id, len(' '.join(m))))
        if m == None:
            LOG.debug('No messages by iD: %d' % m_id)
            return __RSP_MSGNOTFOUND
        return __MSG_FIELD_SEP.join((__RSP_OK, ) + tuple(m))
    else:
        LOG.debug('Unknown control message received: %s ' % message)
        return __RSP_UNKNCONTROL