Exemplo n.º 1
0
        public static bool RunRESTful(HttpListenerRequest request, HttpListenerResponse response)
        {
            byte[] data = new byte[0];
            try
            {
                StreamReader read        = new StreamReader(request.InputStream, Encoding.UTF8);
                string       OriginalXML = read.ReadToEnd();

                VulpesRESTfulVerb verb;
                switch (request.HttpMethod.ToLower())
                {
                case "get": verb = VulpesRESTfulVerb.GET; break;

                case "put": verb = VulpesRESTfulVerb.PUT; break;

                case "delete": verb = VulpesRESTfulVerb.DELETE; break;

                case "head": verb = VulpesRESTfulVerb.HEAD; break;

                case "post": verb = VulpesRESTfulVerb.POST; break;

                case "patch": verb = VulpesRESTfulVerb.PATCH; break;

                default:
                    response.AddHeader("Content-Type", "text/plain; charset=UTF-8");
                    response.StatusCode        = 501;
                    response.StatusDescription = "Not implemented";
                    //data = Encoding.UTF8.GetBytes("501 - Not implemented.");
                    return(true);
                }

                string URL = request.Url.LocalPath;
                Console.WriteLine(verb.ToString() + " " + URL);
                string CuttedParameters = "";
                if (URL.ToLower().StartsWith(Settings.Default.URLPart.ToLower()) == true)
                {
                    URL = URL.Substring(Settings.Default.URLPart.Length, URL.Length - Settings.Default.URLPart.Length);
                }
                string Auth = request.Headers["Authorization"];
                if (Auth == null)
                {
                    Auth = "";
                }
                Auth = Auth.ToLower();
                if (Auth.StartsWith("bearer ") == true)
                {
                    Auth = Auth.Substring(6, Auth.Length - 6).Trim();
                }
                else
                {
                    Auth = "";
                }

                string ClientIPAddress   = GetClientIP(request);
                NetworkConnectionInfo ni = NetworkConnection.GetSession(Auth);
                if (ni != null)
                {
                    ni.IPAddress = ClientIPAddress;
                }
                RESTfulElement CurrentR = null;
                foreach (RESTfulElement r in RESTfulElements)
                {
                    if (URL.ToLower().StartsWith(r.URL.ToLower()) == true && r.Verb == verb)
                    {
                        CuttedParameters = URL.Substring(r.URL.Length, URL.Length - r.URL.Length);
                        if (CuttedParameters.StartsWith("/") == true && r.GetValues != "")
                        {
                            CuttedParameters = CuttedParameters.Substring(1, CuttedParameters.Length - 1);
                        }
                        else
                        if (CuttedParameters.StartsWith("/") == true && r.GetValues == "")
                        {
                            continue;
                        }
                        else
                        if (CuttedParameters == "" && r.GetValues != "")
                        {
                            continue;
                        }

                        if (r.RequireNi == true && ni == null)
                        {
                            response.AddHeader("Content-Type", "text/plain; charset=UTF-8");
                            response.StatusCode        = 403;
                            response.StatusDescription = "Forbidden";
                            //data = Encoding.UTF8.GetBytes("403 - Forbidden.");
                            return(true);
                        }
                        else
                        {
                            CurrentR = r;
                            break;
                        }
                    }
                }

                if (CurrentR == null)
                {
                    response.AddHeader("Content-Type", "text/plain; charset=UTF-8");
                    response.StatusCode        = 404;
                    response.StatusDescription = "Not found";
                    //data = Encoding.UTF8.GetBytes("404 - Not found.");
                    return(true);
                }

                if (RESTfulProtected.Contains(CurrentR) == true)
                {
                    if (string.IsNullOrWhiteSpace(SettingsManager.Settings.AdminIPAddresses) == false)
                    {
                        IPAddress ip = request.RemoteEndPoint.Address;
                        if (ip.ToString() != IPAddress.Loopback.ToString() && ip.ToString() != IPAddress.IPv6Loopback.ToString())
                        {
                            bool IPInRange = false;
                            foreach (string s in SettingsManager.Settings.AdminIPAddresses.Split(','))
                            {
                                if (s.Contains("/") == true)
                                {
                                    IPNetwork ipn;
                                    if (IPNetwork.TryParse(s, out ipn) == true)
                                    {
                                        IPNetwork ipnn = IPNetwork.Parse(ip, IPAddress.Broadcast);
                                        if (ipn.Overlap(ipnn) == true)
                                        {
                                            IPInRange = true;
                                            break;
                                        }
                                    }
                                }
                            }
                            if (IPInRange == false)
                            {
                                response.AddHeader("Content-Type", "text/plain; charset=UTF-8");
                                response.StatusCode        = 403;
                                response.StatusDescription = "Forbidden";
                                return(true);
                            }
                        }
                    }
                }

                ParameterInfo Param = CurrentR.Method.GetParameters()[1];

                List <object> Params = new List <object>();
                Params.Add(ni == null ? null : ni.sql);
                if (CurrentR.RawDataProcessing == true)
                {
                    Params.Add(request);
                    Params.Add(response);
                }
                Params.Add(JsonConvert.DeserializeObject(OriginalXML, Param.ParameterType));
                Params.Add(ni);
                if (CurrentR.PutIPAddress == true)
                {
                    Params.Add(ClientIPAddress);
                }
                if (CurrentR.WithQueryString == true)
                {
                    Params.Add(request.QueryString);
                }

                if (CurrentR.GetValues != "")
                {
                    ParameterInfo[] paramsi = CurrentR.Method.GetParameters();
                    if (paramsi.Length < 4)
                    {
                        response.AddHeader("Content-Type", "text/plain; charset=UTF-8");
                        response.StatusCode        = 404;
                        response.StatusDescription = "Not found";
                        //data = Encoding.UTF8.GetBytes("404 - Not found.");
                        return(true);
                    }

                    int      CurrentParam         = 3 + (CurrentR.RawDataProcessing == true ? 2 : 0);
                    string[] CuttedParametersList = CuttedParameters.Split('/');
                    string[] ParamsDef            = CurrentR.GetValues.Split('/');

                    if (CuttedParametersList.Length != ParamsDef.Length)
                    {
                        response.AddHeader("Content-Type", "text/plain; charset=UTF-8");
                        response.StatusCode        = 404;
                        response.StatusDescription = "Not found";
                        //data = Encoding.UTF8.GetBytes("404 - Not found.");
                        return(true);
                    }

                    foreach (string g in ParamsDef)
                    {
                        if (paramsi.Length < CurrentParam + 1)
                        {
                            response.AddHeader("Content-Type", "text/plain; charset=UTF-8");
                            response.StatusCode        = 404;
                            response.StatusDescription = "Not found";
                            //data = Encoding.UTF8.GetBytes("404 - Not found.");
                            return(true);
                        }
                        if (g != paramsi[CurrentParam].Name)
                        {
                            response.AddHeader("Content-Type", "text/plain; charset=UTF-8");
                            response.StatusCode        = 500;
                            response.StatusDescription = "Server Error";
#if DEBUG
                            data = Encoding.UTF8.GetBytes("500 - Server Error. Bad param definition");
#else
                            //data = Encoding.UTF8.GetBytes("500 - Server Error.");
#endif
                            return(true);
                        }
                        try
                        {
                            Params.Add(Convert.ChangeType(CuttedParametersList[CurrentParam - (CurrentR.RawDataProcessing == true ? 5 : 3)], paramsi[CurrentParam].ParameterType));
                        }
                        catch (Exception ee)
                        {
                            Debug.WriteLine(ee.ToString());
                            response.AddHeader("Content-Type", "text/plain; charset=UTF-8");
                            response.StatusCode        = 404;
                            response.StatusDescription = "Not found";
#if DEBUG
                            data = Encoding.UTF8.GetBytes("404 - Not found. " + ee.ToString());
#else
                            //data = Encoding.UTF8.GetBytes("404 - Not found.");
#endif
                            return(true);
                        }
                        CurrentParam++;
                    }
                }

                object     instance = Activator.CreateInstance(CurrentR.Method.DeclaringType);
                RESTStatus res;
                if (ni == null)
                {
                    res = (RESTStatus)(CurrentR.Method.Invoke(instance, Params.ToArray()));
                }
                else
                {
                    if (CurrentR.UseLock == false)
                    {
                        res = (RESTStatus)(CurrentR.Method.Invoke(instance, Params.ToArray()));
                    }
                    else
                    {
                        try
                        {
                            ni.RWLock.EnterReadLock();
                            res = (RESTStatus)(CurrentR.Method.Invoke(instance, Params.ToArray()));
                        }
                        catch (Exception ee)
                        {
                            Debug.WriteLine(ee.ToString());
                            throw;
                        }
                        finally
                        {
                            ni.RWLock.ExitReadLock();
                        }
                    }
                }
                if (CurrentR.RawDataProcessing == true)
                {
                    data = new byte[0];
                    return(true);
                }

                switch (res)
                {
                case RESTStatus.Created:
                    response.AddHeader("Content-Type", "text/plain; charset=UTF-8");
                    response.StatusCode        = 201;
                    response.StatusDescription = "Created";
                    if (CurrentR.ReturnValueName != "")
                    {
                        foreach (FieldInfo f in CurrentR.Method.DeclaringType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public))
                        {
                            VulpesRESTfulRet ret = f.GetCustomAttribute <VulpesRESTfulRet>();
                            if (ret != null)
                            {
                                if (ret.Name == CurrentR.ReturnValueName)
                                {
                                    data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(f.GetValue(instance)));
                                    break;
                                }
                            }
                        }
                    }
                    return(true);

                case RESTStatus.Fail:
                    response.AddHeader("Content-Type", "text/plain; charset=UTF-8");
                    response.StatusCode        = 490;
                    response.StatusDescription = "Did not work";
                    if (CurrentR.ReturnValueName != "")
                    {
                        foreach (FieldInfo f in CurrentR.Method.DeclaringType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public))
                        {
                            VulpesRESTfulRet ret = f.GetCustomAttribute <VulpesRESTfulRet>();
                            if (ret != null)
                            {
                                if (ret.Name == CurrentR.ReturnValueName)
                                {
                                    data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(f.GetValue(instance)));
                                    break;
                                }
                            }
                        }
                    }
                    //if (data.Length == 0)
                    //    data = Encoding.UTF8.GetBytes("490 - Did not work.");
                    return(true);

                case RESTStatus.NoContent:
                    response.AddHeader("Content-Type", "text/plain; charset=UTF-8");
                    response.StatusCode        = 204;
                    response.StatusDescription = "No Content";
                    return(true);

                case RESTStatus.NotFound:
                    response.AddHeader("Content-Type", "text/plain; charset=UTF-8");
                    response.StatusCode        = 404;
                    response.StatusDescription = "Not found";
                    //data = Encoding.UTF8.GetBytes("404 - Not found.");
                    return(true);

                case RESTStatus.ServerError:
                    response.AddHeader("Content-Type", "text/plain; charset=UTF-8");
                    response.StatusCode        = 500;
                    response.StatusDescription = "Server Error";
                    //data = Encoding.UTF8.GetBytes("500 - Server Error.");
                    return(true);

                case RESTStatus.Denied:
                    response.AddHeader("Content-Type", "text/plain; charset=UTF-8");
                    response.StatusCode        = 403;
                    response.StatusDescription = "Forbidden";
                    //data = Encoding.UTF8.GetBytes("403 - Forbidden.");
                    return(true);

                case RESTStatus.Success:
                    if (CurrentR.ReturnValueName != "")
                    {
                        foreach (FieldInfo f in CurrentR.Method.DeclaringType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public))
                        {
                            VulpesRESTfulRet ret = f.GetCustomAttribute <VulpesRESTfulRet>();
                            if (ret != null)
                            {
                                if (ret.Name == CurrentR.ReturnValueName)
                                {
                                    data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(f.GetValue(instance)));
                                    break;
                                }
                            }
                        }
                    }
                    return(true);
                }
            }
            catch (Exception ee)
            {
                FoxEventLog.WriteEventLog("REST SEH: " + ee.ToString(), EventLogEntryType.Error);

                Debug.WriteLine(ee.ToString());
                try
                {
                    response.AddHeader("Content-Type", "text/plain; charset=UTF-8");
                    response.StatusCode        = 500;
                    response.StatusDescription = "Server Error";
#if DEBUG
                    data = Encoding.UTF8.GetBytes("500 - Server Error. " + ee.ToString());
#else
                    //data = Encoding.UTF8.GetBytes("500 - Server Error.");
#endif
                }
                catch (Exception eee)
                {
                    Debug.WriteLine(eee.ToString());
                }
                return(true);
            }
            finally
            {
                if (data.Length > 0)
                {
                    response.ContentLength64 = data.LongLength;
                    Stream output = response.OutputStream;
                    output.Write(data, 0, data.Length);
                }
            }

            return(true);
        }
Exemplo n.º 2
0
        public RESTStatus ReportEventLog(SQLLib sql, ListEventLogReport EventLogList, NetworkConnectionInfo ni)
        {
            if (ni.HasAcl(ACLFlags.ComputerLogin) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

            EventLogList.MachineID = ni.Username;

            lock (ni.sqllock)
            {
                if (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM ComputerAccounts WHERE MachineID=@m",
                                                      new SQLParam("@m", EventLogList.MachineID))) == 0)
                {
                    ni.Error   = "Invalid MachineID";
                    ni.ErrorID = ErrorFlags.InvalidValue;
                    return(RESTStatus.Denied);
                }
            }

            if (EventLogList.Items == null)
            {
                ni.Error   = "Invalid Items";
                ni.ErrorID = ErrorFlags.InvalidValue;
                return(RESTStatus.Fail);
            }

            if (EventLogList.Items.Count == 0)
            {
                return(RESTStatus.Created);
            }

            DateTime DT = DateTime.Now;

            foreach (EventLogReport ar in EventLogList.Items)
            {
                if (NullTest.Test(ar) == false)
                {
                    ni.Error   = "Invalid Items";
                    ni.ErrorID = ErrorFlags.InvalidValue;
                    return(RESTStatus.Fail);
                }
                CommonUtilities.CalcEventLogID(ar);
            }

            List <SQLParam> sqlparams = new List <SQLParam>();

            sqlparams.Add(new SQLParam("@id", EventLogList.MachineID));
            int    count = 1;
            string vars  = "";

            foreach (EventLogReport ar in EventLogList.Items)
            {
                sqlparams.Add(new SQLParam("@p" + count.ToString(), ar.LogID));
                vars += "@p" + count.ToString() + ",";
                count++;
            }
            if (vars.EndsWith(",") == true)
            {
                vars = vars.Substring(0, vars.Length - 1);
            }

            List <string> LogIDinDB = new List <string>();

            lock (ni.sqllock)
            {
                SqlDataReader dr = sql.ExecSQLReader("SELECT LogID FROM EventLog WHERE MachineID=@id and LogID in (" + vars + ")", sqlparams.ToArray());
                while (dr.Read())
                {
                    LogIDinDB.Add(Convert.ToString(dr["LogID"]));
                }
                dr.Close();
            }

            List <EventLogReport> RemoveEVL = new List <EventLogReport>();

            foreach (EventLogReport ar in EventLogList.Items)
            {
                if (LogIDinDB.Contains(ar.LogID) == true)
                {
                    RemoveEVL.Add(ar);
                    continue;
                }
                if (SettingsManager.Settings.KeepEventLogDays > 0)
                {
                    if (ar.TimeGenerated < DateTime.UtcNow.AddDays(0 - SettingsManager.Settings.KeepEventLogDays))
                    {
                        RemoveEVL.Add(ar);
                        continue;
                    }
                }
            }

            foreach (EventLogReport ar in RemoveEVL)
            {
                EventLogList.Items.Remove(ar);
            }

            List <EventLogReportFull> car = new List <EventLogReportFull>();

            lock (ni.sqllock)
            {
                try
                {
                    sql.BeginTransaction();
                    sql.SEHError = true;

                    foreach (EventLogReport ar in EventLogList.Items)
                    {
                        EventLogReportFull arr = new EventLogReportFull();
                        ClassCopy.CopyClassData(ar, arr);
                        arr.Reported  = DateTime.UtcNow;
                        arr.MachineID = EventLogList.MachineID;
                        List <SQLData> d = sql.InsertFromClassPrep(arr);
                        foreach (SQLData dd in d)
                        {
                            if (dd.Column == "ID")
                            {
                                dd.Data = DBNull.Value;
                                break;
                            }
                        }
                        car.Add(arr);
                        sql.InsertFromClass("EventLog", arr);
                    }
                    sql.CommitTransaction();
                }
                catch (Exception ee)
                {
                    sql.RollBackTransaction();
                    FoxEventLog.WriteEventLog("DB Error: Cannot insert data to EventLog: " + ee.ToString() + "\r\n\r\nJSON: " +
                                              JsonConvert.SerializeObject(car, Formatting.Indented), System.Diagnostics.EventLogEntryType.Error);
                    return(RESTStatus.ServerError);
                }
                finally
                {
                    sql.SEHError = false;
                }
            }

            Thread t = new Thread(new ParameterizedThreadStart(new DReportingThread(ReportingThread)));

            t.Start(car);

            return(RESTStatus.Created);
        }
Exemplo n.º 3
0
        public RESTStatus ReportStatups(SQLLib sql, ListStartupItems StartupList, NetworkConnectionInfo ni)
        {
            if (ni.HasAcl(ACLFlags.ComputerLogin) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

            StartupList.MachineID = ni.Username;

            lock (ni.sqllock)
            {
                if (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM ComputerAccounts WHERE MachineID=@m",
                                                      new SQLParam("@m", StartupList.MachineID))) == 0)
                {
                    ni.Error   = "Invalid MachineID";
                    ni.ErrorID = ErrorFlags.InvalidValue;
                    return(RESTStatus.Denied);
                }
            }

            if (StartupList.Items == null)
            {
                ni.Error   = "Invalid Items";
                ni.ErrorID = ErrorFlags.InvalidValue;
                return(RESTStatus.Fail);
            }
            if (StartupList.SIDUsers == null)
            {
                StartupList.SIDUsers = new List <string>();
            }

            foreach (StartupItem rep in StartupList.Items)
            {
                if (string.IsNullOrWhiteSpace(rep.Location) == true)
                {
                    ni.Error   = "Invalid Items";
                    ni.ErrorID = ErrorFlags.InvalidValue;
                    return(RESTStatus.Fail);
                }
                if (string.IsNullOrWhiteSpace(rep.Key) == true)
                {
                    ni.Error   = "Invalid Items";
                    ni.ErrorID = ErrorFlags.InvalidValue;
                    return(RESTStatus.Fail);
                }

                if (string.IsNullOrWhiteSpace(rep.HKCUUser) == true)
                {
                    rep.HKCUUser = "";
                }
                if (string.IsNullOrWhiteSpace(rep.Item) == true)
                {
                    rep.Item = "";
                }
            }

            List <StartupItem> Installed = new List <StartupItem>();
            List <StartupItem> Reported  = StartupList.Items;

            lock (ni.sqllock)
            {
                SqlDataReader dr = sql.ExecSQLReader("SELECT * FROM Startups WHERE MachineID=@id", new SQLParam("@id", StartupList.MachineID));
                while (dr.Read())
                {
                    StartupItem ar = new StartupItem();
                    ar.Location = Convert.ToString(dr["Location"]);
                    ar.Key      = Convert.ToString(dr["Key"]);
                    ar.Item     = Convert.ToString(dr["Item"]);
                    ar.HKCUUser = Convert.ToString(dr["HKCUUser"]);
                    if (string.IsNullOrWhiteSpace(ar.HKCUUser) == true)
                    {
                        ar.HKCUUser = "";
                    }

                    Installed.Add(ar);
                }
                dr.Close();
            }

            List <StartupItem> Updated   = new List <StartupItem>();
            List <StartupItem> Unchanged = new List <StartupItem>();
            List <StartupItem> Removed   = new List <StartupItem>();
            List <StartupItem> Added     = new List <StartupItem>();

            foreach (StartupItem inst in Installed)
            {
                inst.Location = inst.Location.Trim();
                inst.Key      = inst.Key.Trim();
                inst.Item     = inst.Item.Trim();
                inst.HKCUUser = inst.HKCUUser.Trim();

                bool Found = false;
                foreach (StartupItem rep in Reported)
                {
                    rep.Location = rep.Location.Trim();
                    rep.Key      = rep.Key.Trim();
                    rep.Item     = rep.Item.Trim();
                    rep.HKCUUser = rep.HKCUUser.Trim();

                    if (rep.Location.ToLower() == inst.Location.ToLower() && rep.Key == inst.Key && rep.HKCUUser == inst.HKCUUser)
                    {
                        if (rep.Item.ToLower() == inst.Item.ToLower())
                        {
                            Unchanged.Add(rep);
                            Found = true;
                            break;
                        }
                        else
                        {
                            Updated.Add(rep);
                            Found = true;
                            break;
                        }
                    }
                }
                if (Found == false)
                {
                    if (inst.HKCUUser != "" && StartupList.SIDUsers.Contains(inst.HKCUUser, StringComparer.InvariantCultureIgnoreCase) == false)
                    {
                        //likely that this user is not logged on or such
                        Unchanged.Add(inst);
                    }
                    else
                    {
                        Removed.Add(inst);
                    }
                }
            }

            foreach (StartupItem inst in Reported)
            {
                bool Found = false;
                foreach (StartupItem rep in Installed)
                {
                    if (rep.Key.ToLower() == inst.Key.ToLower() && rep.Location == inst.Location && rep.HKCUUser == inst.HKCUUser)
                    {
                        Found = true;
                        break;
                    }
                }
                if (Found == false)
                {
                    Added.Add(inst);
                }
            }

            lock (ni.sqllock)
            {
                try
                {
                    sql.BeginTransaction();
                    sql.SEHError = true;
                    foreach (StartupItem ar in Removed)
                    {
                        sql.ExecSQL("DELETE FROM Startups WHERE MachineID=@id AND [Key]=@key AND Location=@location AND HKCUUser=@user",
                                    new SQLParam("@id", StartupList.MachineID),
                                    new SQLParam("@key", ar.Key),
                                    new SQLParam("@user", ar.HKCUUser),
                                    new SQLParam("@location", ar.Location));
                    }
                    foreach (StartupItem ar in Updated)
                    {
                        sql.ExecSQL(@"UPDATE Startups SET
                            Item=@item,
                            DT=@DT
                            WHERE MachineID=@id AND [Key]=@key AND Location=@location AND HKCUUser=@user",
                                    new SQLParam("@id", StartupList.MachineID),
                                    new SQLParam("@key", ar.Key),
                                    new SQLParam("@user", ar.HKCUUser),
                                    new SQLParam("@location", ar.Location),
                                    new SQLParam("@item", ar.Item),
                                    new SQLParam("@DT", DateTime.UtcNow));
                    }
                    foreach (StartupItem ar in Added)
                    {
                        sql.InsertMultiData("Startups",
                                            new SQLData("MachineID", StartupList.MachineID),
                                            new SQLData("Item", ar.Item),
                                            new SQLData("Location", ar.Location),
                                            new SQLData("Key", ar.Key),
                                            new SQLData("HKCUUser", ar.HKCUUser),
                                            new SQLData("DT", DateTime.UtcNow));
                    }
                    sql.CommitTransaction();
                }
                catch (Exception ee)
                {
                    sql.RollBackTransaction();
                    FoxEventLog.WriteEventLog("DB Error: Cannot update Startups: " + ee.ToString(), System.Diagnostics.EventLogEntryType.Error);
                    return(RESTStatus.ServerError);
                }
                finally
                {
                    sql.SEHError = false;
                }
            }

            StartupLst l = new StartupLst();

            l.Added     = Added;
            l.Removed   = Removed;
            l.Unchanged = Unchanged;
            l.Updated   = Updated;
            l.MachineID = StartupList.MachineID;
            Thread t = new Thread(new ParameterizedThreadStart(new DReportingThread(ReportingThread)));

            t.Start(l);

            return(RESTStatus.Created);
        }
Exemplo n.º 4
0
        void ReportingThread(object StartupListO)
        {
            try
            {
                using (SQLLib sql = SQLTest.ConnectSQL("Fox SDC Server for Startup Data"))
                {
                    if (sql == null)
                    {
                        FoxEventLog.WriteEventLog("Cannot connect to SQL Server for Startup Reporting!", System.Diagnostics.EventLogEntryType.Error);
                        return;
                    }
                    StartupLst   StartupList  = (StartupLst)StartupListO;
                    ComputerData computerdata = Computers.GetComputerDetail(sql, StartupList.MachineID);
                    if (computerdata == null)
                    {
                        FoxEventLog.WriteEventLog("Cannot get any computer data for Startup Reporting!", System.Diagnostics.EventLogEntryType.Error);
                        return;
                    }

                    List <PolicyObject>        Pol             = Policies.GetPolicyForComputerInternal(sql, StartupList.MachineID);
                    Dictionary <string, Int64> AlreadyReported = new Dictionary <string, long>();
                    foreach (PolicyObject PolO in Pol)
                    {
                        if (PolO.Type != PolicyIDs.ReportingPolicy)
                        {
                            continue;
                        }
                        ReportingPolicyElement RepElementRoot = JsonConvert.DeserializeObject <ReportingPolicyElement>(Policies.GetPolicy(sql, PolO.ID).Data);
                        if (RepElementRoot.Type != ReportingPolicyType.Startup)
                        {
                            continue;
                        }
                        if (RepElementRoot.ReportToAdmin == null)
                        {
                            RepElementRoot.ReportToAdmin = false;
                        }
                        if (RepElementRoot.ReportToClient == null)
                        {
                            RepElementRoot.ReportToClient = false;
                        }
                        if (RepElementRoot.UrgentForAdmin == null)
                        {
                            RepElementRoot.UrgentForAdmin = false;
                        }
                        if (RepElementRoot.UrgentForClient == null)
                        {
                            RepElementRoot.UrgentForClient = false;
                        }
                        if (RepElementRoot.ReportToAdmin == false && RepElementRoot.ReportToClient == false && RepElementRoot.UrgentForAdmin == false && RepElementRoot.UrgentForClient == false)
                        {
                            continue;
                        }

                        foreach (string Element in RepElementRoot.ReportingElements)
                        {
                            ReportingPolicyElementStartup arprep = JsonConvert.DeserializeObject <ReportingPolicyElementStartup>(Element);
                            if (arprep.NotifyOnAdd == false && arprep.NotifyOnRemove == false && arprep.NotifyOnUpdate == false)
                            {
                                continue;
                            }

                            if (arprep.NotifyOnAdd == true)
                            {
                                foreach (StartupItem ar in GetFilteredData(StartupList.Added, computerdata, arprep))
                                {
                                    ReportThings(sql, StartupList.MachineID, "Add", ar, ref AlreadyReported, RepElementRoot);
                                }
                            }

                            if (arprep.NotifyOnUpdate == true)
                            {
                                foreach (StartupItem ar in GetFilteredData(StartupList.Updated, computerdata, arprep))
                                {
                                    ReportThings(sql, StartupList.MachineID, "Update", ar, ref AlreadyReported, RepElementRoot);
                                }
                            }

                            if (arprep.NotifyOnRemove == true)
                            {
                                foreach (StartupItem ar in GetFilteredData(StartupList.Removed, computerdata, arprep))
                                {
                                    ReportThings(sql, StartupList.MachineID, "Remove", ar, ref AlreadyReported, RepElementRoot);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ee)
            {
                FoxEventLog.WriteEventLog("SEH in Startup Reporting " + ee.ToString(), System.Diagnostics.EventLogEntryType.Error);
            }
        }
Exemplo n.º 5
0
        public RESTStatus ReportDiskData(SQLLib sql, ListDiskDataReport DiskDataList, NetworkConnectionInfo ni)
        {
            if (ni.HasAcl(ACLFlags.ComputerLogin) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

            DiskDataList.MachineID = ni.Username;
            lock (ni.sqllock)
            {
                if (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM ComputerAccounts WHERE MachineID=@m",
                                                      new SQLParam("@m", DiskDataList.MachineID))) == 0)
                {
                    ni.Error   = "Invalid MachineID";
                    ni.ErrorID = ErrorFlags.InvalidValue;
                    return(RESTStatus.NotFound);
                }
            }

            if (DiskDataList.Items == null)
            {
                ni.Error   = "Invalid Items";
                ni.ErrorID = ErrorFlags.InvalidValue;
                return(RESTStatus.Fail);
            }

            lock (ni.sqllock)
            {
                sql.ExecSQL("UPDATE DiskData SET DevicePresent=0 WHERE MachineID=@m",
                            new SQLParam("@m", DiskDataList.MachineID));
            }
            foreach (DiskDataReport dr in DiskDataList.Items)
            {
                lock (ni.sqllock)
                {
                    sql.ExecSQL("DELETE FROM DiskData WHERE MachineID=@m AND DeviceID=@d",
                                new SQLParam("@d", dr.DeviceID),
                                new SQLParam("@m", DiskDataList.MachineID));
                }
            }

            List <List <SQLData> > bulkdata = new List <List <SQLData> >();
            DateTime DT = DateTime.Now;

            DiskDataReport cdr = null;

            lock (ni.sqllock)
            {
                try
                {
                    sql.BeginTransaction();
                    sql.SEHError = true;

                    foreach (DiskDataReport dr in DiskDataList.Items)
                    {
                        sql.InsertMultiData("DiskData",
                                            new SQLData("MachineID", dr.MachineID),
                                            new SQLData("DevicePresent", true),
                                            new SQLData("LastUpdated", DT),
                                            new SQLData("DeviceID", dr.DeviceID),
                                            new SQLData("Access", dr.Access),
                                            new SQLData("Automount", dr.Automount),
                                            new SQLData("Availability", dr.Availability),
                                            new SQLData("Capacity", dr.Capacity),
                                            new SQLData("Caption", dr.Caption),
                                            new SQLData("Compressed", dr.Compressed),
                                            new SQLData("ConfigManagerErrorCode", dr.ConfigManagerErrorCode),
                                            new SQLData("Description", dr.Description),
                                            new SQLData("DirtyBitSet", dr.DirtyBitSet),
                                            new SQLData("DriveLetter", dr.DriveLetter),
                                            new SQLData("DriveType", dr.DriveType),
                                            new SQLData("ErrorDescription", dr.ErrorDescription),
                                            new SQLData("ErrorMethodology", dr.ErrorMethodology),
                                            new SQLData("FileSystem", dr.FileSystem),
                                            new SQLData("FreeSpace", dr.FreeSpace),
                                            new SQLData("Label", dr.Label),
                                            new SQLData("LastErrorCode", dr.LastErrorCode),
                                            new SQLData("MaximumFileNameLength", dr.MaximumFileNameLength),
                                            new SQLData("Name", dr.Name),
                                            new SQLData("PNPDeviceID", dr.PNPDeviceID),
                                            new SQLData("SerialNumber", dr.SerialNumber),
                                            new SQLData("Status", dr.Status));
                    }
                    sql.CommitTransaction();
                }
                catch (Exception ee)
                {
                    sql.RollBackTransaction();
                    FoxEventLog.WriteEventLog("DB Error: Cannot insert data to DiskData: " + ee.ToString() + "\r\n\r\nJSON: " +
                                              JsonConvert.SerializeObject(cdr, Formatting.Indented), System.Diagnostics.EventLogEntryType.Error);
                    return(RESTStatus.ServerError);
                }
                finally
                {
                    sql.SEHError = false;
                }
            }

            Thread t = new Thread(new ParameterizedThreadStart(new DReportingThread(ReportingThread)));

            t.Start(DiskDataList);

            return(RESTStatus.Success);
        }
Exemplo n.º 6
0
        public static List <PolicyObject> GetPolicyForComputerInternal(SQLLib sql, string MachineID)
        {
            PolicyObjectList PolicyListSigned = new PolicyObjectList();

            PolicyListSigned.Items = new List <PolicyObject>();

            SqlDataReader dr;

            dr = sql.ExecSQLReader("SELECT * FROM Policies WHERE MachineID=@m AND Enabled=1",
                                   new SQLParam("@m", MachineID));
            while (dr.Read())
            {
                PolicyObject obj = LoadPolicyDB(dr, false, false);
                PolicyListSigned.Items.Add(obj);
            }
            dr.Close();

            Int64? GroupID = null;
            object sqlo    = sql.ExecSQLScalar("select Grouping from ComputerAccounts where MachineID=@m", new SQLParam("@m", MachineID));

            if (sqlo is DBNull || sqlo == null)
            {
                GroupID = null;
            }
            else
            {
                GroupID = Convert.ToInt64(sqlo);
            }

            do
            {
                dr = sql.ExecSQLReader("SELECT * FROM Policies WHERE " + (GroupID == null ? "Grouping is NULL" : "Grouping=@g") + " AND Enabled=1 AND MachineID is NULL",
                                       new SQLParam("@g", GroupID));
                while (dr.Read())
                {
                    PolicyObject obj = LoadPolicyDB(dr, false, false);
                    PolicyListSigned.Items.Add(obj);
                }
                dr.Close();

                if (GroupID != null)
                {
                    sqlo = sql.ExecSQLScalar("select ParentID FROM Grouping WHERE ID=@g", new SQLParam("@g", GroupID));
                    if (sqlo is DBNull || sqlo == null)
                    {
                        GroupID = null;
                    }
                    else
                    {
                        GroupID = Convert.ToInt64(sqlo);
                    }
                }
                else
                {
                    break;
                }
            } while (true);

            PolicyListSigned.Items.Reverse();
            Int64 Count = 1;

            foreach (PolicyObject p in PolicyListSigned.Items)
            {
                p.Order = Count;
                Count++;
            }

            #region Resolve Linked Policies for client

            for (int i = 0; i < PolicyListSigned.Items.Count; i++)
            {
                PolicyObject pol = PolicyListSigned.Items[i];
                if (pol.Type == PolicyIDs.LinkedPolicy)
                {
                    List <Int64> RunningIDs = new List <Int64>();

                    PolicyObject po = pol;

                    while (true)
                    {
                        if (RunningIDs.Contains(po.ID) == true)
                        {
                            FoxEventLog.WriteEventLog("Policy ID " + pol.ID.ToString() + " (" + pol.Name + ") creates a loop!", System.Diagnostics.EventLogEntryType.Warning);
                            break;
                        }

                        RunningIDs.Add(po.ID);

                        Int64 PolID;
                        po.Data = Convert.ToString(sql.ExecSQLScalar("SELECT DataBlob FROM Policies WHERE ID=@id",
                                                                     new SQLParam("@id", po.ID)));
                        if (Int64.TryParse(po.Data, out PolID) == false)
                        {
                            FoxEventLog.WriteEventLog("Cannot read data of policy ID " + po.ID.ToString() + " (" + po.Name + ") for linking.", System.Diagnostics.EventLogEntryType.Warning);
                            break;
                        }

                        if (Policies.PolicyExsits(sql, PolID) == false)
                        {
                            FoxEventLog.WriteEventLog("Policy ID " + PolID.ToString() + " referencing from " + po.ID.ToString() + " (" + po.Name + ") does not exist.", System.Diagnostics.EventLogEntryType.Warning);
                            break;
                        }

                        if (Convert.ToInt32(sql.ExecSQLScalar("SELECT Enabled FROM Policies WHERE ID=@id", new SQLParam("@id", PolID))) != 1)
                        {
                            break;
                        }

                        dr = sql.ExecSQLReader("SELECT * FROM Policies WHERE ID=@id",
                                               new SQLParam("@id", PolID));
                        dr.Read();
                        po = LoadPolicyDB(dr, false, false);
                        dr.Close();
                        if (po == null)
                        {
                            FoxEventLog.WriteEventLog("Cannot read policy ID for linking " + PolID.ToString(), System.Diagnostics.EventLogEntryType.Warning);
                            break;
                        }
                        if (po.Type != PolicyIDs.LinkedPolicy)
                        {
                            pol = po;
                            PolicyListSigned.Items[i] = po;
                            break;
                        }
                    }
                }
            }

            #endregion

            return(PolicyListSigned.Items);
        }
Exemplo n.º 7
0
        public RESTStatus ComputerLogin(SQLLib sql, ComputerLogon logon, NetworkConnectionInfo ni, string IPAddress)
        {
            Err = new ErrorInfo();

            if (logon == null)
            {
                Err.Error   = "Faulty data";
                Err.ErrorID = (int)ErrorFlags.FaultyData;
                return(RESTStatus.Fail);
            }

            if (NullTest.Test(logon) == false)
            {
                Err.Error   = "Invalid data";
                Err.ErrorID = (int)ErrorFlags.InvalidData;
                return(RESTStatus.Fail);
            }

            if (logon.SysInfo != null)
            {
                if (logon.SysInfo.BIOSType == null)
                {
                    logon.SysInfo.BIOSType = "N/A";
                }
                if (logon.SysInfo.CPUName == null)
                {
                    logon.SysInfo.CPUName = "N/A";
                }
                if (logon.SysInfo.SecureBootState == null)
                {
                    logon.SysInfo.SecureBootState = "N/A";
                }
                if (logon.SysInfo.ComputerModel == null)
                {
                    logon.SysInfo.ComputerModel = "N/A";
                }
                if (logon.SysInfo.ComputerModel.Trim() == "")
                {
                    logon.SysInfo.ComputerModel = "N/A";
                }
                if (logon.SysInfo.SystemRoot == null)
                {
                    logon.SysInfo.SystemRoot = "C:\\Windows";
                }
                if (logon.SysInfo.SUSID == null)
                {
                    logon.SysInfo.SUSID = "";
                }
                if (logon.SysInfo.SUSID.Trim() == "")
                {
                    logon.SysInfo.SUSID = Consts.NullGUID;
                }
                if (logon.SysInfo.LegacyUCID == null)
                {
                    logon.SysInfo.LegacyUCID = Consts.NullUCID;
                }
            }

            if (NullTest.Test(logon.SysInfo, "IsMeteredConnection", "RunningInWindowsPE") == false)
            {
                Err.Error   = "Invalid data";
                Err.ErrorID = (int)ErrorFlags.InvalidData;
                return(RESTStatus.Fail);
            }

            if (string.IsNullOrWhiteSpace(logon.Password) == true || string.IsNullOrWhiteSpace(logon.Username) == true)
            {
                Err.Error   = "Invalid data";
                Err.ErrorID = (int)ErrorFlags.InvalidData;
                return(RESTStatus.Fail);
            }

            if (NullTest.TestBlankString(logon.SysInfo, "IsMeteredConnection", "RunningInWindowsPE") == false)
            {
                Err.Error   = "Invalid data";
                Err.ErrorID = (int)ErrorFlags.InvalidData;
                return(RESTStatus.Fail);
            }

            Guid testguid;

            if (Guid.TryParse(logon.Username, out testguid) == false)
            {
                Err.Error   = "Invalid username";
                Err.ErrorID = (int)ErrorFlags.InvalidUsername;
                return(RESTStatus.Fail);
            }

            if (Guid.TryParse(logon.Password, out testguid) == false)
            {
                Err.Error   = "Invalid password";
                Err.ErrorID = (int)ErrorFlags.InvalidPassword;
                return(RESTStatus.Fail);
            }

            if (logon.SysInfo.UCID.Trim().Length != 32)
            {
                Err.Error   = "Invalid UCID";
                Err.ErrorID = (int)ErrorFlags.InvalidValue;
                return(RESTStatus.Fail);
            }

            if (logon.ContractID == null)
            {
                logon.ContractID = "";
            }
            if (logon.ContractPassword == null)
            {
                logon.ContractPassword = "";
            }

            if (Fox_LicenseGenerator.SDCLicensing.ValidLicense == false)
            {
                FoxEventLog.WriteEventLog("Licensing error: no valid license found. Client login are rejected.", EventLogEntryType.Warning);
                Err.Error   = "Licensing error";
                Err.ErrorID = (int)ErrorFlags.LicensingError;
                return(RESTStatus.Fail);
            }

            if (Fox_LicenseGenerator.SDCLicensing.TestExpiry() == false)
            {
                FoxEventLog.WriteEventLog("Licensing error: license expired. Client login are rejected.", EventLogEntryType.Warning);
                Err.Error   = "Licensing error";
                Err.ErrorID = (int)ErrorFlags.LicensingError;
                return(RESTStatus.Fail);
            }

            if (Settings.Default.UseContract == true)
            {
                if (logon.ContractID == "")
                {
                    Err.Error   = "Invalid Contract Data";
                    Err.ErrorID = (int)ErrorFlags.FaultyContractData;
                    return(RESTStatus.Fail);
                }
                if (logon.ContractPassword == "")
                {
                    Err.Error   = "Invalid Contract Data";
                    Err.ErrorID = (int)ErrorFlags.FaultyContractData;
                    return(RESTStatus.Fail);
                }
            }

            logon.Username          = logon.Username.Trim().ToUpper();
            logon.SysInfo.MachineID = logon.SysInfo.MachineID.Trim().ToUpper();

            if (logon.Username != logon.SysInfo.MachineID)
            {
                Err.Error   = "Invalid Username/MachineID";
                Err.ErrorID = (int)ErrorFlags.InvalidValue;
                return(RESTStatus.Fail);
            }

            string newID = NetworkConnection.NewSession();

            ni = NetworkConnection.GetSession(newID);
            if (NetworkConnectionProcessor.InitNi(ni) == false)
            {
                NetworkConnection.DeleteSession(newID);
                Err.Error   = "System Error";
                Err.ErrorID = (int)ErrorFlags.SystemError;
                return(RESTStatus.ServerError);
            }
            sql = ni.sql;

            ni.Permissions = 0;
            ni.Error       = "";
            ni.ErrorID     = ErrorFlags.NoError;

            if (Fox_LicenseGenerator.SDCLicensing.NumComputers != null)
            {
                Int64 Computers = Convert.ToInt64(sql.ExecSQLScalar("select count(*) from ComputerAccounts where Accepted=1"));
                if (Computers > Fox_LicenseGenerator.SDCLicensing.NumComputers.Value)
                {
                    NetworkConnection.DeleteSession(newID);
                    FoxEventLog.WriteEventLog("Licensing error: too many computers are accepted. Client login are rejected.\n" +
                                              "Lic=" + Fox_LicenseGenerator.SDCLicensing.NumComputers.Value.ToString() + " Listed=" + Computers.ToString(),
                                              EventLogEntryType.Warning);
                    Err.Error   = "Licensing error";
                    Err.ErrorID = (int)ErrorFlags.LicensingError;
                    return(RESTStatus.Fail);
                }
            }

            if (Settings.Default.UseContract == true)
            {
                if (Convert.ToInt32(sql.ExecSQLScalar("SELECT Count(*) FROM Contracts WHERE ContractID=@id AND ContractPassword=@pw AND Disabled=0",
                                                      new SQLParam("@id", logon.ContractID),
                                                      new SQLParam("@pw", logon.ContractPassword))) == 0)
                {
                    NetworkConnection.DeleteSession(newID);
                    Err.Error   = "Invalid/Disabled Contract Data";
                    Err.ErrorID = (int)ErrorFlags.FaultyContractData;
                    return(RESTStatus.Fail);
                }
            }

            if (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM ComputerAccounts WHERE MachineID=@m",
                                                  new SQLParam("@m", logon.Username))) == 0)
            {
                if (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM ComputerAccounts WHERE UCID=@u",
                                                      new SQLParam("@u", logon.SysInfo.UCID.Trim()))) > 0)
                {
                    NetworkConnection.DeleteSession(newID);
                    Err.Error   = "UCID used for a different machine";
                    Err.ErrorID = (int)ErrorFlags.UCIDissues;
                    return(RESTStatus.Fail);
                }

                if (Settings.Default.UseContract == true)
                {
                    object o = sql.ExecSQLScalar("Select MaxComputers FROM Contracts WHERE ContractID=@cid", new SQLParam("@cid", logon.ContractID));
                    if (!(o is DBNull))
                    {
                        int i;
                        if (int.TryParse(o.ToString(), out i) == true)
                        {
                            int cnt = Convert.ToInt32(sql.ExecSQL("Select count(*) FROM ComputerAccounts WHERE ContractID=@cid", new SQLParam("@cid", logon.ContractID)));
                            if (cnt + 1 > i)
                            {
                                NetworkConnection.DeleteSession(newID);
                                Err.Error   = "Number of computers exhausted";
                                Err.ErrorID = (int)ErrorFlags.ContractNumComputersExhausted;
                                return(RESTStatus.Fail);
                            }
                        }
                    }
                }

                sql.InsertMultiData("ComputerAccounts",
                                    new SQLData("MachineID", logon.SysInfo.MachineID),
                                    new SQLData("UCID", logon.SysInfo.UCID),
                                    new SQLData("Password", logon.Password),
                                    new SQLData("Is64Bit", logon.SysInfo.Is64Bit),
                                    new SQLData("OSName", logon.SysInfo.OSName),
                                    new SQLData("OSVerMaj", logon.SysInfo.OSVerMaj),
                                    new SQLData("OSVerMin", logon.SysInfo.OSVerMin),
                                    new SQLData("OSVerBuild", logon.SysInfo.OSVerBuild),
                                    new SQLData("OSSuite", logon.SysInfo.OSSuite),
                                    new SQLData("IsTSE", logon.SysInfo.IsTSE),
                                    new SQLData("CPU", logon.SysInfo.CPU),
                                    new SQLData("ComputerModel", logon.SysInfo.ComputerModel),
                                    new SQLData("ComputerName", logon.SysInfo.ComputerName),
                                    new SQLData("Language", logon.SysInfo.Language),
                                    new SQLData("DisplayLanguage", logon.SysInfo.DisplayLanguage),
                                    new SQLData("AgentVersion", logon.SysInfo.AgentVersion),
                                    new SQLData("AgentVersionID", logon.SysInfo.AgentVersionID),
                                    new SQLData("OSVerType", logon.SysInfo.OSVerType),
                                    new SQLData("RunningInHypervisor", logon.SysInfo.RunningInHypervisor),
                                    new SQLData("BIOS", logon.SysInfo.BIOS),
                                    new SQLData("BIOSType", logon.SysInfo.BIOSType),
                                    new SQLData("NumberOfLogicalProcessors", logon.SysInfo.NumberOfLogicalProcessors),
                                    new SQLData("NumberOfProcessors", logon.SysInfo.NumberOfProcessors),
                                    new SQLData("TotalPhysicalMemory", logon.SysInfo.TotalPhysicalMemory),
                                    new SQLData("CPUName", logon.SysInfo.CPUName),
                                    new SQLData("SecureBootState", logon.SysInfo.SecureBootState),
                                    new SQLData("IPAddress", IPAddress),
                                    new SQLData("SystemRoot", logon.SysInfo.SystemRoot),
                                    new SQLData("SUSID", logon.SysInfo.SUSID),
                                    new SQLData("MeteredConnection", logon.SysInfo.IsMeteredConnection),
                                    new SQLData("RunningInWindowsPE", logon.SysInfo.RunningInWindowsPE),
                                    new SQLData("ContractID", Settings.Default.UseContract == true ? (object)logon.ContractID : DBNull.Value));

                Err.Error   = "Not accepted (computer registered)";
                Err.ErrorID = (int)ErrorFlags.NotAccepted;
                NetworkConnection.DeleteSession(newID);
                return(RESTStatus.Fail);
            }

            if (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM ComputerAccounts WHERE MachineID=@m AND UCID=@ucid",
                                                  new SQLParam("@m", logon.Username),
                                                  new SQLParam("@ucid", logon.SysInfo.UCID.Trim()))) == 0)
            {
                #region Remove in future
                if (logon.SysInfo.LegacyUCID != Consts.NullUCID && logon.SysInfo.LegacyUCID.Trim().Length == 32)
                {
                    if (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM ComputerAccounts WHERE UCID=@u AND MachineID=@m AND Password=@p",
                                                          new SQLParam("@u", logon.SysInfo.LegacyUCID.Trim()),
                                                          new SQLParam("@p", logon.Password),
                                                          new SQLParam("@m", logon.Username))) > 0)
                    {
                        sql.ExecSQL("UPDATE ComputerAccounts SET UCID=@nu WHERE UCID=@u AND MachineID=@m",
                                    new SQLParam("@nu", logon.SysInfo.UCID.Trim()),
                                    new SQLParam("@u", logon.SysInfo.LegacyUCID.Trim()),
                                    new SQLParam("@m", logon.Username));

                        FoxEventLog.WriteEventLog("UCID changed:\nMachineID: " + logon.Username + "\nName: " + logon.SysInfo.ComputerName + "\nLUCID: " + logon.SysInfo.LegacyUCID + "\nUCID: " + logon.SysInfo.UCID, EventLogEntryType.Warning);

                        Err.Error   = "UCID changed!";
                        Err.ErrorID = (int)ErrorFlags.NotAccepted;
                        NetworkConnection.DeleteSession(newID);
                        return(RESTStatus.Fail);
                    }
                }
                #endregion

                Err.Error   = "MachineID & UCID do not match";
                Err.ErrorID = (int)ErrorFlags.MachineUCIDmissmatch;
                NetworkConnection.DeleteSession(newID);
                return(RESTStatus.Fail);
            }

            if (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM ComputerAccounts WHERE MachineID=@m AND Password=@p",
                                                  new SQLParam("@m", logon.Username),
                                                  new SQLParam("@p", logon.Password))) == 0)
            {
                Err.Error   = "Invalid password";
                Err.ErrorID = (int)ErrorFlags.InvalidPassword;
                NetworkConnection.DeleteSession(newID);
                return(RESTStatus.Fail);
            }

            if (Settings.Default.UseContract == true)
            {
                string CurrentContractID = Convert.ToString(sql.ExecSQLScalar("SELECT ContractID FROM ComputerAccounts WHERE MachineID=@m",
                                                                              new SQLParam("@m", logon.Username)));
                if (CurrentContractID == null)
                {
                    CurrentContractID = "";
                }
                if (CurrentContractID != "")
                {
                    if (CurrentContractID.Trim().ToLower() != logon.ContractID.Trim().ToLower())
                    {
                        Err.Error   = "Invalid Contract Data";
                        Err.ErrorID = (int)ErrorFlags.FaultyContractData;
                        NetworkConnection.DeleteSession(newID);
                        return(RESTStatus.Fail);
                    }
                }

                object   dt;
                DateTime dtt;

                dt = sql.ExecSQLScalar("Select ValidFrom FROM Contracts WHERE ContractID=@cid", new SQLParam("@cid", CurrentContractID));
                if (!(dt is DBNull))
                {
                    try
                    {
                        dtt = SQLLib.GetDTUTC(dt);
                        if (DateTime.UtcNow < dtt)
                        {
                            Err.Error   = "Contract not started / expired";
                            Err.ErrorID = (int)ErrorFlags.ContractNotStarted_Expired;
                            NetworkConnection.DeleteSession(newID);
                            return(RESTStatus.Fail);
                        }
                    }
                    catch
                    {
                        Err.Error   = "Invalid Contract Data";
                        Err.ErrorID = (int)ErrorFlags.FaultyContractData;
                        NetworkConnection.DeleteSession(newID);
                        return(RESTStatus.Fail);
                    }
                }

                dt = sql.ExecSQLScalar("Select ValidTo FROM Contracts WHERE ContractID=@cid", new SQLParam("@cid", CurrentContractID));
                if (!(dt is DBNull))
                {
                    try
                    {
                        dtt = SQLLib.GetDTUTC(dt);
                        if (dtt < DateTime.UtcNow)
                        {
                            Err.Error   = "Contract not started / expired";
                            Err.ErrorID = (int)ErrorFlags.ContractNotStarted_Expired;
                            NetworkConnection.DeleteSession(newID);
                            return(RESTStatus.Fail);
                        }
                    }
                    catch
                    {
                        Err.Error   = "Invalid Contract Data";
                        Err.ErrorID = (int)ErrorFlags.FaultyContractData;
                        NetworkConnection.DeleteSession(newID);
                        return(RESTStatus.Fail);
                    }
                }
            }
            else
            {
                logon.ContractID       = "";
                logon.ContractPassword = "";
            }

            sql.ExecSQL("UPDATE ComputerAccounts SET BIOS=@BIOS, OSVerType=@OSVerType, Is64Bit = @Is64Bit,OSName = @OSName,OSVerMaj = @OSVerMaj," +
                        "OSVerMin = @OSVerMin,OSVerBuild = @OSVerBuild,OSSuite = @OSSuite,IsTSE = @IsTSE,CPU = @CPU,ComputerModel = @ComputerModel,ComputerName = @ComputerName," +
                        "Language = @Language,DisplayLanguage = @DisplayLanguage,MachineID = @MachineID,LastUpdated = getutcdate(), AgentVersion=@AgentVersion, AgentVersionID=@AgentVersionID," +
                        "RunningInHypervisor=@RunningInHypervisor, ContractID=@ContractID, IPAddress=@IPAddress,BIOSType=@BIOSType, NumberOfLogicalProcessors=@NumberOfLogicalProcessors, " +
                        "NumberOfProcessors=@NumberOfProcessors, TotalPhysicalMemory=@TotalPhysicalMemory, CPUName=@CPUName, SecureBootState=@SecureBootState, " +
                        "SystemRoot=@SystemRoot,SUSID=@SUSID,MeteredConnection=@meteredconnection, " +
                        "RunningInWindowsPE=@RunningInWindowsPE " +
                        "    WHERE MachineID = @MachineID",
                        new SQLParam("@Is64Bit", logon.SysInfo.Is64Bit),
                        new SQLParam("@OSName", logon.SysInfo.OSName),
                        new SQLParam("@OSVerMaj", logon.SysInfo.OSVerMaj),
                        new SQLParam("@OSVerMin", logon.SysInfo.OSVerMin),
                        new SQLParam("@OSVerBuild", logon.SysInfo.OSVerBuild),
                        new SQLParam("@OSSuite", logon.SysInfo.OSSuite),
                        new SQLParam("@IsTSE", logon.SysInfo.IsTSE),
                        new SQLParam("@CPU", logon.SysInfo.CPU),
                        new SQLParam("@ComputerModel", logon.SysInfo.ComputerModel),
                        new SQLParam("@ComputerName", logon.SysInfo.ComputerName),
                        new SQLParam("@Language", logon.SysInfo.Language),
                        new SQLParam("@DisplayLanguage", logon.SysInfo.DisplayLanguage),
                        new SQLParam("@MachineID", logon.Username),
                        new SQLParam("@AgentVersionID", logon.SysInfo.AgentVersionID),
                        new SQLParam("@AgentVersion", logon.SysInfo.AgentVersion),
                        new SQLParam("@OSVerType", logon.SysInfo.OSVerType),
                        new SQLParam("@RunningInHypervisor", logon.SysInfo.RunningInHypervisor),
                        new SQLParam("@BIOS", logon.SysInfo.BIOS),
                        new SQLParam("@BIOSType", logon.SysInfo.BIOSType),
                        new SQLParam("@NumberOfLogicalProcessors", logon.SysInfo.NumberOfLogicalProcessors),
                        new SQLParam("@NumberOfProcessors", logon.SysInfo.NumberOfProcessors),
                        new SQLParam("@TotalPhysicalMemory", logon.SysInfo.TotalPhysicalMemory),
                        new SQLParam("@CPUName", logon.SysInfo.CPUName),
                        new SQLParam("@SecureBootState", logon.SysInfo.SecureBootState),
                        new SQLParam("@IPAddress", IPAddress),
                        new SQLParam("@SystemRoot", logon.SysInfo.SystemRoot),
                        new SQLParam("@SUSID", logon.SysInfo.SUSID),
                        new SQLParam("@meteredconnection", logon.SysInfo.IsMeteredConnection),
                        new SQLParam("@RunningInWindowsPE", logon.SysInfo.RunningInWindowsPE),
                        new SQLParam("@ContractID", Settings.Default.UseContract == true ? (object)logon.ContractID : DBNull.Value));

            sql.ExecSQL("UPDATE ComputerAccounts SET LastUpdated=getutcdate() WHERE MachineID=@m",
                        new SQLParam("@m", logon.Username));

            int Acceptance = Convert.ToInt32(sql.ExecSQLScalar("SELECT Accepted FROM ComputerAccounts WHERE MachineID=@m",
                                                               new SQLParam("@m", logon.Username)));

            switch (Acceptance)
            {
            case 1:     //OK
                break;

            default:
                Err.Error   = "Not accepted";
                Err.ErrorID = (int)ErrorFlags.NotAccepted;
                NetworkConnection.DeleteSession(newID);
                return(RESTStatus.Fail);
            }

            ni.Username           = logon.Username;
            ni.Name               = logon.SysInfo.ComputerName;
            ni.EMail              = "";
            ni.MustChangePassword = false;
            ni.LoggedIn           = false;
            ni.ComputerLoggedIn   = true;
            ni.Permissions        = (Int64)ACLFlags.ComputerLogin;
            Debug.WriteLine("Computer: " + ni.Name + " logged in");
            Err.Error   = "OK:" + newID;
            Err.ErrorID = (int)ErrorFlags.NoError;
            return(RESTStatus.Success);
        }
Exemplo n.º 8
0
        static int Main(string[] args)
        {
            for (int i = 0; i < args.Length; i++)
            {
                if (args[i].ToLower() == "-?")
                {
                    Console.WriteLine("Service only:");
                    Console.WriteLine("      -instance <instance id>");
                    Console.WriteLine("      -registereventlog");
                    Console.WriteLine("      -createlocaldb");
                    Console.WriteLine("      -noservice");
                    Console.WriteLine("      -install");
                    Console.WriteLine("      -httpcfg");
                    Console.WriteLine("      -httpcfgsystem");
                    return(0);
                }
                if (args[i].ToLower() == "-registereventlog")
                {
                    try
                    {
                        FoxEventLog.RegisterEventLog();
                    }
                    catch (Exception ee)
                    {
                        Console.WriteLine(ee.ToString());
                        return(-1);
                    }
                    return(0);
                }
                if (args[i].ToLower() == "-noservice")
                {
                    Settings.Default.Load();
                    SMain();
                    return(0);
                }
                if (args[i].ToLower() == "-createlocaldb")
                {
                    Settings.Default.Load();
                    try
                    {
                        BlankLocalDB.CreateBlankLocalDB();
                    }
                    catch (Exception ee)
                    {
                        Console.WriteLine(ee.ToString());
                        return(-1);
                    }
                    return(0);
                }
                if (args[i].ToLower() == "-install")
                {
                    try
                    {
                        ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
                    }
                    catch (Exception ee)
                    {
                        Console.WriteLine(ee.ToString());
                        return(-1);
                    }

                    try
                    {
                        FoxEventLog.RegisterEventLog();
                    }
                    catch (Exception ee)
                    {
                        Console.WriteLine(ee.ToString());
                        return(-1);
                    }
                    return(0);
                }
                if (args[i].ToLower() == "-instance")
                {
                    if (args.Length > i)
                    {
                        InstanceID = Utilities.FilterOutBadChars(args[i + 1].Trim());
                        i++;
                    }
                    else
                    {
                        Console.WriteLine("Missing supplement parameter");
                        return(-1);
                    }
                }
                if (args[i].ToLower() == "-httpcfg")
                {
                    Settings.Default.Load();
                    WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();
                    foreach (string lo in Settings.Default.ListenOn.Split('|'))
                    {
                        Console.WriteLine("Setting URLACL for " + lo + ", User: "******"-httpcfgsystem")
                {
                    Settings.Default.Load();
                    foreach (string lo in Settings.Default.ListenOn.Split('|'))
                    {
                        Console.WriteLine("Setting URLACL for " + lo + ", User: "******"NT AUTHORITY\\SYSTEM");
                        HttpServerApi.ModifyNamespaceReservation(lo, "NT AUTHORITY\\SYSTEM", HttpServerApiConfigurationAction.AddOrUpdate);
                    }
                    return(0);
                }
            }

            Settings.Default.Load();
#if DEBUG
            SMain();
#else
            ServicesToRun = new ServiceBase[]
            {
                new FoxSDCASrvService()
            };
            ServiceBase.Run(ServicesToRun);
#endif
            return(0);
        }
Exemplo n.º 9
0
        static void ReadVersions()
        {
            string AppPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            if (AppPath.EndsWith("\\") == false)
            {
                AppPath += "\\";
            }
            AppPath += "Packages\\";

            string NormalUpdate = AppPath + "SDCA.foxpkg";
            string EarlyUpdate  = AppPath + "SDCA-Early.foxpkg";

            string Error;

            if (File.Exists(NormalUpdate) == false)
            {
                FoxEventLog.WriteEventLog("No client updates will be provided. The file " + NormalUpdate + " is missing.",
                                          System.Diagnostics.EventLogEntryType.Error);
                CurrentVersion = CurrentEarlyVersion = null;
                return;
            }

            PackageInstaller pkg = new PackageInstaller();
            PKGStatus        status;
            PKGRecieptData   receipt;

            Int64?NormalVersion = null;
            Int64?EarlyVersion  = null;

            try
            {
                if (pkg.InstallPackage(NormalUpdate, null, PackageInstaller.InstallMode.TestPackageOnly, false, out Error, out status, out receipt) == false)
                {
                    FoxEventLog.WriteEventLog("No client updates will be provided. The file " + NormalUpdate + " is invalid / invalid signatures.",
                                              System.Diagnostics.EventLogEntryType.Error);
                    CurrentVersion = CurrentEarlyVersion = null;
                    return;
                }

                if (pkg.PackageInfo(NormalUpdate, null, out Error) == false)
                {
                    FoxEventLog.WriteEventLog("No client updates will be provided. The file " + NormalUpdate + " is invalid / invalid info.",
                                              System.Diagnostics.EventLogEntryType.Error);
                    CurrentVersion = CurrentEarlyVersion = null;
                    return;
                }

                if (pkg.PackageInfoData.PackageID != "Vulpes-SDCA1-Update")
                {
                    FoxEventLog.WriteEventLog("No client updates will be provided. The file " + NormalUpdate + " is has an invalid identifier.",
                                              System.Diagnostics.EventLogEntryType.Error);
                    CurrentVersion = CurrentEarlyVersion = null;
                    return;
                }
            }
            catch
            {
                NormalVersion       = null;
                EarlyVersion        = null;
                CurrentVersion      = NormalVersion;
                CurrentEarlyVersion = EarlyVersion;
                FoxEventLog.WriteEventLog("Update packages contains errors. No updates will be provided.", System.Diagnostics.EventLogEntryType.Error);
                return;
            }

            NormalVersion = pkg.PackageInfoData.VersionID;

            if (File.Exists(EarlyUpdate) == true)
            {
                if (pkg.InstallPackage(EarlyUpdate, null, PackageInstaller.InstallMode.TestPackageOnly, false, out Error, out status, out receipt) == true)
                {
                    if (pkg.PackageInfo(EarlyUpdate, null, out Error) == true)
                    {
                        if (pkg.PackageInfoData.PackageID == "Vulpes-SDCA1-Update")
                        {
                            EarlyVersion = pkg.PackageInfoData.VersionID;

                            if (EarlyVersion < NormalVersion)
                            {
                                FoxEventLog.WriteEventLog("The version ID of the file " + EarlyUpdate + " is older than the normal version - not deploying.",
                                                          System.Diagnostics.EventLogEntryType.Warning);
                                EarlyVersion = null;
                            }
                            else
                            {
                                FoxEventLog.WriteEventLog("The file " + EarlyUpdate + " will be deployed along with the normal updates.",
                                                          System.Diagnostics.EventLogEntryType.Information);
                            }
                        }
                    }
                }
            }

            CurrentVersion      = NormalVersion;
            CurrentEarlyVersion = EarlyVersion;

            FoxEventLog.WriteEventLog("The Agent update system is working normally.\r\nVersion: " + CurrentVersion.ToString() + "\r\nEarly Version: " + CurrentEarlyVersion.ToString(), System.Diagnostics.EventLogEntryType.Information);
        }
Exemplo n.º 10
0
        void ReportingThread(object SimpleTaskO)
        {
            try
            {
                using (SQLLib sql = SQLTest.ConnectSQL("Fox SDC Server for SimpleTask Result Data"))
                {
                    if (sql == null)
                    {
                        FoxEventLog.WriteEventLog("Cannot connect to SQL Server for SimpleTask Result Reporting!", System.Diagnostics.EventLogEntryType.Error);
                        return;
                    }
                    SimpleTaskResult SimpleTask = (SimpleTaskResult)SimpleTaskO;

                    List <PolicyObject>        Pol             = Policies.GetPolicyForComputerInternal(sql, SimpleTask.MachineID);
                    Dictionary <string, Int64> AlreadyReported = new Dictionary <string, long>();
                    foreach (PolicyObject PolO in Pol)
                    {
                        if (PolO.Type != PolicyIDs.ReportingPolicy)
                        {
                            continue;
                        }
                        ReportingPolicyElement RepElementRoot = JsonConvert.DeserializeObject <ReportingPolicyElement>(Policies.GetPolicy(sql, PolO.ID).Data);
                        if (RepElementRoot.Type != ReportingPolicyType.SimpleTaskCompleted)
                        {
                            continue;
                        }
                        if (RepElementRoot.ReportToAdmin == null)
                        {
                            RepElementRoot.ReportToAdmin = false;
                        }
                        if (RepElementRoot.ReportToClient == null)
                        {
                            RepElementRoot.ReportToClient = false;
                        }
                        if (RepElementRoot.UrgentForAdmin == null)
                        {
                            RepElementRoot.UrgentForAdmin = false;
                        }
                        if (RepElementRoot.UrgentForClient == null)
                        {
                            RepElementRoot.UrgentForClient = false;
                        }
                        if (RepElementRoot.ReportToAdmin == false && RepElementRoot.ReportToClient == false && RepElementRoot.UrgentForAdmin == false &&
                            RepElementRoot.UrgentForClient == false)
                        {
                            continue;
                        }

                        foreach (string Element in RepElementRoot.ReportingElements)
                        {
                            ReportingPolicyElementSimpleTaskCompleted arprep = JsonConvert.DeserializeObject <ReportingPolicyElementSimpleTaskCompleted>(Element);

                            ReportThings(sql, SimpleTask.MachineID, "Completed", SimpleTask, ref AlreadyReported, RepElementRoot);
                        }
                    }
                }
            }
            catch (Exception ee)
            {
                FoxEventLog.WriteEventLog("SEH in SimpleTask Result Reporting " + ee.ToString(), System.Diagnostics.EventLogEntryType.Error);
            }
        }
Exemplo n.º 11
0
        public static bool TestServer(out string ErrorReason, bool SkipSomeSanityChecks = false)
        {
            ErrorReason = "";

            SQLLib sql = null;

            try
            {
                if (Settings.Default.DBType.ToLower() == "mssql")
                {
                    if (Settings.Default.DBServer == "" || Settings.Default.DBDB == "")
                    {
                        ErrorReason = "Servername / DB missing";
                        return(false);
                    }
                    sql = new SQLLib();
                    sql.SqlCommandTimeout = 0; //waiting .... :-)
                    sql.ApplicationName   = "Fox SDC Server [test/update connection]";
                    sql.ConnectionPooling = false;
                    sql.SEHError          = true;
                    if (sql.ConnectDatabase(Settings.Default.DBServer, Settings.Default.DBDB, true) == false)
                    {
                        ErrorReason = "Cannot connect to the SQL Server";
                        return(false);
                    }
                }
                if (Settings.Default.DBType.ToLower() == "localdb")
                {
                    if (Settings.Default.DBLocalPath == "")
                    {
                        ErrorReason = "LocalDB path missing";
                        return(false);
                    }
                    sql = new SQLLib();
                    sql.SqlCommandTimeout = 0; //waiting .... :-)
                    sql.ApplicationName   = "Fox SDC Server [test/update connection]";
                    sql.ConnectionPooling = false;
                    sql.SEHError          = true;
                    if (sql.ConnectLocalDatabase(Settings.Default.DBLocalPath) == false)
                    {
                        ErrorReason = "Cannot connect to the SQL Server";
                        return(false);
                    }
                }
            }
            catch (Exception ee)
            {
                ErrorReason = "Cannot connect to the SQL Server [SEH]\n" + ee.ToString();
                Debug.WriteLine(ee.ToString());
                return(false);
            }

            if (sql == null)
            {
                ErrorReason = "sql==null //is the SQL Profile properly defined in registry?\n";
                return(false);
            }

            string ServerVersion = Convert.ToString(sql.ExecSQLScalar("SELECT SERVERPROPERTY('productversion')"));
            string ServerVPart   = ServerVersion.Split('.')[0].Trim();
            int    ServerVPartI  = 0;

            if (int.TryParse(ServerVPart, out ServerVPartI) == false)
            {
                sql.CloseConnection();
                ErrorReason = "Cannot read SQL Version";
                return(false);
            }
            if (ServerVPartI < 11)
            {
                sql.CloseConnection();
                ErrorReason = "Unsupported SQL Version - Minimum V.11 (SQL 2012)";
            }

            try
            {
                sql.ExecSQL("SELECT * FROM Config");
            }
            catch
            {
                sql.CloseConnection();
                ErrorReason = "Cannot SELECT Table CONFIG.";
                return(false);
            }

            try
            {
                if (Convert.ToString(sql.ExecSQLScalar("SELECT Value FROM Config WHERE [Key]='ID'")) != "FOXSDCv1")
                {
                    sql.CloseConnection();
                    ErrorReason = "Invalid ID in Config Table";
                    return(false);
                }
            }
            catch
            {
                sql.CloseConnection();
                ErrorReason = "Cannot SELECT Table CONFIG. (ID)";
                return(false);
            }

            while (DBUpdate.UpdateDB(sql) == false)
            {
                ;
            }

            sql.SEHError = true;

            try
            {
                if (Convert.ToInt32(sql.ExecSQLScalar("SELECT Value FROM Config WHERE [Key]='Version'")) != Program.DBVersion)
                {
                    sql.CloseConnection();
                    ErrorReason = "Invalid Version in Config Table";
                    return(false);
                }
            }
            catch
            {
                sql.CloseConnection();
                ErrorReason = "Cannot SELECT Table CONFIG. (Version)";
                return(false);
            }

            if (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM Users WHERE Username='******'")) == 0)
            {
                FoxEventLog.WriteEventLog("Creating user ROOT", EventLogEntryType.Warning);
                sql.InsertMultiData("Users",
                                    new SQLData("Username", "root"),
                                    new SQLData("Name", "Root User"),
                                    new SQLData("Password", DefaultPasswordHash),
                                    new SQLData("Permissions", AllPermissions),
                                    new SQLData("MustChangePassword", 1));
            }
            if (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM Users WHERE Username='******' AND Permissions=@p", new SQLParam("@p", AllPermissions))) == 0)
            {
                FoxEventLog.WriteEventLog("Fixing user ROOT", EventLogEntryType.Warning);
                sql.ExecSQL("UPDATE Users SET Permissions=@p WHERE Username='******'", new SQLParam("@p", AllPermissions));
            }

            try
            {
                Guid g;
                if (Guid.TryParse(Convert.ToString(sql.ExecSQLScalar("SELECT Value FROM Config WHERE [Key]='GUID'")), out g) == false)
                {
                    FoxEventLog.WriteEventLog("Creating GUID", EventLogEntryType.Warning);
                    sql.ExecSQL("DELETE FROM Config WHERE [Key]='GUID'");
                    sql.ExecSQL("INSERT INTO Config VALUES ('GUID', @g)", new SQLParam("@g", Guid.NewGuid().ToString()));
                }
            }
            catch (Exception ee)
            {
                Debug.WriteLine(ee.ToString());
                ErrorReason = "Cannot verify GUID";
                return(false);
            }


            SettingsManager.LoadSettings(sql);

            //try
            //{
            //    string ret = Convert.ToString(sql.ExecSQLScalar("select dbo.FoxCreateSerial(1, 1)"));
            //}
            //catch (Exception ee)
            //{
            //    Debug.WriteLine(ee.ToString());
            //    ErrorReason = "Cannot execute FUNCTIONs in SQL";
            //    return (false);
            //}

            sql.CloseConnection();
            ErrorReason = "";
            return(true);
        }
Exemplo n.º 12
0
        void ReportingThread(object SmartDataListO)
        {
            try
            {
                using (SQLLib sql = SQLTest.ConnectSQL("Fox SDC Server for SMART Device Data"))
                {
                    if (sql == null)
                    {
                        FoxEventLog.WriteEventLog("Cannot connect to SQL Server for SMART Device Reporting!", System.Diagnostics.EventLogEntryType.Error);
                        return;
                    }
                    SmartDataLst SmartDataList = (SmartDataLst)SmartDataListO;
                    ComputerData computerdata  = Computers.GetComputerDetail(sql, SmartDataList.MachineID);
                    if (computerdata == null)
                    {
                        FoxEventLog.WriteEventLog("Cannot get any computer data for SMART Device Reporting!", System.Diagnostics.EventLogEntryType.Error);
                        return;
                    }

                    List <PolicyObject>        Pol             = Policies.GetPolicyForComputerInternal(sql, SmartDataList.MachineID);
                    Dictionary <string, Int64> AlreadyReported = new Dictionary <string, long>();
                    foreach (PolicyObject PolO in Pol)
                    {
                        if (PolO.Type != PolicyIDs.ReportingPolicy)
                        {
                            continue;
                        }
                        ReportingPolicyElement RepElementRoot = JsonConvert.DeserializeObject <ReportingPolicyElement>(Policies.GetPolicy(sql, PolO.ID).Data);
                        if (RepElementRoot.Type != ReportingPolicyType.SMART)
                        {
                            continue;
                        }
                        if (RepElementRoot.ReportToAdmin == null)
                        {
                            RepElementRoot.ReportToAdmin = false;
                        }
                        if (RepElementRoot.ReportToClient == null)
                        {
                            RepElementRoot.ReportToClient = false;
                        }
                        if (RepElementRoot.UrgentForAdmin == null)
                        {
                            RepElementRoot.UrgentForAdmin = false;
                        }
                        if (RepElementRoot.UrgentForClient == null)
                        {
                            RepElementRoot.UrgentForClient = false;
                        }
                        if (RepElementRoot.ReportToAdmin == false && RepElementRoot.ReportToClient == false && RepElementRoot.UrgentForAdmin == false &&
                            RepElementRoot.UrgentForClient == false)
                        {
                            continue;
                        }

                        foreach (string Element in RepElementRoot.ReportingElements)
                        {
                            ReportingPolicyElementSMART arprep = JsonConvert.DeserializeObject <ReportingPolicyElementSMART>(Element);
                            if (arprep.NotifyOnAdd == false && arprep.NotifyOnRemove == false && arprep.NotifyOnUpdate == false &&
                                arprep.NotifyOnError == false)
                            {
                                continue;
                            }

                            if (arprep.NotifyOnAdd == true)
                            {
                                foreach (VulpesSMARTInfo ar in SmartDataList.Added)
                                {
                                    ReportThings(sql, SmartDataList.MachineID, "Add", ar, ref AlreadyReported, RepElementRoot);
                                }
                            }

                            if (arprep.NotifyOnUpdate == true)
                            {
                                foreach (VulpesSMARTInfo ar in SmartDataList.Updated)
                                {
                                    foreach (VulpesSMARTInfo indbvsm in SmartDataList.InDB)
                                    {
                                        if (indbvsm.PNPDeviceID == ar.PNPDeviceID)
                                        {
                                            if (SMARTDescription.CompareFull(ar, indbvsm, arprep.SkipAttribUpdateReport) == false)
                                            {
                                                if (indbvsm.Attributes != null)
                                                {
                                                    List <int> UpdatedAttribs = new List <int>();
                                                    if (ar.Attributes == null)
                                                    {
                                                        ar.Attributes = new Dictionary <int, VulpesSMARTAttribute>();
                                                    }
                                                    foreach (KeyValuePair <int, VulpesSMARTAttribute> indb in indbvsm.Attributes)
                                                    {
                                                        if (ar.Attributes.ContainsKey(indb.Key) == true)
                                                        {
                                                            if (ar.Attributes[indb.Key].FailureImminent != indb.Value.FailureImminent ||
                                                                ar.Attributes[indb.Key].Flags != indb.Value.Flags ||
                                                                ar.Attributes[indb.Key].ID != indb.Value.ID ||
                                                                ar.Attributes[indb.Key].Threshold != indb.Value.Threshold ||
                                                                ar.Attributes[indb.Key].Value != indb.Value.Value ||
                                                                ar.Attributes[indb.Key].Vendordata != indb.Value.Vendordata ||
                                                                ar.Attributes[indb.Key].Worst != indb.Value.Worst)
                                                            {
                                                                UpdatedAttribs.Add(indb.Key);
                                                            }
                                                        }
                                                    }
                                                    ReportThings(sql, SmartDataList.MachineID, "Update", ar, ref AlreadyReported, RepElementRoot, UpdatedAttribs);
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            if (arprep.NotifyOnRemove == true)
                            {
                                foreach (VulpesSMARTInfo ar in SmartDataList.Removed)
                                {
                                    ReportThings(sql, SmartDataList.MachineID, "Remove", ar, ref AlreadyReported, RepElementRoot);
                                }
                            }

                            if (arprep.NotifyOnError == true)
                            {
                                foreach (VulpesSMARTInfo ar in SmartDataList.Added)
                                {
                                    if (SMARTDescription.IsInError(ar) == true)
                                    {
                                        ReportThings(sql, SmartDataList.MachineID, "Error", ar, ref AlreadyReported, RepElementRoot);
                                    }
                                }
                                foreach (VulpesSMARTInfo ar in SmartDataList.Updated)
                                {
                                    if (SMARTDescription.IsInError(ar) == true)
                                    {
                                        foreach (VulpesSMARTInfo indbvsm in SmartDataList.InDB)
                                        {
                                            if (indbvsm.PNPDeviceID == ar.PNPDeviceID)
                                            {
                                                if (SMARTDescription.CompareFullCriticalOnly(indbvsm, ar) == false)
                                                {
                                                    ReportThings(sql, SmartDataList.MachineID, "Error", ar, ref AlreadyReported, RepElementRoot);
                                                }
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ee)
            {
                FoxEventLog.WriteEventLog("SEH in SMART Data Reporting " + ee.ToString(), System.Diagnostics.EventLogEntryType.Error);
            }
        }
Exemplo n.º 13
0
        static void MThread()
        {
            do
            {
                using (SQLLib sql = SQLTest.ConnectSQL("Fox SDC Server for Maintenance", 0))
                {
                    if (sql == null)
                    {
                        Pause();
                        if (StopThread == true)
                        {
                            break;
                        }
                    }

                    try
                    {
                        if (SettingsManager.Settings.KeepEventLogDays > 0)
                        {
                            DateTime now = DateTime.UtcNow;
                            Int64    res = Convert.ToInt64(sql.ExecSQLScalar(@"DECLARE @Deleted_Rows INT
                            DECLARE @Deleted_Rows_Total INT
                            SET @Deleted_Rows = 1
                            SET @Deleted_Rows_Total = 0

                            WHILE (@Deleted_Rows > 0)
                            BEGIN
                                delete top (10000) from EventLog where TimeGenerated<DATEADD(day, @d, getutcdate())
                                SET @Deleted_Rows = @@ROWCOUNT
                                SET @Deleted_Rows_Total = @Deleted_Rows_Total + @Deleted_Rows
                            END

                            Select @Deleted_Rows_Total",
                                                                             new SQLParam("@d", 0 - SettingsManager.Settings.KeepEventLogDays)));
                            Int64 secs = Convert.ToInt64((DateTime.UtcNow - now).TotalSeconds);
                            FoxEventLog.WriteEventLog("Eventlog data Maintenance completed: " + res.ToString() + " entr" + (res == 1 ? "y" : "ies") + " deleted\nTime needed: " + secs + " second" + (secs == 1 ? "" : "s"), System.Diagnostics.EventLogEntryType.Information);
                        }
                        if (SettingsManager.Settings.KeepNonPresentDisks > 0)
                        {
                            DateTime now = DateTime.UtcNow;
                            int      res = sql.ExecSQLNQ("delete from DiskData where DevicePresent!=1 AND LastUpdated<DATEADD(day, @d, getutcdate())",
                                                         new SQLParam("@d", 0 - SettingsManager.Settings.KeepNonPresentDisks));
                            Int64 secs = Convert.ToInt64((DateTime.UtcNow - now).TotalSeconds);
                            FoxEventLog.WriteEventLog("Nonpresent disk data Maintenance completed: " + res.ToString() + " entr" + (res == 1 ? "y" : "ies") + " deleted\nTime needed: " + secs + " second" + (secs == 1 ? "" : "s"), System.Diagnostics.EventLogEntryType.Information);
                        }
                        if (SettingsManager.Settings.KeepReports > 0)
                        {
                            DateTime now = DateTime.UtcNow;
                            int      res = sql.ExecSQLNQ("delete from Reporting where Reported<DATEADD(day, @d, getutcdate())",
                                                         new SQLParam("@d", 0 - SettingsManager.Settings.KeepReports));
                            Int64 secs = Convert.ToInt64((DateTime.UtcNow - now).TotalSeconds);
                            FoxEventLog.WriteEventLog("Report Maintenance completed: " + res.ToString() + " entr" + (res == 1 ? "y" : "ies") + " deleted\nTime needed: " + secs + " second" + (secs == 1 ? "" : "s"), System.Diagnostics.EventLogEntryType.Information);
                        }
                        if (SettingsManager.Settings.KeepBitlockerRK > 0)
                        {
                            DateTime now = DateTime.UtcNow;
                            int      res = sql.ExecSQLNQ("delete from BitlockerRK where Reported<DATEADD(day, @d, getutcdate())",
                                                         new SQLParam("@d", 0 - SettingsManager.Settings.KeepBitlockerRK));
                            Int64 secs = Convert.ToInt64((DateTime.UtcNow - now).TotalSeconds);
                            FoxEventLog.WriteEventLog("Old BitlockerRK Maintenance completed: " + res.ToString() + " entr" + (res == 1 ? "y" : "ies") + " deleted\nTime needed: " + secs + " second" + (secs == 1 ? "" : "s"), System.Diagnostics.EventLogEntryType.Information);
                        }
                        if (SettingsManager.Settings.KeepChatLogs > 0)
                        {
                            DateTime now = DateTime.UtcNow;
                            int      res = sql.ExecSQLNQ("delete from Chats where DT<DATEADD(day, @d, getutcdate())",
                                                         new SQLParam("@d", 0 - SettingsManager.Settings.KeepChatLogs));
                            Int64 secs = Convert.ToInt64((DateTime.UtcNow - now).TotalSeconds);
                            FoxEventLog.WriteEventLog("Old Chat Logs Maintenance completed: " + res.ToString() + " entr" + (res == 1 ? "y" : "ies") + " deleted\nTime needed: " + secs + " second" + (secs == 1 ? "" : "s"), System.Diagnostics.EventLogEntryType.Information);
                        }
                    }
                    catch (Exception ee)
                    {
                        FoxEventLog.WriteEventLog("Cannot delete Eventlog data\n" + ee.ToString(), System.Diagnostics.EventLogEntryType.Error);
                    }

                    sql.CloseConnection();
                }
                Pause();
                if (StopThread == true)
                {
                    break;
                }
            } while (StopThread == false);
        }
Exemplo n.º 14
0
        void ReportingThread(object EventDataListO)
        {
            try
            {
                using (SQLLib sql = SQLTest.ConnectSQL("Fox SDC Server for EventLog Data"))
                {
                    if (sql == null)
                    {
                        FoxEventLog.WriteEventLog("Cannot connect to SQL Server for Event Log Data Reporting!", System.Diagnostics.EventLogEntryType.Error);
                        return;
                    }
                    List <EventLogReportFull> EventDataList = (List <EventLogReportFull>)EventDataListO;
                    if (EventDataList.Count == 0)
                    {
                        return;
                    }
                    List <PolicyObject>        Pol             = Policies.GetPolicyForComputerInternal(sql, EventDataList[0].MachineID);
                    Dictionary <string, Int64> AlreadyReported = new Dictionary <string, long>();
                    foreach (PolicyObject PolO in Pol)
                    {
                        if (PolO.Type != PolicyIDs.ReportingPolicy)
                        {
                            continue;
                        }
                        ReportingPolicyElement RepElementRoot = JsonConvert.DeserializeObject <ReportingPolicyElement>(Policies.GetPolicy(sql, PolO.ID).Data);
                        if (RepElementRoot.Type != ReportingPolicyType.EventLog)
                        {
                            continue;
                        }
                        if (RepElementRoot.ReportToAdmin == null)
                        {
                            RepElementRoot.ReportToAdmin = false;
                        }
                        if (RepElementRoot.ReportToClient == null)
                        {
                            RepElementRoot.ReportToClient = false;
                        }
                        if (RepElementRoot.UrgentForAdmin == null)
                        {
                            RepElementRoot.UrgentForAdmin = false;
                        }
                        if (RepElementRoot.UrgentForClient == null)
                        {
                            RepElementRoot.UrgentForClient = false;
                        }
                        if (RepElementRoot.ReportToAdmin == false && RepElementRoot.ReportToClient == false && RepElementRoot.UrgentForAdmin == false && RepElementRoot.UrgentForClient == false)
                        {
                            continue;
                        }

                        foreach (string Element in RepElementRoot.ReportingElements)
                        {
                            ReportingPolicyElementEventLog evrep = JsonConvert.DeserializeObject <ReportingPolicyElementEventLog>(Element);
                            if (evrep.Book == null)
                            {
                                evrep.Book = new List <string>();
                            }
                            if (evrep.CategoryNumbers == null)
                            {
                                evrep.CategoryNumbers = new List <int>();
                            }
                            if (evrep.EventLogTypes == null)
                            {
                                evrep.EventLogTypes = new List <int>();
                            }
                            if (evrep.Sources == null)
                            {
                                evrep.Sources = new List <string>();
                            }
                            if (evrep.Book.Count == 0 && evrep.CategoryNumbers.Count == 0 && evrep.EventLogTypes.Count == 0 && evrep.Sources.Count == 0)
                            {
                                continue;
                            }
                            foreach (EventLogReportFull EV in EventDataList)
                            {
                                if (evrep.Book.Count != 0)
                                {
                                    bool Match = false;
                                    foreach (string Book in evrep.Book)
                                    {
                                        if (Book.ToLower() == EV.EventLog.ToLower())
                                        {
                                            Match = true;
                                            break;
                                        }
                                    }
                                    if (Match == false)
                                    {
                                        continue;
                                    }
                                }
                                if (evrep.Sources.Count != 0)
                                {
                                    bool Match = false;
                                    foreach (string Source in evrep.Sources)
                                    {
                                        if (Source.ToLower() == EV.Source.ToLower())
                                        {
                                            Match = true;
                                            break;
                                        }
                                    }
                                    if (Match == false)
                                    {
                                        continue;
                                    }
                                }
                                if (evrep.EventLogTypes.Count != 0)
                                {
                                    bool Match = false;
                                    foreach (int EVLType in evrep.EventLogTypes)
                                    {
                                        if (EVLType == EV.EventLogType)
                                        {
                                            Match = true;
                                            break;
                                        }
                                    }
                                    if (Match == false)
                                    {
                                        continue;
                                    }
                                }
                                if (evrep.CategoryNumbers.Count != 0)
                                {
                                    bool Match = false;
                                    foreach (int Cat in evrep.CategoryNumbers)
                                    {
                                        if (Cat == (EV.InstanceID & 0x3FFFFFFF))
                                        {
                                            Match = true;
                                            break;
                                        }
                                    }
                                    if (Match == false)
                                    {
                                        continue;
                                    }
                                }

                                if (evrep.IncludeExclude == 1) //include
                                {
                                    if (evrep.IncludeExcludeTexts != null)
                                    {
                                        bool Match = false;
                                        foreach (string s in evrep.IncludeExcludeTexts)
                                        {
                                            if (EV.Message.ToLower().Contains(s.ToLower()) == true)
                                            {
                                                Match = true;
                                                break;
                                            }
                                        }
                                        if (Match == false)
                                        {
                                            continue;
                                        }
                                    }
                                }

                                if (evrep.IncludeExclude == 2) //exclude
                                {
                                    if (evrep.IncludeExcludeTexts != null)
                                    {
                                        bool Match = true;
                                        foreach (string s in evrep.IncludeExcludeTexts)
                                        {
                                            if (EV.Message.ToLower().Contains(s.ToLower()) == true)
                                            {
                                                Match = false;
                                                break;
                                            }
                                        }
                                        if (Match == false)
                                        {
                                            continue;
                                        }
                                    }
                                }

                                bool ReportToAdmin   = RepElementRoot.ReportToAdmin.Value;
                                bool ReportToClient  = RepElementRoot.ReportToClient.Value;
                                bool UrgentForAdmin  = RepElementRoot.UrgentForAdmin.Value;
                                bool UrgentForClient = RepElementRoot.UrgentForClient.Value;

                                if (AlreadyReported.ContainsKey(EV.LogID) == true)
                                {
                                    if ((AlreadyReported[EV.LogID] & (Int64)ReportingFlags.ReportToAdmin) != 0)
                                    {
                                        ReportToAdmin = false;
                                    }
                                    if ((AlreadyReported[EV.LogID] & (Int64)ReportingFlags.ReportToClient) != 0)
                                    {
                                        ReportToClient = false;
                                    }
                                    if ((AlreadyReported[EV.LogID] & (Int64)ReportingFlags.UrgentForAdmin) != 0)
                                    {
                                        UrgentForAdmin = false;
                                    }
                                    if ((AlreadyReported[EV.LogID] & (Int64)ReportingFlags.UrgentForClient) != 0)
                                    {
                                        UrgentForClient = false;
                                    }
                                }

                                if (ReportToAdmin == false && ReportToClient == false && UrgentForAdmin == false && UrgentForClient == false)
                                {
                                    continue;
                                }
                                ReportingFlags Flags = (ReportToAdmin == true ? ReportingFlags.ReportToAdmin : 0) |
                                                       (ReportToClient == true ? ReportingFlags.ReportToClient : 0) |
                                                       (UrgentForAdmin == true ? ReportingFlags.UrgentForAdmin : 0) |
                                                       (UrgentForClient == true ? ReportingFlags.UrgentForClient : 0);
                                switch ((EventLogEntryType)EV.EventLogType)
                                {
                                case 0:
                                case EventLogEntryType.Information:
                                    Flags = (ReportingFlags)((Int64)Flags | ((Int64)ReportingStatusPictureEnum.Info << (int)ReportingFlags.IconFlagsShift));
                                    break;

                                case EventLogEntryType.Warning:
                                    Flags = (ReportingFlags)((Int64)Flags | ((Int64)ReportingStatusPictureEnum.Exclamation << (int)ReportingFlags.IconFlagsShift));
                                    break;

                                case EventLogEntryType.Error:
                                    Flags = (ReportingFlags)((Int64)Flags | ((Int64)ReportingStatusPictureEnum.Stop << (int)ReportingFlags.IconFlagsShift));
                                    break;

                                case EventLogEntryType.SuccessAudit:
                                    Flags = (ReportingFlags)((Int64)Flags | ((Int64)ReportingStatusPictureEnum.Key << (int)ReportingFlags.IconFlagsShift));
                                    break;

                                case EventLogEntryType.FailureAudit:
                                    Flags = (ReportingFlags)((Int64)Flags | ((Int64)ReportingStatusPictureEnum.NoKey << (int)ReportingFlags.IconFlagsShift));
                                    break;
                                }
                                ReportingProcessor.ReportEventLog(sql, EV.MachineID, EV, Flags);
                                if (AlreadyReported.ContainsKey(EV.LogID) == true)
                                {
                                    AlreadyReported[EV.LogID] |= (Int64)Flags;
                                }
                                else
                                {
                                    AlreadyReported.Add(EV.LogID, (Int64)Flags);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ee)
            {
                FoxEventLog.WriteEventLog("SEH in Event Data Reporting " + ee.ToString(), System.Diagnostics.EventLogEntryType.Error);
            }
        }
Exemplo n.º 15
0
        public RESTStatus ReportAddRemovePrograms(SQLLib sql, ListAddRemoveApps AddRemoveList, NetworkConnectionInfo ni)
        {
            if (ni.HasAcl(ACLFlags.ComputerLogin) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

            AddRemoveList.MachineID = ni.Username;

            lock (ni.sqllock)
            {
                if (Convert.ToInt32(sql.ExecSQLScalar("SELECT COUNT(*) FROM ComputerAccounts WHERE MachineID=@m",
                                                      new SQLParam("@m", AddRemoveList.MachineID))) == 0)
                {
                    ni.Error   = "Invalid MachineID";
                    ni.ErrorID = ErrorFlags.InvalidValue;
                    return(RESTStatus.Denied);
                }
            }

            if (AddRemoveList.Items == null)
            {
                ni.Error   = "Invalid Items";
                ni.ErrorID = ErrorFlags.InvalidValue;
                return(RESTStatus.Fail);
            }
            if (AddRemoveList.SIDUsers == null)
            {
                AddRemoveList.SIDUsers = new List <string>();
            }

            foreach (AddRemoveApp rep in AddRemoveList.Items)
            {
                if (rep.ProductID == null)
                {
                    rep.ProductID = "";
                }
                if (rep.Name == null)
                {
                    rep.Name = "";
                }
                if (rep.DisplayVersion == null)
                {
                    rep.DisplayVersion = "";
                }
                if (rep.UninstallString == null)
                {
                    rep.UninstallString = "";
                }
                if (rep.Language == null)
                {
                    rep.Language = "";
                }
                if (rep.DisplayLanguage == null)
                {
                    rep.DisplayLanguage = "";
                }
                if (rep.HKCUUser == null)
                {
                    rep.HKCUUser = "";
                }

                rep.ProductID       = rep.ProductID.Trim();
                rep.Name            = rep.Name.Trim();
                rep.DisplayVersion  = rep.DisplayVersion.Trim();
                rep.UninstallString = rep.UninstallString.Trim();
                rep.Language        = rep.Language.Trim();
                rep.DisplayLanguage = rep.DisplayLanguage.Trim();
                rep.HKCUUser        = rep.HKCUUser.Trim();
            }

            List <AddRemoveApp> Installed = new List <AddRemoveApp>();
            List <AddRemoveApp> Reported  = AddRemoveList.Items;

            lock (ni.sqllock)
            {
                SqlDataReader dr = sql.ExecSQLReader("SELECT * FROM AddRemovePrograms WHERE MachineID=@id", new SQLParam("@id", AddRemoveList.MachineID));
                while (dr.Read())
                {
                    AddRemoveApp ar = new AddRemoveApp();
                    ar.DisplayLanguage   = Convert.ToString(dr["DisplayLanguage"]);
                    ar.DisplayVersion    = Convert.ToString(dr["DisplayVersion"]);
                    ar.IsMSI             = Convert.ToBoolean(dr["IsMSI"]);
                    ar.IsWOWBranch       = Convert.ToBoolean(dr["IsWOWBranch"]);
                    ar.IsSystemComponent = Convert.ToBoolean(dr["IsSystemComponent"]);
                    ar.Language          = Convert.ToString(dr["Language"]);
                    ar.MachineID         = Convert.ToString(dr["MachineID"]);
                    ar.Name            = Convert.ToString(dr["Name"]);
                    ar.ProductID       = Convert.ToString(dr["ProductID"]);
                    ar.UninstallString = Convert.ToString(dr["UninstallString"]);
                    ar.VersionMajor    = Convert.ToInt32(dr["VersionMajor"]);
                    ar.VersionMinor    = Convert.ToInt32(dr["VersionMinor"]);
                    ar.HKCUUser        = Convert.ToString(dr["HKCUUser"]);
                    if (string.IsNullOrWhiteSpace(ar.HKCUUser) == true)
                    {
                        ar.HKCUUser = "";
                    }

                    Installed.Add(ar);
                }
                dr.Close();
            }

            List <AddRemoveApp> Updated   = new List <AddRemoveApp>();
            List <AddRemoveApp> Unchanged = new List <AddRemoveApp>();
            List <AddRemoveApp> Removed   = new List <AddRemoveApp>();
            List <AddRemoveApp> Added     = new List <AddRemoveApp>();

            foreach (AddRemoveApp inst in Installed)
            {
                if (inst.ProductID == null)
                {
                    inst.ProductID = "";
                }
                if (inst.Name == null)
                {
                    inst.Name = "";
                }
                if (inst.DisplayVersion == null)
                {
                    inst.DisplayVersion = "";
                }
                if (inst.UninstallString == null)
                {
                    inst.UninstallString = "";
                }
                if (inst.Language == null)
                {
                    inst.Language = "";
                }
                if (inst.DisplayLanguage == null)
                {
                    inst.DisplayLanguage = "";
                }

                inst.ProductID       = inst.ProductID.Trim();
                inst.Name            = inst.Name.Trim();
                inst.DisplayVersion  = inst.DisplayVersion.Trim();
                inst.UninstallString = inst.UninstallString.Trim();
                inst.Language        = inst.Language.Trim();
                inst.DisplayLanguage = inst.DisplayLanguage.Trim();
                inst.HKCUUser        = inst.HKCUUser.Trim();

                bool Found = false;
                foreach (AddRemoveApp rep in Reported)
                {
                    if (rep.ProductID.ToLower() == inst.ProductID.ToLower() && rep.IsWOWBranch == inst.IsWOWBranch && rep.HKCUUser == inst.HKCUUser)
                    {
                        if (rep.IsMSI == inst.IsMSI && rep.IsSystemComponent == inst.IsSystemComponent && rep.Name.ToLower() == inst.Name.ToLower() &&
                            rep.DisplayVersion.ToLower() == inst.DisplayVersion.ToLower() && inst.UninstallString.ToLower() == rep.UninstallString.ToLower() &&
                            rep.VersionMajor == inst.VersionMajor && rep.VersionMinor == inst.VersionMinor && rep.Language.ToLower() == inst.Language.ToLower() &&
                            rep.DisplayLanguage.ToLower() == inst.DisplayLanguage.ToLower())
                        {
                            Unchanged.Add(rep);
                            Found = true;
                            break;
                        }
                        else
                        {
                            Updated.Add(rep);
                            Found = true;
                            break;
                        }
                    }
                }
                if (Found == false)
                {
                    if (inst.HKCUUser != "" && AddRemoveList.SIDUsers.Contains(inst.HKCUUser, StringComparer.InvariantCultureIgnoreCase) == false)
                    {
                        //likely that this user is not logged on or such
                        Unchanged.Add(inst);
                    }
                    else
                    {
                        Removed.Add(inst);
                    }
                }
            }

            foreach (AddRemoveApp inst in Reported)
            {
                bool Found = false;
                foreach (AddRemoveApp rep in Installed)
                {
                    if (rep.ProductID.ToLower() == inst.ProductID.ToLower() && rep.IsWOWBranch == inst.IsWOWBranch && rep.HKCUUser == inst.HKCUUser)
                    {
                        Found = true;
                        break;
                    }
                }
                if (Found == false)
                {
                    Added.Add(inst);
                }
            }

            lock (ni.sqllock)
            {
                try
                {
                    sql.BeginTransaction();
                    sql.SEHError = true;
                    foreach (AddRemoveApp ar in Removed)
                    {
                        sql.ExecSQL("DELETE FROM AddRemovePrograms WHERE MachineID=@id AND IsWOWBranch=@wow AND ProductID=@prod AND HKCUUser=@user",
                                    new SQLParam("@id", AddRemoveList.MachineID),
                                    new SQLParam("@prod", ar.ProductID),
                                    new SQLParam("@user", ar.HKCUUser),
                                    new SQLParam("@wow", ar.IsWOWBranch));
                    }
                    foreach (AddRemoveApp ar in Updated)
                    {
                        sql.ExecSQL(@"UPDATE AddRemovePrograms SET
                            IsMSI=@IsMSI,
                            IsSystemComponent=@IsSystemComponent,
                            Name=@Name,
                            DisplayVersion=@DisplayVersion,
                            UninstallString=@UninstallString,
                            VersionMajor=@VersionMajor,
                            VersionMinor=@VersionMinor,
                            Language=@Language,
                            DisplayLanguage=@DisplayLanguage,
                            DT=@DT
                            WHERE MachineID=@id AND IsWOWBranch=@wow AND ProductID=@prod AND HKCUUser=@user",
                                    new SQLParam("@id", AddRemoveList.MachineID),
                                    new SQLParam("@prod", ar.ProductID),
                                    new SQLParam("@wow", ar.IsWOWBranch),
                                    new SQLParam("@IsMSI", ar.IsMSI),
                                    new SQLParam("@IsSystemComponent", ar.IsSystemComponent),
                                    new SQLParam("@Name", ar.Name.Trim()),
                                    new SQLParam("@DisplayVersion", ar.DisplayVersion),
                                    new SQLParam("@UninstallString", ar.UninstallString),
                                    new SQLParam("@VersionMajor", ar.VersionMajor),
                                    new SQLParam("@VersionMinor", ar.VersionMinor),
                                    new SQLParam("@Language", ar.Language),
                                    new SQLParam("@DisplayLanguage", ar.DisplayLanguage),
                                    new SQLParam("@user", ar.HKCUUser),
                                    new SQLParam("@DT", DateTime.UtcNow));
                    }
                    foreach (AddRemoveApp ar in Added)
                    {
                        sql.InsertMultiData("AddRemovePrograms",
                                            new SQLData("MachineID", AddRemoveList.MachineID),
                                            new SQLData("ProductID", ar.ProductID),
                                            new SQLData("IsWOWBranch", ar.IsWOWBranch),
                                            new SQLData("IsMSI", ar.IsMSI),
                                            new SQLData("IsSystemComponent", ar.IsSystemComponent),
                                            new SQLData("Name", ar.Name.Trim()),
                                            new SQLData("DisplayVersion", ar.DisplayVersion),
                                            new SQLData("UninstallString", ar.UninstallString),
                                            new SQLData("VersionMajor", ar.VersionMajor),
                                            new SQLData("VersionMinor", ar.VersionMinor),
                                            new SQLData("Language", ar.Language),
                                            new SQLData("DisplayLanguage", ar.DisplayLanguage),
                                            new SQLData("HKCUUser", ar.HKCUUser),
                                            new SQLData("DT", DateTime.UtcNow));
                    }
                    sql.CommitTransaction();
                }
                catch (Exception ee)
                {
                    sql.RollBackTransaction();
                    FoxEventLog.WriteEventLog("DB Error: Cannot update AddRemovePrograms: " + ee.ToString(), System.Diagnostics.EventLogEntryType.Error);
                    return(RESTStatus.ServerError);
                }
                finally
                {
                    sql.SEHError = false;
                }
            }

            AddRemoveProgramsLst l = new AddRemoveProgramsLst();

            l.Added     = Added;
            l.Removed   = Removed;
            l.Unchanged = Unchanged;
            l.Updated   = Updated;
            l.MachineID = AddRemoveList.MachineID;
            Thread t = new Thread(new ParameterizedThreadStart(new DReportingThread(ReportingThread)));

            t.Start(l);

            return(RESTStatus.Created);
        }
Exemplo n.º 16
0
        public static void SMain()
        {
            string ErrorReason;

            Console.WriteLine("Server version: " + Assembly.GetExecutingAssembly().GetName().Version.ToString() + (InstanceID == "" ? "" : " (" + InstanceID + ")"));
            FoxEventLog.WriteEventLog("Server version: " + Assembly.GetExecutingAssembly().GetName().Version.ToString() + " starting" + (InstanceID == "" ? "" : " (" + InstanceID + ")"), EventLogEntryType.Information);
            if (SQLTest.TestSettings(out ErrorReason) == false)
            {
                FoxEventLog.WriteEventLog("Settings are faulty: " + ErrorReason, EventLogEntryType.Error);
                Console.WriteLine("Settings are faulty: " + ErrorReason);
#if !DEBUG
                Process.GetCurrentProcess().Kill();
#endif
                return;
            }
            if (SQLTest.TestServer(out ErrorReason) == false)
            {
                FoxEventLog.WriteEventLog("Cannot connect to the server: " + ErrorReason, EventLogEntryType.Error);
                Console.WriteLine("Cannot connect to the server: " + ErrorReason);
#if !DEBUG
                Process.GetCurrentProcess().Kill();
#endif
                return;
            }
            RESTful.RegisterRESTfulClasses();
            FS_Watcher.InstallFSW();

            if (Utilities.TestSign(out ErrorReason) == false)
            {
                FoxEventLog.WriteEventLog("Cannot test-sign with the certificate " + SettingsManager.Settings.UseCertificate + ": " + ErrorReason, EventLogEntryType.Warning);
            }

#if DEBUG
            if (Fox_LicenseGenerator.SDCLicensing.ValidLicense == false)
            {
                FoxEventLog.WriteEventLog("Writing a crap-license into memory.", EventLogEntryType.Information);
                Fox_LicenseGenerator.SDCLicensing.NumComputers        = 1000;
                Fox_LicenseGenerator.SDCLicensing.AllowContract       = true;
                Fox_LicenseGenerator.SDCLicensing.Data                = new Fox_LicenseGenerator.LicensingData();
                Fox_LicenseGenerator.SDCLicensing.Data.Features       = "";
                Fox_LicenseGenerator.SDCLicensing.Data.LicenseID      = Guid.NewGuid().ToString();
                Fox_LicenseGenerator.SDCLicensing.Data.LicenseType    = "Memory";
                Fox_LicenseGenerator.SDCLicensing.Data.Owner          = "Fox";
                Fox_LicenseGenerator.SDCLicensing.Data.OwnerCustomID  = "";
                Fox_LicenseGenerator.SDCLicensing.Data.SupportValidTo = null;
                Fox_LicenseGenerator.SDCLicensing.Data.UCID           = UCID.GetUCID();
                Fox_LicenseGenerator.SDCLicensing.Data.ValidTo        = null;
                Fox_LicenseGenerator.SDCLicensing.Data.ValidFrom      = DateTime.UtcNow.Date;
                Fox_LicenseGenerator.SDCLicensing.Data.Vacant1        = "1000";
                Fox_LicenseGenerator.SDCLicensing.ValidLicense        = true;
            }
#endif

            try
            {
                Console.CancelKeyPress += Console_CancelKeyPress;
                WebServerHandler.RunWebServer();
                MaintenanceTasks.StartMaintenanceTreads();
                ReportingThread.StartReportingThreads();
                RemoteNetworkConnectionWSCrosser.InitialInitWS();
                Console.WriteLine("=============== Server started ===============");
                Debug.WriteLine("=============== Server started ===============");
                Console.WriteLine(Settings.Default.ListenOn);
                Debug.WriteLine(Settings.Default.ListenOn);
                Console.WriteLine(Settings.Default.WSListenOn);
                Debug.WriteLine(Settings.Default.WSListenOn);
                FoxEventLog.WriteEventLog("Server started", EventLogEntryType.Information);
                ServiceRunning = true;
                Thread tmm = new Thread(new ThreadStart(TimeoutManager));
                tmm.Start();
                do
                {
                    Thread.Sleep(1000);
                } while (ServiceRunning == true);
            }
            catch (Exception ee)
            {
                FoxEventLog.WriteEventLog("Cannot start server " + ee.Message, EventLogEntryType.Error);
                Console.WriteLine("Cannot start server " + ee.Message);
#if !DEBUG
                Process.GetCurrentProcess().Kill();
#endif
                return;
            }
        }
Exemplo n.º 17
0
        public RESTStatus GetPolicyForComputer(SQLLib sql, object dummy, NetworkConnectionInfo ni)
        {
            if (ni.HasAcl(ACLFlags.ComputerLogin) == false)
            {
                ni.Error   = "Access denied";
                ni.ErrorID = ErrorFlags.AccessDenied;
                return(RESTStatus.Denied);
            }

            PolicyListSigned       = new PolicyObjectListSigned();
            PolicyListSigned.Items = new List <PolicyObjectSigned>();

            string MachineID = ni.Username;

            lock (ni.sqllock)
            {
                SqlDataReader dr = sql.ExecSQLReader("SELECT * FROM Policies WHERE MachineID=@m AND Enabled=1 AND Type not in (" + PolicyIDs.HiddenPoliciesSQLINClause + ")",
                                                     new SQLParam("@m", MachineID));
                while (dr.Read())
                {
                    PolicyObject       obj  = LoadPolicyDB(dr, false, true);
                    PolicyObjectSigned objs = new PolicyObjectSigned();
                    objs.Policy = obj;
                    if (Certificates.Sign(objs, SettingsManager.Settings.UseCertificate) == false)
                    {
                        FoxEventLog.WriteEventLog("Cannot sign policy with Certificate " + SettingsManager.Settings.UseCertificate, System.Diagnostics.EventLogEntryType.Warning);
                        ni.Error   = "Cannot sign policy with Certificate " + SettingsManager.Settings.UseCertificate;
                        ni.ErrorID = ErrorFlags.CannotSign;
                        dr.Close();
                        return(RESTStatus.ServerError);
                    }
                    PolicyListSigned.Items.Add(objs);
                }
                dr.Close();
            }

            Int64? GroupID = null;
            object sqlo    = sql.ExecSQLScalar("select Grouping from ComputerAccounts where MachineID=@m", new SQLParam("@m", MachineID));

            if (sqlo is DBNull || sqlo == null)
            {
                GroupID = null;
            }
            else
            {
                GroupID = Convert.ToInt64(sqlo);
            }

            do
            {
                lock (ni.sqllock)
                {
                    SqlDataReader dr = sql.ExecSQLReader("SELECT * FROM Policies WHERE " + (GroupID == null ? "Grouping is NULL" : "Grouping=@g") + " AND Enabled=1 AND Type NOT IN (" + PolicyIDs.HiddenPoliciesSQLINClause + ") AND MachineID is NULL",
                                                         new SQLParam("@g", GroupID));
                    while (dr.Read())
                    {
                        PolicyObject       obj  = LoadPolicyDB(dr, false, true);
                        PolicyObjectSigned objs = new PolicyObjectSigned();
                        objs.Policy = obj;
                        PolicyListSigned.Items.Add(objs);
                    }
                    dr.Close();
                }

                if (GroupID != null)
                {
                    lock (ni.sqllock)
                    {
                        sqlo = sql.ExecSQLScalar("select ParentID FROM Grouping WHERE ID=@g", new SQLParam("@g", GroupID));
                    }

                    if (sqlo is DBNull || sqlo == null)
                    {
                        GroupID = null;
                    }
                    else
                    {
                        GroupID = Convert.ToInt64(sqlo);
                    }
                }
                else
                {
                    break;
                }
            } while (true);

            PolicyListSigned.Items.Reverse();
            Int64 Count = 1;

            foreach (PolicyObjectSigned p in PolicyListSigned.Items)
            {
                p.Policy.Order = Count;
                Count++;
                if (Certificates.Sign(p, SettingsManager.Settings.UseCertificate) == false)
                {
                    FoxEventLog.WriteEventLog("Cannot sign policy with Certificate " + SettingsManager.Settings.UseCertificate, System.Diagnostics.EventLogEntryType.Warning);
                    ni.Error   = "Cannot sign policy with Certificate " + SettingsManager.Settings.UseCertificate;
                    ni.ErrorID = ErrorFlags.CannotSign;
                    return(RESTStatus.ServerError);
                }
            }

            List <PolicyObjectSigned> RemoveFromList = new List <PolicyObjectSigned>();

            #region Resolve Linked Policies for client

            for (int i = 0; i < PolicyListSigned.Items.Count; i++)
            {
                PolicyObjectSigned pol = PolicyListSigned.Items[i];
                if (pol.Policy.Type == PolicyIDs.LinkedPolicy)
                {
                    List <Int64> RunningIDs = new List <Int64>();

                    PolicyObject po = pol.Policy;

                    while (true)
                    {
                        if (RunningIDs.Contains(po.ID) == true)
                        {
                            FoxEventLog.WriteEventLog("Policy ID " + pol.Policy.ID.ToString() + " (" + pol.Policy.Name + ") creates a loop!", System.Diagnostics.EventLogEntryType.Warning);
                            break;
                        }

                        RunningIDs.Add(po.ID);

                        lock (ni.sqllock)
                        {
                            po.Data = Convert.ToString(sql.ExecSQLScalar("SELECT DataBlob FROM Policies WHERE ID=@id",
                                                                         new SQLParam("@id", po.ID)));
                        }

                        Int64 PolID;
                        if (Int64.TryParse(po.Data, out PolID) == false)
                        {
                            FoxEventLog.WriteEventLog("Cannot read data of policy ID " + po.ID.ToString() + " (" + po.Name + ") for linking.", System.Diagnostics.EventLogEntryType.Warning);
                            break;
                        }

                        lock (ni.sqllock)
                        {
                            if (Policies.PolicyExsits(sql, PolID) == false)
                            {
                                FoxEventLog.WriteEventLog("Policy ID " + PolID.ToString() + " referencing from " + po.ID.ToString() + " (" + po.Name + ") does not exist.", System.Diagnostics.EventLogEntryType.Warning);
                                break;
                            }
                        }

                        lock (ni.sqllock)
                        {
                            if (Convert.ToInt32(sql.ExecSQLScalar("SELECT Enabled FROM Policies WHERE ID=@id", new SQLParam("@id", PolID))) != 1)
                            {
                                break;
                            }
                        }

                        lock (ni.sqllock)
                        {
                            SqlDataReader dr = sql.ExecSQLReader("SELECT * FROM Policies WHERE ID=@id",
                                                                 new SQLParam("@id", PolID));
                            dr.Read();
                            po = LoadPolicyDB(dr, false, true);
                            dr.Close();
                        }

                        if (po == null)
                        {
                            FoxEventLog.WriteEventLog("Cannot read policy ID for linking " + PolID.ToString(), System.Diagnostics.EventLogEntryType.Warning);
                            break;
                        }

                        if (po.Type != PolicyIDs.LinkedPolicy)
                        {
                            if (PolicyIDs.HiddenPolicies.Contains(po.Type) == true)
                            {
                                pol.Policy    = null;
                                pol.Signature = null;
                                break;
                            }
                            else
                            {
                                pol.Policy    = po;
                                pol.Signature = null;
                                break;
                            }
                        }
                    }

                    if (pol.Policy != null)
                    {
                        if (Certificates.Sign(pol, SettingsManager.Settings.UseCertificate) == false)
                        {
                            FoxEventLog.WriteEventLog("Cannot sign policy with Certificate " + SettingsManager.Settings.UseCertificate, System.Diagnostics.EventLogEntryType.Warning);
                            ni.Error   = "Cannot sign policy with Certificate " + SettingsManager.Settings.UseCertificate;
                            ni.ErrorID = ErrorFlags.CannotSign;
                            return(RESTStatus.ServerError);
                        }
                    }
                    else
                    {
                        RemoveFromList.Add(pol);
                    }
                }
            }

            foreach (PolicyObjectSigned pos in RemoveFromList)
            {
                PolicyListSigned.Items.Remove(pos);
            }

            #endregion

            if (Certificates.Sign(PolicyListSigned, SettingsManager.Settings.UseCertificate) == false)
            {
                FoxEventLog.WriteEventLog("Cannot sign policy list with Certificate " + SettingsManager.Settings.UseCertificate, System.Diagnostics.EventLogEntryType.Warning);
                ni.Error   = "Cannot sign policy list with Certificate " + SettingsManager.Settings.UseCertificate;
                ni.ErrorID = ErrorFlags.CannotSign;
                return(RESTStatus.ServerError);
            }

            return(RESTStatus.Success);
        }
Exemplo n.º 18
0
        static void RThread()
        {
            do
            {
                try
                {
                    using (SQLLib sql = SQLTest.ConnectSQL("Fox SDC Server for Reporting", 0))
                    {
                        if (sql == null)
                        {
                            Pause();
                            if (StopThread == true)
                            {
                                break;
                            }
                        }
                        string ErrorMessage;
                        if (MailSender.CheckConfig() == false)
                        {
                            Pause();
                            if (StopThread == true)
                            {
                                break;
                            }
                            continue;
                        }

                        if (string.IsNullOrWhiteSpace(SettingsManager.Settings.EMailAdminTo) == true)
                        {
                            Pause();
                            if (StopThread == true)
                            {
                                break;
                            }
                            continue;
                        }

                        SqlDataReader dr;
                        List <string> ConcernedMachineIDs;

                        #region Normal Admin Report

                        if (SettingsManager.Settings.LastScheduleRanAdmin == null)
                        {
                            SettingsManager.Settings.LastScheduleRanAdmin = DateTime.UtcNow;
                            SettingsManager.SaveApplySettings2(sql, SettingsManager.Settings);
                        }
                        else
                        {
                            DateTime?Planned = Scheduler.GetNextRunDate(SettingsManager.Settings.LastScheduleRanAdmin.Value, SettingsManager.Settings.EMailAdminScheduling);
                            if (RunAdminNow == true)
                            {
                                Planned     = DateTime.UtcNow.AddMinutes(-1);
                                RunAdminNow = false;
                            }

                            if (Planned != null)
                            {
                                if (Planned.Value < DateTime.UtcNow) //is in the past - run now (may also be a "miss")
                                {
                                    dr = sql.ExecSQLReader("Select distinct machineid from Reporting where (Flags & @f1)!=0 AND (Flags & @f2)=0",
                                                           new SQLParam("@f1", ReportingFlags.ReportToAdmin),
                                                           new SQLParam("@f2", ReportingFlags.AdminReported));

                                    ConcernedMachineIDs = new List <string>();

                                    while (dr.Read())
                                    {
                                        ConcernedMachineIDs.Add(Convert.ToString(dr["MachineID"]));
                                    }
                                    dr.Close();

                                    if (ConcernedMachineIDs.Count > 0)
                                    {
                                        byte[] PDFFile = RenderReport.RenderMachineReport(sql, ConcernedMachineIDs, null, null, ReportingFlagsPaper.ReportAdmin, "PDF");
                                        if (PDFFile == null)
                                        {
                                            FoxEventLog.WriteEventLog("Admin Report has no data.", System.Diagnostics.EventLogEntryType.Error);
                                        }
                                        else
                                        {
                                            string Text    = SettingsManager.Settings.EMailAdminText;
                                            string Subject = SettingsManager.Settings.EMailAdminSubject;
                                            Text = Text.Replace("{URGENT}", "").
                                                   Replace("{NMACHINESS}", ConcernedMachineIDs.Count == 1 ? "" : "s").
                                                   Replace("{NMACHINES}", ConcernedMachineIDs.Count.ToString());
                                            Subject = Subject.Replace("{URGENT}", "").
                                                      Replace("{NMACHINESS}", ConcernedMachineIDs.Count == 1 ? "" : "s").
                                                      Replace("{NMACHINES}", ConcernedMachineIDs.Count.ToString());
                                            if (MailSender.SendEMailAdmin(Subject, Text, new List <System.Net.Mail.Attachment> {
                                                new System.Net.Mail.Attachment(new MemoryStream(PDFFile), ReportAttachementFilename)
                                            }, System.Net.Mail.MailPriority.Normal, out ErrorMessage, SettingsManager.Settings.EMailAdminIsHTML) == false)
                                            {
                                                FoxEventLog.WriteEventLog("Cannot send Admin E-Mail: " + ErrorMessage, System.Diagnostics.EventLogEntryType.Error);
                                            }
                                        }
                                    }

                                    SettingsManager.Settings.LastScheduleRanAdmin = DateTime.UtcNow;
                                    SettingsManager.SaveApplySettings2(sql, SettingsManager.Settings);
                                }
                            }
                            else
                            {
                                //update anyways
                                SettingsManager.Settings.LastScheduleRanAdmin = DateTime.UtcNow;
                                SettingsManager.SaveApplySettings2(sql, SettingsManager.Settings);
                            }
                        }

                        #endregion

                        #region Urgent Admin

                        dr = sql.ExecSQLReader("Select distinct machineid from Reporting where (Flags & @f1)!=0 AND (Flags & @f2)=0",
                                               new SQLParam("@f1", ReportingFlags.UrgentForAdmin),
                                               new SQLParam("@f2", ReportingFlags.UrgentAdminReported));

                        ConcernedMachineIDs = new List <string>();

                        while (dr.Read())
                        {
                            ConcernedMachineIDs.Add(Convert.ToString(dr["MachineID"]));
                        }
                        dr.Close();

                        if (ConcernedMachineIDs.Count > 0)
                        {
                            byte[] PDFFile = RenderReport.RenderMachineReport(sql, ConcernedMachineIDs, null, null, ReportingFlagsPaper.UrgentAdmin, "PDF");
                            if (PDFFile == null)
                            {
                                FoxEventLog.WriteEventLog("Urgent Admin Report has no data.", System.Diagnostics.EventLogEntryType.Error);
                            }
                            else
                            {
                                string Text    = SettingsManager.Settings.EMailAdminText;
                                string Subject = SettingsManager.Settings.EMailAdminSubject;
                                Text = Text.Replace("{URGENT}", "Urgent ").
                                       Replace("{NMACHINESS}", ConcernedMachineIDs.Count == 1 ? "" : "s").
                                       Replace("{NMACHINES}", ConcernedMachineIDs.Count.ToString());
                                Subject = Subject.Replace("{URGENT}", "Urgent ").
                                          Replace("{NMACHINESS}", ConcernedMachineIDs.Count == 1 ? "" : "s").
                                          Replace("{NMACHINES}", ConcernedMachineIDs.Count.ToString());
                                if (MailSender.SendEMailAdmin(Subject, Text, new List <System.Net.Mail.Attachment> {
                                    new System.Net.Mail.Attachment(new MemoryStream(PDFFile), ReportAttachementFilename)
                                }, System.Net.Mail.MailPriority.High, out ErrorMessage, SettingsManager.Settings.EMailAdminIsHTML) == false)
                                {
                                    FoxEventLog.WriteEventLog("Cannot send Urgent Admin E-Mail: " + ErrorMessage, System.Diagnostics.EventLogEntryType.Error);
                                }
                            }
                        }

                        #endregion

                        #region Normal Client Report

                        if (Settings.Default.UseContract == true)
                        {
                            if (SettingsManager.Settings.LastScheduleRanClient == null)
                            {
                                SettingsManager.Settings.LastScheduleRanClient = DateTime.UtcNow;
                                SettingsManager.SaveApplySettings2(sql, SettingsManager.Settings);
                            }
                            else
                            {
                                DateTime?Planned = Scheduler.GetNextRunDate(SettingsManager.Settings.LastScheduleRanClient.Value, SettingsManager.Settings.EMailClientScheduling);
                                if (Planned != null)
                                {
                                    if (Planned.Value < DateTime.UtcNow) //is in the past - run now (may also be a "miss")
                                    {
                                        dr = sql.ExecSQLReader(@"select ComputerAccounts.MachineID,ComputerAccounts.ContractID,EMail from ComputerAccounts
                                        inner join Contracts on Contracts.ContractID = ComputerAccounts.ContractID
                                        where Disabled = 0 and MachineID in (Select distinct machineid from Reporting where (Flags & @f1) != 0 AND(Flags & @f2) = 0) and EMail is not null and EMail !=''",
                                                               new SQLParam("@f1", ReportingFlags.ReportToClient),
                                                               new SQLParam("@f2", ReportingFlags.ClientReported));

                                        List <ConcernedMachineIDsClient> ConcernedMachineIDC = new List <ConcernedMachineIDsClient>();
                                        List <string> ContractIDs = new List <string>();

                                        while (dr.Read())
                                        {
                                            ConcernedMachineIDsClient m = new ConcernedMachineIDsClient();
                                            m.ContractID = Convert.ToString(dr["ContractID"]);
                                            m.MachineID  = Convert.ToString(dr["MachineID"]);
                                            m.EMail      = Convert.ToString(dr["EMail"]);
                                            ConcernedMachineIDC.Add(m);
                                            if (ContractIDs.Contains(m.ContractID) == false)
                                            {
                                                ContractIDs.Add(m.ContractID);
                                            }
                                        }
                                        dr.Close();

                                        foreach (string ContractID in ContractIDs)
                                        {
                                            List <string> ConcernedMachineIDsForClient = new List <string>();
                                            string        EMail = "";
                                            foreach (ConcernedMachineIDsClient m in ConcernedMachineIDC)
                                            {
                                                if (m.ContractID == ContractID)
                                                {
                                                    ConcernedMachineIDsForClient.Add(m.MachineID);
                                                }
                                                if (string.IsNullOrWhiteSpace(EMail) == true)
                                                {
                                                    EMail = m.EMail;
                                                }
                                            }

                                            if (string.IsNullOrWhiteSpace(EMail) == true)
                                            {
                                                continue;
                                            }

                                            if (ConcernedMachineIDsForClient.Count > 0)
                                            {
                                                byte[] PDFFile = RenderReport.RenderMachineReport(sql, ConcernedMachineIDsForClient, null, null, ReportingFlagsPaper.ReportClient, "PDF");
                                                if (PDFFile == null)
                                                {
                                                    FoxEventLog.WriteEventLog("Client Report has no data.", System.Diagnostics.EventLogEntryType.Error);
                                                }
                                                else
                                                {
                                                    string Text    = SettingsManager.Settings.EMailClientText;
                                                    string Subject = SettingsManager.Settings.EMailClientSubject;
                                                    Text = Text.Replace("{URGENT}", "").
                                                           Replace("{NMACHINESS}", ConcernedMachineIDsForClient.Count == 1 ? "" : "s").
                                                           Replace("{NMACHINES}", ConcernedMachineIDsForClient.Count.ToString());
                                                    Subject = Subject.Replace("{URGENT}", "").
                                                              Replace("{NMACHINESS}", ConcernedMachineIDsForClient.Count == 1 ? "" : "s").
                                                              Replace("{NMACHINES}", ConcernedMachineIDsForClient.Count.ToString());
                                                    if (MailSender.SendEMailClient(EMail, Subject, Text, new List <System.Net.Mail.Attachment> {
                                                        new System.Net.Mail.Attachment(new MemoryStream(PDFFile), ReportAttachementFilename)
                                                    }, System.Net.Mail.MailPriority.High, out ErrorMessage, SettingsManager.Settings.EMailClientIsHTML) == false)
                                                    {
                                                        FoxEventLog.WriteEventLog("Cannot send Client E-Mail: " + ErrorMessage, System.Diagnostics.EventLogEntryType.Error);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    //update anyways
                                    SettingsManager.Settings.LastScheduleRanClient = DateTime.UtcNow;
                                    SettingsManager.SaveApplySettings2(sql, SettingsManager.Settings);
                                }
                            }
                        }

                        #endregion

                        #region Urgent Client

                        if (Settings.Default.UseContract == true)
                        {
                            dr = sql.ExecSQLReader(@"select ComputerAccounts.MachineID,ComputerAccounts.ContractID,EMail from ComputerAccounts
                                inner join Contracts on Contracts.ContractID = ComputerAccounts.ContractID
                                where Disabled = 0 and MachineID in (Select distinct machineid from Reporting where (Flags & @f1) != 0 AND(Flags & @f2) = 0) and EMail is not null and EMail !=''",
                                                   new SQLParam("@f1", ReportingFlags.UrgentForClient),
                                                   new SQLParam("@f2", ReportingFlags.UrgentClientReported));

                            List <ConcernedMachineIDsClient> ConcernedMachineIDC = new List <ConcernedMachineIDsClient>();
                            List <string> ContractIDs = new List <string>();

                            while (dr.Read())
                            {
                                ConcernedMachineIDsClient m = new ConcernedMachineIDsClient();
                                m.ContractID = Convert.ToString(dr["ContractID"]);
                                m.MachineID  = Convert.ToString(dr["MachineID"]);
                                m.EMail      = Convert.ToString(dr["EMail"]);
                                ConcernedMachineIDC.Add(m);
                                if (ContractIDs.Contains(m.ContractID) == false)
                                {
                                    ContractIDs.Add(m.ContractID);
                                }
                            }
                            dr.Close();

                            foreach (string ContractID in ContractIDs)
                            {
                                List <string> ConcernedMachineIDsForClient = new List <string>();
                                string        EMail = "";
                                foreach (ConcernedMachineIDsClient m in ConcernedMachineIDC)
                                {
                                    if (m.ContractID == ContractID)
                                    {
                                        ConcernedMachineIDsForClient.Add(m.MachineID);
                                    }
                                    if (string.IsNullOrWhiteSpace(EMail) == true)
                                    {
                                        EMail = m.EMail;
                                    }
                                }

                                if (string.IsNullOrWhiteSpace(EMail) == true)
                                {
                                    continue;
                                }

                                if (ConcernedMachineIDsForClient.Count > 0)
                                {
                                    byte[] PDFFile = RenderReport.RenderMachineReport(sql, ConcernedMachineIDsForClient, null, null, ReportingFlagsPaper.UrgentClient, "PDF");
                                    if (PDFFile == null)
                                    {
                                        FoxEventLog.WriteEventLog("Urgent Client Report has no data.", System.Diagnostics.EventLogEntryType.Error);
                                    }
                                    else
                                    {
                                        string Text    = SettingsManager.Settings.EMailClientText;
                                        string Subject = SettingsManager.Settings.EMailClientSubject;
                                        Text = Text.Replace("{URGENT}", "Urgent ").
                                               Replace("{NMACHINESS}", ConcernedMachineIDsForClient.Count == 1 ? "" : "s").
                                               Replace("{NMACHINES}", ConcernedMachineIDsForClient.Count.ToString());
                                        Subject = Subject.Replace("{URGENT}", "Urgent ").
                                                  Replace("{NMACHINESS}", ConcernedMachineIDsForClient.Count == 1 ? "" : "s").
                                                  Replace("{NMACHINES}", ConcernedMachineIDsForClient.Count.ToString());
                                        if (MailSender.SendEMailClient(EMail, Subject, Text, new List <System.Net.Mail.Attachment> {
                                            new System.Net.Mail.Attachment(new MemoryStream(PDFFile), ReportAttachementFilename)
                                        }, System.Net.Mail.MailPriority.High, out ErrorMessage, SettingsManager.Settings.EMailClientIsHTML) == false)
                                        {
                                            FoxEventLog.WriteEventLog("Cannot send Urgent Client E-Mail: " + ErrorMessage, System.Diagnostics.EventLogEntryType.Error);
                                        }
                                    }
                                }
                            }
                        }

                        #endregion
                    }
                }
                catch (Exception ee)
                {
                    FoxEventLog.WriteEventLog("Cannot process reporting data\n" + ee.ToString(), System.Diagnostics.EventLogEntryType.Error);
                }

                Pause();
                if (StopThread == true)
                {
                    break;
                }
            } while (StopThread == false);
        }
Exemplo n.º 19
0
        void ReportingThread(object DiskDataListO)
        {
            try
            {
                using (SQLLib sql = SQLTest.ConnectSQL("Fox SDC Server for DiskData"))
                {
                    if (sql == null)
                    {
                        FoxEventLog.WriteEventLog("Cannot connect to SQL Server for Disk Data Reporting!", System.Diagnostics.EventLogEntryType.Error);
                        return;
                    }
                    ListDiskDataReport  DiskDataList = (ListDiskDataReport)DiskDataListO;
                    List <PolicyObject> Pol          = Policies.GetPolicyForComputerInternal(sql, DiskDataList.MachineID);

                    Dictionary <string, Int64> AlreadyReported = new Dictionary <string, long>();
                    foreach (PolicyObject PolO in Pol)
                    {
                        if (PolO.Type != PolicyIDs.ReportingPolicy)
                        {
                            continue;
                        }
                        ReportingPolicyElement RepElementRoot = JsonConvert.DeserializeObject <ReportingPolicyElement>(Policies.GetPolicy(sql, PolO.ID).Data);
                        if (RepElementRoot.Type != ReportingPolicyType.Disk)
                        {
                            continue;
                        }

                        foreach (string Element in RepElementRoot.ReportingElements)
                        {
                            ReportingPolicyElementDisk diskrep = JsonConvert.DeserializeObject <ReportingPolicyElementDisk>(Element);
                            if (diskrep.DriveLetter == null)
                            {
                                continue;
                            }
                            if (diskrep.DriveLetter.Length != 1)
                            {
                                continue;
                            }

                            foreach (DiskDataReport DD in DiskDataList.Items)
                            {
                                string Drive = diskrep.DriveLetter;

                                if (diskrep.DriveLetter == "$")
                                {
                                    ComputerData d = Computers.GetComputerDetail(sql, DiskDataList.MachineID);
                                    if (d != null)
                                    {
                                        if (string.IsNullOrWhiteSpace(d.SystemRoot) == false)
                                        {
                                            Drive = d.SystemRoot.Substring(0, 1);
                                        }
                                    }
                                }

                                if (string.IsNullOrWhiteSpace(DD.DriveLetter) == true)
                                {
                                    continue;
                                }
                                if (DD.DriveLetter.ToLower().Substring(0, 1) != Drive.ToLower())
                                {
                                    continue;
                                }

                                Int64 SZLimit;

                                if (diskrep.Method == 1)
                                {
                                    SZLimit = (Int64)((100m / (decimal)DD.Capacity) * (decimal)diskrep.MinimumSize);
                                }
                                else
                                {
                                    SZLimit = diskrep.MinimumSize;
                                }

                                if (DD.FreeSpace < SZLimit)
                                {
                                    bool ReportToAdmin   = RepElementRoot.ReportToAdmin.Value;
                                    bool ReportToClient  = RepElementRoot.ReportToClient.Value;
                                    bool UrgentForAdmin  = RepElementRoot.UrgentForAdmin.Value;
                                    bool UrgentForClient = RepElementRoot.UrgentForClient.Value;

                                    if (AlreadyReported.ContainsKey(DD.DriveLetter) == true)
                                    {
                                        if ((AlreadyReported[DD.DriveLetter] & (Int64)ReportingFlags.ReportToAdmin) != 0)
                                        {
                                            ReportToAdmin = false;
                                        }
                                        if ((AlreadyReported[DD.DriveLetter] & (Int64)ReportingFlags.ReportToClient) != 0)
                                        {
                                            ReportToClient = false;
                                        }
                                        if ((AlreadyReported[DD.DriveLetter] & (Int64)ReportingFlags.UrgentForAdmin) != 0)
                                        {
                                            UrgentForAdmin = false;
                                        }
                                        if ((AlreadyReported[DD.DriveLetter] & (Int64)ReportingFlags.UrgentForClient) != 0)
                                        {
                                            UrgentForClient = false;
                                        }
                                    }

                                    if (ReportToAdmin == false && ReportToClient == false && UrgentForAdmin == false && UrgentForClient == false)
                                    {
                                        continue;
                                    }
                                    ReportingFlags Flags = (ReportToAdmin == true ? ReportingFlags.ReportToAdmin : 0) |
                                                           (ReportToClient == true ? ReportingFlags.ReportToClient : 0) |
                                                           (UrgentForAdmin == true ? ReportingFlags.UrgentForAdmin : 0) |
                                                           (UrgentForClient == true ? ReportingFlags.UrgentForClient : 0);
                                    ReportingProcessor.ReportDiskData(sql, DiskDataList.MachineID, DD.DriveLetter, SZLimit, DD.FreeSpace, DD.Capacity, Flags);
                                    if (AlreadyReported.ContainsKey(DD.DriveLetter) == true)
                                    {
                                        AlreadyReported[DD.DriveLetter] |= (Int64)Flags;
                                    }
                                    else
                                    {
                                        AlreadyReported.Add(DD.DriveLetter, (Int64)Flags);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ee)
            {
                FoxEventLog.WriteEventLog("SEH in Disk Data Reporting " + ee.ToString(), System.Diagnostics.EventLogEntryType.Error);
            }
        }