Imports System.Xml
Imports System.Data.OleDb
Imports System.Management
Module Functions

    Public Hours As Short
    Public Minutes As Short




    Public Function ValidIP(ByVal IP As String) As Boolean

        Dim temp() As String
        Dim X As Integer
        Try
            If Not IP Like "*.*.*.*" Then Exit Function
            temp = Split(IP, ".")
            If UBound(temp) = 3 Then
                For X = 0 To UBound(temp)
                    If Trim(temp(X)) = vbNullString Or Not IsNumeric(temp(X)) Then Exit Function
                    Select Case X
                        Case 0
                            If temp(X) > 223 Or temp(X) <= 0 Then Exit Function
                        Case 1 To 3
                            If temp(X) > 255 Or temp(X) < 0 Then Exit Function
                    End Select
                Next X
            End If
            ValidIP = True

        Catch
            CreateError(Err.Description + " " + Err.Source, Err.Number)
        End Try

    End Function

    Public Function FindIPInString(ByRef statspage As String, Optional ByRef Keyword As String = "") As String
        FindIPInString = vbNullString
        Dim temp() As String
        Dim X As Object = 0
        Dim Y As Short
        Try
            If Trim(statspage) = vbNullString Then GoTo clean
            If Trim(Keyword) IsNot vbNullString Then
                X = InStr(statspage, Keyword)
            End If

            'If X = 0 Then X = 1
            If X = 0 Then
                FindIPInString = "Keyword not found"
                Exit Function
            End If
            Do Until X > Len(statspage)
                Do Until Mid(statspage, X, 15) Like "*.*.*.*" And IsNumeric(Mid(statspage, X, 1)) Or X > Len(statspage)
                    X = X + 1
                Loop
                If X > Len(statspage) Then GoTo clean
                temp = Split(Mid(statspage, X, 15), ".") : Y = 1
                Do Until Not IsNumeric(Mid(temp(3), Y, 1)) Or Y > Len(temp(3))
                    Y = Y + 1
                Loop
                temp(3) = Mid(temp(3), 1, Y - 1)
                For Y = 0 To 3
                    FindIPInString = IIf(Trim(FindIPInString) = vbNullString, vbNullString, FindIPInString & ".") & temp(Y)
                    If Not IsNumeric(temp(Y)) Then Exit For
                Next Y
                If ValidIP(FindIPInString) Or FindIPInString = "0.0.0.0" Then Exit Do Else FindIPInString = vbNullString
                X = X + 1
            Loop
clean:
            If Not Trim(FindIPInString) Like "*.*.*.*" Then FindIPInString = "0.0.0.0"

        Catch
            CreateError(Err.Description + " " + Err.Source, Err.Number)
        End Try

    End Function
    Private Function Lefty(ByVal str As String, ByVal index As Integer) As String
        Lefty = str.Substring(0, index)
    End Function

    Private Function Righty(ByVal str As String, ByVal index As Integer) As String
        Righty = str.Substring(str.Length - index)
    End Function

    Public Function CheckDaily(ByRef tempTimeNow As String) As Boolean
        Try
            Dim SwitchIt As Boolean
            Dim tempTime As Integer ' in minutes

            Dim tempTimeNowMin As Integer ' in minutes
            Dim tempMinutes As Integer ' hours*60 + minutes (in minutes)
            SwitchIt = False
            If Hours = 0 And Minutes = 0 Then ' got loaded b/c the loadsettings function activated a label or something
                CheckDaily = False
                Exit Function
            End If
            tempTime = CInt(CInt(Lefty(FormatDateTime(TimeOfDay, DateFormat.ShortTime), 2)) * 60) + CInt(Righty(FormatDateTime(TimeOfDay, DateFormat.ShortTime), 2))
            tempTimeNowMin = CInt(CInt(Lefty(tempTimeNow, 2)) * 60) + CInt(Righty(tempTimeNow, 2))
            tempMinutes = CInt((Hours * 60) + Minutes)
            If tempTime >= tempTimeNowMin + tempMinutes Then
                SwitchIt = True
            Else
                If tempTime - tempMinutes + CInt(24 * 60) <= tempTimeNowMin Then
                    SwitchIt = True
                End If
            End If
            CheckDaily = SwitchIt
        Catch
            CreateError(Err.Description + " " + Err.Source, Err.Number)
        End Try

    End Function
    Public Function CreateInformational(ByVal msg As String, ByVal evID As Integer) As Object
        Dim Log As New EventLog
        Log.Source = "DDNS Enterprise Client"
        Log.WriteEntry(msg, EventLogEntryType.Information, evID)
        Return Nothing
    End Function

    Public Function CreateWarning(ByVal msg As String, ByVal evID As Integer) As Object
        Dim Log As New EventLog
        Log.Source = "DDNS Enterprise Client"
        Log.WriteEntry(msg, EventLogEntryType.Warning, evID)
        Return Nothing
    End Function

    Public Function CreateError(ByVal msg As String, ByVal evID As Integer) As Object
        Dim Log As New EventLog
        Log.Source = "DDNS Enterprise Client"
        Log.WriteEntry(msg, EventLogEntryType.Error, evID)
        Return Nothing
    End Function
    Public Function App_Path() As String
        Return System.AppDomain.CurrentDomain.BaseDirectory()
    End Function
    Public Function Connect(ByRef URL As String, Optional ByVal UserID As String = "", Optional ByVal Password As String = "") As String
        Dim myCred As New Net.NetworkCredential(UserID, Password)
        If Not My.Computer.Network.IsAvailable = True Then
            Connect = "Offline"
            Exit Function
        End If
        Dim Request As Net.HttpWebRequest
        Try
            Request = CType(System.Net.HttpWebRequest.Create(URL), System.Net.HttpWebRequest)
            Request.UserAgent = "DDNS-Enterprise-Client-v2.0"
            Request.Method = "GET"
            Request.Credentials = myCred
            Dim HttpWResponse As Net.HttpWebResponse = Request.GetResponse()
            Dim strm As IO.Stream = HttpWResponse.GetResponseStream()
            Dim sr As IO.StreamReader = New IO.StreamReader(strm)
            Dim sText As String = sr.ReadToEnd()
            Connect = sText
            strm.Close()
            Request = Nothing
            HttpWResponse = Nothing
            strm = Nothing
            sr = Nothing
        Catch
            Connect = "Failed"
            CreateError(Err.Description + " " + Err.Source, Err.Number)
        End Try

    End Function

 
    Public Function ReadDoms() As Boolean
        Dim SQL As OleDbCommand
        Dim RSet As OleDbDataReader
        Dim Conn As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & System.AppDomain.CurrentDomain.BaseDirectory() & "progdb.mdb;")
        Dim UserId As String = ""
        Dim Pass As String = ""
        Dim Server As String = ""
        Dim URL_Array As New ArrayList()
        Dim DB_Array As New ArrayList()
        Dim DBTR As String = ""
        Dim Result As Integer
        Try
            SQL = New OleDbCommand("Select Server, UserID, Pass From Settings", Conn)
            Conn.Open()
            RSet = SQL.ExecuteReader
            If RSet.HasRows = False Then

                Exit Function
            Else
                While RSet.Read
                    Server = RSet("Server").ToString
                    UserId = RSet("UserID").ToString
                    Pass = RSet("Pass").ToString
                End While
            End If
            RSet.Close()
            If UserId = "" Or Pass = "" Then
                ReadDoms = False
                Exit Function
            End If
            Dim XMLIN As String = Connect(Server + "/client/domlook.asp", UserId, Pass)
            If XMLIN = "Offline" Then
                ReadDoms = False
                Exit Function
            End If
            If XMLIN = "nouser" Or XMLIN = "nodom" Then
                ReadDoms = False
                Exit Function
            End If

            Dim m_xmld As XmlDocument
            Dim m_nodelist As XmlNodeList
            Dim m_node As XmlNode
            m_xmld = New XmlDocument()
            m_xmld.LoadXml(XMLIN)
            m_nodelist = m_xmld.SelectNodes("/records/domain")
            For Each m_node In m_nodelist
                Dim URL = m_node.ChildNodes.Item(0).InnerText
                Dim IP = m_node.ChildNodes.Item(1).InnerText
                Dim DISABLED = m_node.ChildNodes.Item(2).InnerText
                URL_Array.Add(URL)
                SQL = New OleDbCommand("SELECT  * FROM Domains WHERE URL = '" + URL + "'", Conn)
                RSet = SQL.ExecuteReader
                If RSet.HasRows = False Then
                    RSet.Close()
                    SQL = New OleDbCommand("INSERT INTO Domains (URL, Disabled, IP, Method) VALUES ('" & URL & "', '" & DISABLED & "', '" & IP & "', 'Default Detection Method')", Conn)
                    RSet = SQL.ExecuteReader
                    RSet.Close()
                Else
                    RSet.Close()
                    SQL = New OleDbCommand("UPDATE Domains SET IP = '" & IP & "', Disabled = '" & DISABLED & "' Where (URL = '" & URL & "')", Conn)
                    RSet = SQL.ExecuteReader
                    RSet.Close()
                End If

            Next

            SQL = New OleDbCommand("Select * From Domains", Conn)
            RSet = SQL.ExecuteReader
            If RSet.HasRows = False Then
            Else
                While RSet.Read
                    DB_Array.Add(RSet("URL").ToString)
                End While
            End If
            RSet.Close()
            URL_Array.Sort()
            DB_Array.Sort()
            For Each DBTR In DB_Array
                Result = URL_Array.BinarySearch(DBTR, New CaseInsensitiveComparer())
                If Result < 0 Then
                    SQL = New OleDbCommand("Delete From Domains Where URL = '" & DBTR & "'", Conn)
                    RSet = SQL.ExecuteReader
                End If
            Next
            RSet.Close()
            Conn.Close()

        Catch
            ReadDoms = False
            CreateError(Err.Description & " " & Err.Source, Err.Number)
        End Try
    End Function

    Public Function Maintain_IP_Detect() As Boolean
        Dim SQL As OleDbCommand
        Dim RSet As OleDbDataReader
        Dim LConn As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & System.AppDomain.CurrentDomain.BaseDirectory() & "progdb.mdb;")
        Dim Meth As String = ""
        Try
            SQL = New OleDbCommand("Select * from IP_Detection", LConn)
            LConn.Open()
            RSet = SQL.ExecuteReader
            If RSet.HasRows = False Then
                Exit Function
            Else
                While RSet.Read

                    Meth = RSet("Method").ToString

                    If Meth = "Adapter" Then
                        TAdapter(RSet("Ident").ToString, RSet("A_Index").ToString)
                    End If
                    If Meth = "Router" Then
                        UPDetect(RSet("Ident").ToString, RSet("URL").ToString, RSet("Keyword").ToString, RSet("UserID").ToString, RSet("Password").ToString)
                    End If
                End While
                RSet.Close()
                LConn.Close()
            End If
        Catch
            CreateError(Err.Description & " " & Err.Source, Err.Number)
        End Try
    End Function
    Private Function TAdapter(ByVal Name As String, ByVal IndexA As String) As Boolean
        Dim SQL As OleDbCommand
        Dim BConn As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & System.AppDomain.CurrentDomain.BaseDirectory() & "progdb.mdb;")
        Dim DSet As OleDbDataReader
        Try
            BConn.Open()
            Dim oSearcher As New System.Management.ManagementObjectSearcher("select * from Win32_NetworkAdapterConfiguration where index = " & IndexA & " ")
            Dim oObject As System.Management.ManagementObject
            Dim sIP() As String
            Dim Fin_IP As String = ""
            Dim Index As String = ""
            Dim Desc As String = ""
            Dim sString As String = ""
            Dim sMessage As String = ""
            For Each oObject In oSearcher.Get
                Index = Nothing
                Desc = Nothing
                sIP = Nothing
                If Not oObject("ipaddress") Is Nothing Then Index = oObject("Index")
                If Not oObject("ipaddress") Is Nothing Then Desc = oObject("Description")
                If Not oObject("ipaddress") Is Nothing Then sIP = oObject("ipaddress")
                If Not Index = "" Then
                    For Each sString In sIP
                        Fin_IP = sString
                    Next
                End If
            Next
            sMessage = ValidIP(Fin_IP)
            If sMessage = True Then
                SQL = New OleDbCommand("UPDATE IP_Detection SET IP = '" & Fin_IP & "' Where (Ident = '" & Name & "')", BConn)
                DSet = SQL.ExecuteReader

            Else
                SQL = New OleDbCommand("UPDATE IP_Detection SET Status = 'Inoperable' Where (Ident = '" & Name & "')", BConn)
                DSet = SQL.ExecuteReader

            End If
            BConn.Close()
        Catch
            CreateError(Err.Description & " " & Err.Source, Err.Number)
        End Try

    End Function
    Public Function UPDetect(ByVal Name As String, ByVal URL As String, Optional ByVal Keyword As String = "", Optional ByVal User As String = "", Optional ByVal Password As String = "") As Boolean
        Dim SQL As OleDbCommand
        Dim AConn As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & System.AppDomain.CurrentDomain.BaseDirectory() & "progdb.mdb;")
        Dim DSet As OleDbDataReader
        Try
            AConn.Open()
            Dim Page As String = ""
            Dim F_IP As String = ""
            Dim IsVal As Boolean = False
            Page = Connect(URL, User, Password)
            If Page = "Failed" Then
                SQL = New OleDbCommand("UPDATE IP_Detection SET Status = 'Inoperable' Where (Ident = '" & Name & "')", AConn)
                DSet = SQL.ExecuteReader
                Exit Function
            End If
            F_IP = FindIPInString(Page, Keyword)
            If F_IP = "Keyword not found" Then
                SQL = New OleDbCommand("UPDATE IP_Detection SET Status = 'Inoperable' Where (Ident = '" & Name & "')", AConn)
                DSet = SQL.ExecuteReader
                Exit Function
            End If
            IsVal = ValidIP(F_IP)
            If IsVal = False Then
                SQL = New OleDbCommand("UPDATE IP_Detection SET Status = 'Inoperable' Where (Ident = '" & Name & "')", AConn)
                DSet = SQL.ExecuteReader
                Exit Function
            Else
                SQL = New OleDbCommand("UPDATE IP_Detection SET IP = '" & F_IP & "' Where (Ident = '" & Name & "')", AConn)
                DSet = SQL.ExecuteReader
                Exit Function
            End If
            AConn.Close()
        Catch
            CreateError(Err.Description & " " & Err.Source, Err.Number)
        End Try
    End Function
    Public Function Send_Updates() As Boolean
        Dim UserId As String = ""
        Dim Pass As String = ""
        Dim Server As String = ""
        Dim Response As String = ""
        Dim SQL As OleDbCommand
        Dim RSet As OleDbDataReader
        Dim LConn As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & System.AppDomain.CurrentDomain.BaseDirectory() & "progdb.mdb;")

        Try

            SQL = New OleDbCommand("Select Server, UserID, Pass From Settings", LConn)
            LConn.Open()
            RSet = SQL.ExecuteReader
            If RSet.HasRows = False Then

                Exit Function
            Else
                While RSet.Read
                    Server = RSet("Server").ToString
                    UserId = RSet("UserID").ToString
                    Pass = RSet("Pass").ToString
                End While
            End If
            RSet.Close()

            SQL = New OleDbCommand("SELECT A1.URL, A1.Method, A2.IP FROM Domains A1, IP_Detection A2 WHERE A1.Method = A2.Ident And A1.IP Not Like A2.IP", LConn)

            RSet = SQL.ExecuteReader
            If RSet.HasRows = False Then
                Exit Function
            Else
                While RSet.Read
                    If RSet("method").ToString = "Default Detection Method" Then
                        Connect(Server + "/client/update.asp?host=" + RSet("URL").ToString + "", UserId, Pass)

                    Else
                        Connect(Server + "/client/update.asp?host=" + RSet("URL").ToString + "&myip=" + RSet("IP").ToString + "", UserId, Pass)

                    End If


                End While
                RSet.Close()
                LConn.Close()
            End If
        Catch
            CreateError(Err.Description & " " & Err.Source, Err.Number)
        End Try
    End Function
End Module
