# Copyright 2026 SigmaSRC, Inc. All Rights Reserved.

"""Gather the nameserver by parsing resolv.conf."""

# Hmm, on Windows we should gather it by other means.  I think
# ipconfig/all would tell us.

import os
import re
import sys
import logging

if __name__ == "__main__":
    try:
        import sigma
    except ImportError:
        sys.path.append(os.path.join(os.pardir, os.pardir))

logger = logging.getLogger("gather.gather_nameserver")

_linere = re.compile(r"nameserver\s*(\d+\.\d+\.\d+\.\d+)")

def Gather(collector):
    t = collector.table("nameserver", ["nameserver"])
    if os.name == "nt":
        from win32com.client import GetObject
        try:
            obj = GetObject("WinMgMts://./root/cimv2")
            objItems = obj.InstancesOf("Win32_NetworkAdapterConfiguration")
            for item in objItems:
                enabled = item.Properties_("IPEnabled").Value
                if not enabled:
                    continue
                dnslist = item.Properties_("DNSServerSearchOrder").Value
                if not dnslist: # It may be None or an empty list
                    continue
                for dns in dnslist:
                    t.add([dns])
        except:
            logger.exception("nameserver gather failed")
    elif os.name == "posix":
        # This should work on Linux, Solaris, and Mac OS X at least.
        try:
            file = open("/etc/resolv.conf")
        except IOError as err:
            # No resolv.conf, nothing to gather 
            # (This happens legitimately on Mac OS X when no network
            # interface is up)
            return
        try:
            for line in file:
                match = _linere.match(line)
                if match:
                    ip = match.group(1)
                    t.add([ip])
        finally:
            file.close()
    else:
        raise RuntimeError("can't gather nameservers on %s system" % os.name)
    

def _test():
    from sigma.gather import gathering
    gathering.test(Gather)

if __name__ == "__main__":
    _test()
