import six
import struct


def parse_dbus_header(header):
    """Parse a D-BUS header. Return the message size."""
    if six.indexbytes(header, 0) == ord('l'):
        endian = '<'
    elif six.indexbytes(header, 0) == ord('B'):
        endian = '>'
    else:
        raise ValueError('illegal endianness')
    if not 1 <= six.indexbytes(header, 1) <= 4:
        raise ValueError('illegel message type')
    if struct.unpack(endian + 'I', header[8:12])[0] == 0:
        raise ValueError('illegal serial number')
    harrlen = struct.unpack(endian + 'I', header[12:16])[0]
    padlen = (8 - harrlen) % 8
    bodylen = struct.unpack(endian + 'I', header[4:8])[0]
    return 16 + harrlen + padlen + bodylen