qmsk/net/socket/address.pyx
author Tero Marttila <terom@fixme.fi>
Fri, 25 Sep 2009 21:34:04 +0300
changeset 49 e2f79e68418a
parent 46 64b4ffb44754
permissions -rw-r--r--
fix up circular cimports related to the sockaddr type, and touch up endpoint/getaddrinfo a bit
cimport qmsk.net.libc as libc
cimport qmsk.net.py as py

#from qmsk.net.socket.address cimport *

cimport qmsk.net.libc as libc

cimport qmsk.net.socket.platform as platform

# concrete sockaddr implementation types
# mapping of AF -> sockaddr, user-modifyable
cimport qmsk.net.socket.af_inet, qmsk.net.socket.af_inet6

SOCKADDR_BY_FAMILY = {
    platform.AF_INET:   qmsk.net.socket.af_inet.sockaddr_in,
    platform.AF_INET6:  qmsk.net.socket.af_inet6.sockaddr_in6,
}

# build a sockaddr from the given sockaddr struct, based on sa_family
cdef sockaddr build_sockaddr (platform.sockaddr *sa, size_t sa_len) :
    # lookup correct class to use
    addr_type = SOCKADDR_BY_FAMILY[sa.sa_family]
    
    # construct with defaults
    cdef sockaddr addr = addr_type()

    # store
    addr._set_sockaddr(sa, sa_len)

    return addr

cdef class addrinfo :
 
    cdef _init_ai_members (self) :
        """
            Update self.ai.ai_* to reflect self.ai_*
        """

        cdef platform.socklen_t addr_len

        if self.ai_addr is not None :
            self.ai_addr._get_sockaddr(&self.ai.ai_addr, &addr_len)
            self.ai.ai_addrlen = addr_len

        else :
            self.ai.ai_addr = NULL
            self.ai.ai_addrlen = 0
        
        if self.ai_canonname is not None :
            self.ai.ai_canonname = self.ai_canonname

        else :
            self.ai.ai_canonname = NULL
    
    def __init__ (self, int flags = 0, int family = 0, int socktype = 0, int protocol = 0, sockaddr addr = None, object canonname = None) :
        """
            Construct a new addrinfo with the given parameters
        """


        self.ai.ai_flags = flags
        self.ai.ai_family = family
        self.ai.ai_socktype = socktype
        self.ai.ai_protocol = protocol

        self.ai_addr = addr

        if canonname is not None :
            self.ai_canonname = str(canonname)

        else :
            self.ai_canonname = None

        # update self.ai
        self._init_ai_members()
        
    cdef _init_addrinfo (self, platform.addrinfo *ai) :
        """
            Re-initialize this addrinfo's parameters from the given addrinfo
        """
        
        # copy raw
        self.ai = ai[0]
        
        # store copies of external objects
        if ai.ai_addr :
            # copy addr as object
            self.ai_addr = build_sockaddr(ai.ai_addr, ai.ai_addrlen)
            
        else :
            self.ai_addr = None

        if ai.ai_canonname :
            # copy as object
            self.ai_canonname = ai.ai_canonname
            
        else :
            self.ai_canonname = None

        # update self.ai
        self._init_ai_members()

    property flags :
        def __get__ (self) : return self.ai.ai_flags

    property family :
        def __get__ (self) : return self.ai.ai_family

    property socktype :
        def __get__ (self) : return self.ai.ai_socktype
    
    property protocol :
        def __get__ (self) : return self.ai.ai_protocol
    
    property addr :
        # XXX: None?
        def __get__ (self) : return self.ai_addr
    
    property canonname :
        # XXX: None?
        def __get__ (self) : return self.ai_canonname

    def __str__ (self) :
        return "family=%d, socktype=%d, protocol=%d, addr=%s, canonname=%s" % (self.family, self.socktype, self.protocol, self.addr, self.canonname)

cdef addrinfo build_addrinfo (platform.addrinfo *c_ai) :
    cdef addrinfo ai = addrinfo()
    
    ai._init_addrinfo(c_ai)

    return ai

def getaddrinfo (hostname, service, int family, int socktype, int protocol = 0, int flags = 0) :
    """
        Look up given hostname/service using the given socket parameters, and return a sequence of addrinfo objects.
            
            hostname        - internet address/hostname to look up, or None (for INADDR_ANY/localhost, see AI_PASSIVE)
            service         - port/service to use, or None (for ephemeral). Should be given as a string
            family          - address family to use, one of AF_*. May be AF_UNSPEC.
            socktype        - socket type to use, one of SOCK_*.
            protocol        - protocol to use, one of IPPROTO_* or zero to pick the default protocol for the given
                              socktype.
            flags           - bitmask of AI_* flags for getaddrinfo()

                AI_NUMERICHOST  - self.hostname is a literal address, do not perform any network host address lookups
                AI_NUMERICSERV  - self.service is a literal port number, do not lookup service names
                AI_CANONNAME    - return addrinfo objects with .canonname set to the official name of the host
                AI_PASSIVE      - intended for use by server applications, return addrinfos with an unspecified
                                  .addr if no self.hostname is not given.
                AI_ADDRCONFIG   - only return addrinfos with a .addrs of a given address family if the system has at
                                  least one local address of that address family configured.
                AI_V4MAPPED     - if family=AF_INET6, and no matching IPv6 addresses could be found, return IPv4-mapped
                                  IPv6 addresses.
                AI_ALL          - if used together with AI_V4MAPPED, then return both IPv6 and IPv4-mapped IPv6
                                  addresses.

    """
 
    # XXX: Cython doesn't support proper compound value literals...
    cdef platform.addrinfo hints
    
    libc.memset(&hints, 0, sizeof(hints))
    hints.ai_flags          = flags
    hints.ai_family         = family
    hints.ai_socktype       = socktype
    hints.ai_protocol       = protocol

    cdef platform.addrinfo *res, *r
    cdef int err
    cdef object ret = []

    cdef char *_hostname = NULL
    cdef char *_service = NULL

    if hostname is not None :
        _hostname = hostname
    
    if service is not None :
        # XXX: also accept integer port number?
        if isinstance(service, int) :
            service = str(service)

        _service = service

    # operate!
    err = platform.c_getaddrinfo(_hostname, _service, &hints, &res)

    if err :
        # XXX: raise a GAIError
        raise Exception(platform.gai_strerror(err))
    
    try :
        # gather results from linked list to PyList
        r = res

        while r :
            ret.append(build_addrinfo(r))

            r = r.ai_next
        
        # ok
        return ret

    finally :
        platform.c_freeaddrinfo(res)



cdef class endpoint :

    def __init__ (self, hostname=None, service=None) :
        """
            Construct with the given hostname/service, either of which may be None.

            A hostname of None implies all valid local addresses (with AI_PASSIVE), and a service of None implies an
            ephemeral port.

                hostname        - the literal address or DNS hostname or anything else that GAI supports
                service         - the numeric port or service name
        """

        self.hostname = hostname
        self.service = service

    def getaddrinfo (self, int family, int socktype, int protocol = 0, int flags = platform.AI_PASSIVE) :
        """
            See getaddrinfo().
        """

        return getaddrinfo(self.hostname, self.service, family, socktype, protocol, flags)

    def __str__ (self) :
        return "hostname=%s, service=%s" % (self.hostname, self.service)