import socket
import struct


def synproxy_parse_message(data):
    """ Return tuple (mode, ipaddr, port, proto, tcpmss, tcpsack, tcpwscale) """
    if len(data) != 12:
        raise Exception('wrong message')

    # Unpack IP address
    ipaddr = socket.inet_ntop(socket.AF_INET, data[0:4])
    # Unpack fields
    port, proto, flags, tcpmss, tcpsack, tcpwscale = struct.unpack('!HBBHBB', data[4:12])
    # Parse flags
    ## flush
    if (flags & 0b0000001) == 0b0000001:
        mode = 'flush'
        # Assert zeroed values? (port, proto, tcpmss, tcpsack, tcpwscale)
        port, proto, tcpmss, tcpsack, tcpwscale = 0, 0, 0, 0, 0
    ## add
    elif (flags & 0b0000010) == 0b0000010:
        mode = 'add'
    ## mod
    elif (flags & 0b0000100) == 0b0000100:
        mode = 'mod'
    ## del
    elif (flags & 0b0001000) == 0b0001000:
        mode = 'del'
    else:
        raise Exception('wrong message')

    # Do not process port and proto flags
    return (mode, ipaddr, port, proto, tcpmss, tcpsack, tcpwscale)