示例#1
0
文件: User.cs 项目: abhai2k/pgina
        /// <summary>
        /// returns profiledir based on regkey
        /// </summary>
        /// <param name="sid"></param>
        /// <returns></returns>
        public static List <string> GetProfileDir(SecurityIdentifier sid)
        {
            List <string> ret = new List <string>();

            //"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\S-1-5-21-534125731-1308685933-1530606844-1000}"
            using (RegistryKey key = Registry.LocalMachine.OpenSubKey(ROOT_PROFILE_KEY))
            {
                if (key != null)
                {
                    foreach (string keyName in key.GetSubKeyNames())
                    {
                        if (keyName.Contains(sid.ToString())) //get the %SID% and %SID%.bak key
                        {
                            using (RegistryKey subKey = Registry.LocalMachine.OpenSubKey(string.Format("{0}\\{1}", ROOT_PROFILE_KEY, keyName)))
                            {
                                LibraryLogging.Info("ProfileList key found {0}", keyName);
                                ret.Add(subKey.GetValue("ProfileImagePath", "", RegistryValueOptions.None).ToString());
                            }
                        }
                    }
                }
                else
                {
                    LibraryLogging.Info("GetProfileDir key {0} not found", ROOT_PROFILE_KEY);
                }
            }

            return(ret);
        }
示例#2
0
        protected void HandlePipeConnection(BinaryReader reader, BinaryWriter writer, IDictionary <string, object> initialMessage)
        {
            try
            {
                // If we should announce with a specific message, do so
                if (initialMessage != null)
                {
                    WriteMessage(writer, initialMessage);
                }

                // So long as our Func<> returns true, we keep going.  When it returns false,
                //  it is done and its time to closeup and look for another client.
                while (StreamAction(reader, writer))
                {
                }
            }
            catch (IOException)
            {
                throw;
            }
            catch (Exception e)
            {
                LibraryLogging.Error("Error while using pipe connection: {0}", e);
            }
        }
示例#3
0
文件: User.cs 项目: abhai2k/pgina
        /// <summary>
        /// sets user profile quota
        /// </summary>
        /// <param name="where">ROOTKEY hklm or hku</param>
        /// <param name="name">SubKey name</param>
        /// <param name="quota">if 0 means the profile quota GPO it will be deleted</param>
        /// <returns>false on error</returns>
        public static Boolean SetQuota(Abstractions.WindowsApi.pInvokes.structenums.RegistryLocation where, string name, uint quota)
        {
            LibraryLogging.Info("set Quota for {0}", name);
            try
            {
                using (RegistryKey key = Abstractions.WindowsApi.pInvokes.GetRegistryLocation(where).CreateSubKey(name + @"\Software\Microsoft\Windows\CurrentVersion\Policies\System"))
                {
                    if (quota > 0)
                    {
                        key.SetValue("EnableProfileQuota", 1, RegistryValueKind.DWord);
                        //key.SetValue("ProfileQuotaMessage", "You have exceeded your profile storage space. Before you can log off, you need to move some items from your profile to network or local storage.", RegistryValueKind.String);
                        key.SetValue("MaxProfileSize", quota, RegistryValueKind.DWord);
                        key.SetValue("IncludeRegInProQuota", 1, RegistryValueKind.DWord);
                        key.SetValue("WarnUser", 1, RegistryValueKind.DWord);
                        key.SetValue("WarnUserTimeout", 5, RegistryValueKind.DWord);
                    }
                    else
                    {
                        key.DeleteValue("EnableProfileQuota", false);
                        key.DeleteValue("ProfileQuotaMessage", false);
                        key.DeleteValue("MaxProfileSize", false);
                        key.DeleteValue("IncludeRegInProQuota", false);
                        key.DeleteValue("WarnUser", false);
                        key.DeleteValue("WarnUserTimeout", false);
                    }
                }
            }
            catch (Exception ex)
            {
                LibraryLogging.Error("Can't set profile quota for {0} Error:{1}", name, ex.Message);
                return(false);
            }

            return(true);
        }
示例#4
0
        /// <summary>
        /// remove users who are unknown to the system from the directory acl
        /// </summary>
        /// <param name="dir"></param>
        /// <returns></returns>
        public static Boolean RemoveAccRuleFromUnknownUser(string dir)
        {
            DirectoryInfo     dInfo     = new DirectoryInfo(dir);
            DirectorySecurity dSecurity = dInfo.GetAccessControl();

            try
            {
                foreach (FileSystemAccessRule user in dSecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
                {
                    //LibraryLogging.Debug("directory ACE user: {0}", user.IdentityReference.Value);
                    if (user.IdentityReference.Value.StartsWith("S-1-5-21-"))
                    {
                        LibraryLogging.Debug("delete unknown directory ACE from {0} in {1}", user.IdentityReference.Value, dir);
                        dSecurity.RemoveAccessRule(user);
                    }
                }
            }
            catch (Exception ex)
            {
                LibraryLogging.Error("unable to RemoveAccRuleFromUnknownUser for {0} error {1}", dir, ex.Message);
                return(false);
            }

            return(true);
        }
示例#5
0
 private void DetachAbstractionsLibraryLogging()
 {
     LibraryLogging.RemoveListener(LibraryLogging.Level.Debug, m_abstractLogger.DebugFormat);
     LibraryLogging.RemoveListener(LibraryLogging.Level.Error, m_abstractLogger.ErrorFormat);
     LibraryLogging.RemoveListener(LibraryLogging.Level.Info, m_abstractLogger.InfoFormat);
     LibraryLogging.RemoveListener(LibraryLogging.Level.Warn, m_abstractLogger.WarnFormat);
 }
示例#6
0
 private void HookUpAbstractionsLibraryLogging()
 {
     LibraryLogging.AddListener(LibraryLogging.Level.Debug, m_abstractLogger.DebugFormat);
     LibraryLogging.AddListener(LibraryLogging.Level.Error, m_abstractLogger.ErrorFormat);
     LibraryLogging.AddListener(LibraryLogging.Level.Info, m_abstractLogger.InfoFormat);
     LibraryLogging.AddListener(LibraryLogging.Level.Warn, m_abstractLogger.WarnFormat);
 }
示例#7
0
        /// <summary>
        /// get UTC ntp time
        /// based on http://stackoverflow.com/questions/1193955/how-to-query-an-ntp-server-using-c
        /// </summary>
        /// <param name="FQDN">server address</param>
        /// <returns>DateTime, on error DateTime.MinValue</returns>
        public static DateTime GetNetworkTime(string[] FQDN)
        {
            DateTime RetVal = DateTime.MinValue;

            //time server
            for (uint x = 0; x < FQDN.Length; x++)
            {
                // NTP message size - 16 bytes of the digest (RFC 2030)
                Byte[] ntpData = new byte[48];

                //Setting the Leap Indicator, Version Number and Mode values
                ntpData[0] = 0x1B; //LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode)

                try
                {
                    IPAddress[] addresses = Dns.GetHostEntry(FQDN[x]).AddressList;

                    //The UDP port number assigned to NTP is 123
                    IPEndPoint ipEndPoint = new IPEndPoint(addresses[0], 123);
                    //NTP uses UDP
                    Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    socket.ReceiveTimeout = 3 * 1000;
                    socket.SendTimeout    = 3 * 1000;

                    socket.Connect(ipEndPoint);

                    socket.Send(ntpData);
                    socket.Receive(ntpData);
                    socket.Close();

                    //Offset to get to the "Transmit Timestamp" field (time at which the reply
                    //departed the server for the client, in 64-bit timestamp format."
                    const byte serverReplyTime = 40;

                    //Get the seconds part
                    UInt64 intPart = BitConverter.ToUInt32(ntpData, serverReplyTime);

                    //Get the seconds fraction
                    UInt64 fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4);

                    //Convert From big-endian to little-endian
                    intPart   = SwapEndianness(intPart);
                    fractPart = SwapEndianness(fractPart);

                    UInt64 milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);

                    //**UTC** time
                    RetVal = (new DateTime(1900, 1, 1)).AddMilliseconds((Int64)milliseconds);

                    break;
                }
                catch (Exception ex)
                {
                    LibraryLogging.Error("get ntp {0} error:{1}", FQDN[x], ex);
                }
            }

            return(RetVal);
        }
示例#8
0
        private void ServerThread()
        {
            PipeSecurity security = new PipeSecurity();

            using (WindowsIdentity myself = WindowsIdentity.GetCurrent())
            {
                try
                {
                    // Anyone can talk to us
                    LibraryLogging.Debug("Setting PipeAccess R/W for world: {0}", Abstractions.Windows.Security.GetWellknownSID(WellKnownSidType.WorldSid));
                    security.AddAccessRule(new PipeAccessRule(Abstractions.Windows.Security.GetWellknownSID(WellKnownSidType.WorldSid), PipeAccessRights.ReadWrite, AccessControlType.Allow));

                    // But only we have full control (including the 'create' right, which allows us to be the server side of this equation)
                    LibraryLogging.Debug("Setting PipeAccess FullControl for myself: {0}", WindowsIdentity.GetCurrent().Name);
                    security.AddAccessRule(new PipeAccessRule(WindowsIdentity.GetCurrent().Owner, PipeAccessRights.FullControl, AccessControlType.Allow));
                }
                catch (Exception e)
                {
                    LibraryLogging.Error("Unable to set all pipe access rules, the security of the pGina service pipe is in an unknown state!: {0}", e);
                }
            }

            while (Running)
            {
                try
                {
                    using (NamedPipeServerStream pipeServer = new NamedPipeServerStream(Name, PipeDirection.InOut, MaxClients,
                                                                                        PipeTransmissionMode.Byte, PipeOptions.WriteThrough, 0, 0, security, HandleInheritability.None))
                    {
                        try
                        {
                            pipeServer.WaitForConnection();
                        }
                        catch (Exception e)
                        {
                            LibraryLogging.Error("Error in server connection handler: {0}", e);
                            continue;
                        }

                        // Handle this connection, note that we always expect client to initiate the
                        //  flow of messages, so we do not include an initial message
                        HandlePipeConnection(pipeServer, null);
                    }
                }
                catch (Exception e)
                {
                    LibraryLogging.Error("Error while trying to open pipe server: {0}", e);
                    Thread.Sleep(500);
                }
            }
        }
示例#9
0
        /// <summary>
        /// apply registry security settings to user profiles
        /// </summary>
        /// <param name="where"></param>
        /// <param name="keyname"></param>
        /// <param name="username"></param>
        /// <returns></returns>
        public static Boolean RegSec(pInvokes.structenums.RegistryLocation where, string keyname, string username)
        {
            try
            {
                IdentityReference  UserIRef = new NTAccount(String.Format("{0}\\{1}", Environment.MachineName, username));
                SecurityIdentifier UserSid  = (SecurityIdentifier)UserIRef.Translate(typeof(SecurityIdentifier));

                using (RegistryKey key = pInvokes.GetRegistryLocation(where).OpenSubKey(keyname, true))
                {
                    RegistrySecurity keySecurity = key.GetAccessControl(AccessControlSections.Access);
                    string           SDDL        = keySecurity.GetSecurityDescriptorSddlForm(AccessControlSections.All);
                    //LibraryLogging.Info(SDDL);

                    foreach (RegistryAccessRule user in keySecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
                    {
                        //LibraryLogging.Info("registry ACE user: {0} {1} {2}", key.Name, user.InheritanceFlags.ToString(), user.IdentityReference.Value);
                        if (user.IdentityReference.Value.StartsWith("S-1-5-21-") && !user.IdentityReference.Value.Equals(UserIRef.Value))
                        {
                            //LibraryLogging.Info("mod registry ACE:{0} from unknown user:{1} to {2} {3} {4}", key.Name, user.IdentityReference.Value, username, user.RegistryRights.ToString(), user.AccessControlType.ToString());

                            SDDL = SDDL.Replace(user.IdentityReference.Value, UserSid.Value);
                            //LibraryLogging.Info(SDDL);
                            keySecurity.SetSecurityDescriptorSddlForm(SDDL);
                            key.SetAccessControl(keySecurity);

                            break;
                        }
                    }
                    foreach (string subkey in key.GetSubKeyNames())
                    {
                        if (!RegSec(where, keyname + "\\" + subkey, username))
                        {
                            return(false);
                        }
                    }
                }
            }
            catch (SystemException ex)
            {
                LibraryLogging.Warn("RegSec:{0} Warning {1}", keyname, ex.Message);
            }
            catch (Exception ex)
            {
                LibraryLogging.Error("RegSec:{0} Error:{1}", keyname, ex.Message);
                return(false);
            }

            return(true);
        }
示例#10
0
        public static Boolean SetDirOwner(string dir, IdentityReference Account)
        {
            DirectoryInfo     dInfo     = new DirectoryInfo(dir);
            DirectorySecurity dSecurity = dInfo.GetAccessControl();

            try
            {
                dSecurity.SetOwner(Account);
                dInfo.SetAccessControl(dSecurity);
            }
            catch (Exception ex)
            {
                LibraryLogging.Error("SetDirOwner unable to SetOwner for {0} error {1}", dir, ex.Message);
                return(false);
            }

            return(true);
        }
示例#11
0
        public static Boolean SetDirOwner(string dir, string Account)
        {
            DirectoryInfo     dInfo     = new DirectoryInfo(dir);
            DirectorySecurity dSecurity = dInfo.GetAccessControl();
            IdentityReference User      = new NTAccount(String.Format("{0}\\{1}", Environment.MachineName, Account));

            try
            {
                dSecurity.SetOwner(User);
                dInfo.SetAccessControl(dSecurity);
            }
            catch (Exception ex)
            {
                LibraryLogging.Error("SetDirOwner unable to SetOwner for {0} error {1}", dir, ex.Message);
                return(false);
            }

            return(true);
        }
示例#12
0
        public void Start(Func <BinaryReader, BinaryWriter, bool> action, IDictionary <string, object> initialMessage, int timeout)
        {
            StreamAction = action;

            using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", Name, PipeDirection.InOut,
                                                                                PipeOptions.WriteThrough, TokenImpersonationLevel.None, HandleInheritability.None))
            {
                for (int x = 1; x <= 5; x++)
                {
                    try
                    {
                        pipeClient.Connect(timeout);
                    }
                    catch (Exception e)
                    {
                        if (x == 5)
                        {
                            LibraryLogging.Error("Error connecting PipeClient: {0}", e);
                            return;
                        }
                        Thread.Sleep(100);
                    }
                }

                // Write the initial message to get the pumps running,
                //  error handling to prevent a pipe error exception
                try
                {
                    using (BinaryReader reader = new BinaryReader(pipeClient, Encoding.Unicode /*, true*/))
                    {
                        using (BinaryWriter writer = new BinaryWriter(pipeClient, Encoding.Unicode /*, true*/))
                        {
                            HandlePipeConnection(reader, writer, null);
                        }
                    }
                }
                catch (IOException)
                {
                    LibraryLogging.Error("Error broken pipe connection");
                    Start(action, initialMessage, timeout);
                }
            }
        }
示例#13
0
文件: Pipe.cs 项目: zhiqian1027/pgina
        protected void HandlePipeConnection(PipeStream pipeStream, IDictionary <string, object> initialMessage)
        {
            // You think we'd scope these with using() right? They are IDisposable
            //  after all... but nope, the implementation of these is such that
            //  disposing of them also disposes the underlying stream.  Leaving us
            //  with a double (or triple if we close the pipeServer stream ourselves)
            //  close.  Yay.  Instead we abandoned these to the GC knowing that they
            //  are only wrappers anyway and have/use little/no resources of their own.
            BinaryReader reader = new BinaryReader(pipeStream, Encoding.Unicode);
            BinaryWriter writer = new BinaryWriter(pipeStream, Encoding.Unicode);

            try
            {
                // If we should announce with a specific message, do so
                if (initialMessage != null)
                {
                    WriteMessage(writer, initialMessage);
                }

                // So long as our Func<> returns true, we keep going.  When it returns false,
                //  it is done and its time to closeup and look for another client.
                while (StreamAction(reader, writer))
                {
                }
            }
            catch (Exception e)
            {
                LibraryLogging.Error("Error while using pipe connection: {0}", e);
            }

            try
            {
                pipeStream.Flush();
                pipeStream.WaitForPipeDrain();
                pipeStream.Close();
            }
            catch (Exception e)
            {
                LibraryLogging.Error("Error while flushing/closing pipe connection: {0}", e);
            }
        }
示例#14
0
文件: User.cs 项目: abhai2k/pgina
        /// <summary>
        /// return true if profile is temp. uses ProfileList State regkey
        /// </summary>
        /// <param name="sid"></param>
        /// <returns></returns>
        public static bool?IsProfileTemp(string sid)
        {
            try
            {
                using (RegistryKey key = Registry.LocalMachine.OpenSubKey(string.Format("{0}\\{1}", ROOT_PROFILE_KEY, sid)))
                {
                    if (key != null)
                    {
                        object        type  = key.GetValue("State");
                        Profile_State value = 0;
                        switch (key.GetValueKind("State"))
                        {
                        case RegistryValueKind.DWord:
                            value = (Profile_State)type;
                            break;

                        case RegistryValueKind.QWord:
                            value = (Profile_State)type;
                            break;
                        }

                        if (value.HasFlag(Profile_State.Temporary_profile_loaded))
                        {
                            return(true);
                        }
                    }
                    else
                    {
                        LibraryLogging.Info("IsProfileTemp key {0}\\{1} not found", ROOT_PROFILE_KEY, sid);
                        return(null);
                    }
                }
            }
            catch (Exception ex)
            {
                LibraryLogging.Info("IsProfileTemp exception:{0}", ex.Message);
                return(null);
            }

            return(false);
        }
示例#15
0
        public static Boolean SetDirectorySecurity(string dir, string[] Account, FileSystemRights Rights, AccessControlType ControlType, InheritanceFlags Inherit, PropagationFlags Propagation)
        {
            DirectoryInfo     dInfo     = new DirectoryInfo(dir);
            DirectorySecurity dSecurity = dInfo.GetAccessControl();

            try
            {
                foreach (string account in Account)
                {
                    dSecurity.AddAccessRule(new FileSystemAccessRule(account, Rights, Inherit, Propagation, ControlType));
                }
                dInfo.SetAccessControl(dSecurity);
            }
            catch (Exception ex)
            {
                LibraryLogging.Error("unable to SetDirectorySecurity for {0} error {1}", dir, ex.Message);
                return(false);
            }

            return(true);
        }
示例#16
0
文件: User.cs 项目: abhai2k/pgina
        /// <summary>
        /// query for already set user profile quota
        /// </summary>
        /// <param name="where"></param>
        /// <param name="name"></param>
        /// <returns>true on already set</returns>
        public static Boolean QueryQuota(Abstractions.WindowsApi.pInvokes.structenums.RegistryLocation where, string name)
        {
            LibraryLogging.Info("query Quota for {0}", name);
            try
            {
                using (RegistryKey key = Abstractions.WindowsApi.pInvokes.GetRegistryLocation(where).OpenSubKey(name + @"\Software\Microsoft\Windows\CurrentVersion\Policies\System"))
                {
                    if (key.GetValue("EnableProfileQuota") == null)
                    {
                        return(false);
                    }
                }
            }
            catch (Exception ex)
            {
                LibraryLogging.Error("Can't get profile quota for {0} Error:{1}", name, ex.Message);
                return(false);
            }

            return(true);
        }
示例#17
0
        public void Start(Func <BinaryReader, BinaryWriter, bool> action, IDictionary <string, object> initialMessage, int timeout)
        {
            StreamAction = action;

            using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", Name, PipeDirection.InOut,
                                                                                PipeOptions.WriteThrough, TokenImpersonationLevel.None, HandleInheritability.None))
            {
                try
                {
                    pipeClient.Connect(timeout);
                }
                catch (Exception e)
                {
                    LibraryLogging.Error("Error connecting PipeClient: {0}", e);
                    return;
                }

                // Write the initial message to get the pumps running,
                //  not in a try/catch so that errors bubble up
                HandlePipeConnection(pipeClient, initialMessage);
            }
        }
示例#18
0
        public static Boolean ReplaceDirectorySecurity(string dir, IdentityReference[] Account, FileSystemRights Rights, AccessControlType ControlType, InheritanceFlags Inherit, PropagationFlags Propagation)
        {
            DirectoryInfo     dInfo     = new DirectoryInfo(dir);
            DirectorySecurity dSecurity = new DirectorySecurity();

            try
            {
                dSecurity.SetAccessRuleProtection(true, false);
                foreach (IdentityReference account in Account)
                {
                    dSecurity.ResetAccessRule(new FileSystemAccessRule(account, Rights, Inherit, Propagation, ControlType));
                }
                dInfo.SetAccessControl(dSecurity);
            }
            catch (Exception ex)
            {
                LibraryLogging.Error("unable to ReplaceDirectorySecurity for {0} error {1}", dir, ex.Message);
                return(false);
            }

            return(true);
        }
示例#19
0
        public static Boolean ReplaceFileSecurity(string File, string[] Account, FileSystemRights Rights, AccessControlType ControlType, InheritanceFlags Inherit, PropagationFlags Propagation)
        {
            FileInfo     fInfo     = new FileInfo(File);
            FileSecurity fSecurity = fInfo.GetAccessControl();

            try
            {
                fSecurity.SetAccessRuleProtection(true, false);
                foreach (string account in Account)
                {
                    fSecurity.ResetAccessRule(new FileSystemAccessRule(account, Rights, Inherit, Propagation, ControlType));
                }
                fInfo.SetAccessControl(fSecurity);
            }
            catch (Exception ex)
            {
                LibraryLogging.Error("unable to ReplaceFileSecurity for {0} error {1}", File, ex.Message);
                return(false);
            }

            return(true);
        }
示例#20
0
        /// <summary>
        /// apply recursive attribute to directories and files
        /// </summary>
        /// <param name="dir"></param>
        /// <param name="attrib"></param>
        /// <returns></returns>
        public static Boolean SetRecDirAttrib(DirectoryInfo dir, FileAttributes attrib)
        {
            try
            {
                foreach (DirectoryInfo subDirPath in dir.GetDirectories())
                {
                    subDirPath.Attributes = attrib;
                    SetRecDirAttrib(subDirPath, attrib);
                }
                foreach (FileInfo filePath in dir.GetFiles())
                {
                    filePath.Attributes = attrib;
                }
            }
            catch (Exception ex)
            {
                LibraryLogging.Error("Cant't set attrib {0} on {1} Error:{2}", attrib, dir, ex.Message);
                return(false);
            }

            return(true);
        }
示例#21
0
        /// <summary>
        /// does send a mail including the last 60 system-Event and application-Event lines
        /// plus the last 175 pgina logfile lines
        /// </summary>
        /// <param name="mailAddress"></param>
        /// <param name="smtpAddress"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        /// <param name="ssl"></param>
        /// <returns></returns>
        public static Boolean email(string[] mailAddress, string[] smtpAddress, string username, string password, string subject, string body, bool ssl)
        {
            Boolean ret = false;

            #region input checks
            if (mailAddress.Length == 0)
            {
                LibraryLogging.Error("can't send email: mailAddress.Length == 0");
                return(false);
            }
            else
            {
                bool atleastonemail = false;
                foreach (string str in mailAddress)
                {
                    if (!String.IsNullOrEmpty(str))
                    {
                        atleastonemail = true;
                        break;
                    }
                }
                if (!atleastonemail)
                {
                    LibraryLogging.Error("can't send email: mailAddress array is empty");
                    return(false);
                }
            }
            if (smtpAddress.Length == 0)
            {
                LibraryLogging.Error("can't send email: smtpAddress.Length == 0");
                return(false);
            }
            else
            {
                bool atleastoneserver = false;
                foreach (string str in smtpAddress)
                {
                    if (!String.IsNullOrEmpty(str))
                    {
                        atleastoneserver = true;
                        break;
                    }
                }
                if (!atleastoneserver)
                {
                    LibraryLogging.Error("can't send email: smtpAddress array is empty");
                    return(false);
                }
            }
            if (String.IsNullOrEmpty(subject))
            {
                LibraryLogging.Error("can't send email: subject is empty");
            }
            #endregion

            try
            {
                using (EventLog systemLog = new EventLog("System"))
                {
                    body += "\n\n====================Eventlog System====================\n";
                    for (int x = systemLog.Entries.Count - 60; x < systemLog.Entries.Count; x++)
                    {
                        body += String.Format("{0:yyyy-MM-dd HH:mm:ss} {1} {2} {3}\n", systemLog.Entries[x].TimeGenerated, systemLog.Entries[x].EntryType, (UInt16)systemLog.Entries[x].InstanceId, systemLog.Entries[x].Message);
                    }
                }
                using (EventLog application = new EventLog("Application"))
                {
                    body += "\n\n====================Eventlog Application===============\n";
                    for (int x = application.Entries.Count - 60; x < application.Entries.Count; x++)
                    {
                        body += String.Format("{0:yyyy-MM-dd HH:mm:ss} {1} {2} {3}\n", application.Entries[x].TimeGenerated, application.Entries[x].EntryType, (UInt16)application.Entries[x].InstanceId, application.Entries[x].Message);
                    }
                }
            }
            catch { }

            ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(true); };

            for (uint x = 0; x < smtpAddress.Length; x++)
            {
                string smtp = smtpAddress[x].Split(new char[] { ':' }).First();
                int    port = 465;
                if (String.Compare(smtp, smtpAddress[x].Split(new char[] { ':' }).Last()) != 0)
                {
                    try
                    {
                        port = Convert.ToInt32(smtpAddress[x].Split(new char[] { ':' }).Last());
                    }
                    catch (Exception ex)
                    {
                        LibraryLogging.Warn("unable to retrieve smtp port from {0} Error:{1}", smtpAddress[x], ex.Message);
                        continue;
                    }
                }
                using (SmtpClient client = new SmtpClient(smtp, port))
                {
                    client.EnableSsl = ssl;
                    client.Timeout   = Convert.ToInt32(new TimeSpan(0, 0, 30).TotalMilliseconds);
                    if (!String.IsNullOrEmpty(username) && !String.IsNullOrEmpty(password))
                    {
                        client.Credentials = new NetworkCredential(username, password);
                    }

                    for (uint y = 0; y < mailAddress.Length; y++)
                    {
                        if (mailAddress[y] == null)
                        {
                            continue;
                        }
                        try
                        {
                            // get the logfile
                            string logfile = null;
                            logfile = LogManager.GetRepository().GetAppenders().OfType <FileAppender>().Where(fa => fa.Name == "bigfile").Single().File;
                            if (!String.IsNullOrEmpty(logfile))
                            {
                                using (StreamReader log = new StreamReader(logfile, true))
                                {
                                    // read the last 50kbytes of the log
                                    if (log.BaseStream.Length > 50 * 1024) //50kbytes
                                    {
                                        log.BaseStream.Seek(50 * 1024 * -1, SeekOrigin.End);
                                    }

                                    string[] lastlines  = log.ReadToEnd().Split('\n');
                                    int      line_count = 0;
                                    if (lastlines.Length > 175)
                                    {
                                        line_count = lastlines.Length - 176;
                                    }
                                    body += "\n\n====================Pgina log==========================\n";
                                    for (; line_count < lastlines.Length; line_count++)
                                    {
                                        body += lastlines[line_count] + '\n';
                                    }
                                }
                            }

                            using (MailMessage message = new MailMessage(mailAddress[y], mailAddress[y], subject, body))
                            {
                                client.Send(message);
                            }
                            mailAddress[y] = null;
                        }
                        catch (Exception ex)
                        {
                            LibraryLogging.Warn("Failed to send message \"{0}\" to:{1} port:{2} Error:{3}", subject, smtp, port, ex.Message);
                        }
                    }
                }

                if (mailAddress.All(k => string.IsNullOrEmpty(k)))
                {
                    ret = true;
                    break;
                }
            }

            return(ret);
        }
示例#22
0
        private void ServerThread()
        {
            PipeSecurity security = new PipeSecurity();

            using (WindowsIdentity myself = WindowsIdentity.GetCurrent())
            {
                try
                {
                    // Anyone can talk to us
                    LibraryLogging.Debug("Setting PipeAccess R/W for world: {0}", Abstractions.Windows.Security.GetWellknownSID(WellKnownSidType.WorldSid));
                    security.AddAccessRule(new PipeAccessRule(Abstractions.Windows.Security.GetWellknownSID(WellKnownSidType.WorldSid), PipeAccessRights.ReadWrite, AccessControlType.Allow));

                    // But only we have full control (including the 'create' right, which allows us to be the server side of this equation)
                    LibraryLogging.Debug("Setting PipeAccess FullControl for myself: {0}", WindowsIdentity.GetCurrent().Name);
                    security.AddAccessRule(new PipeAccessRule(WindowsIdentity.GetCurrent().Owner, PipeAccessRights.FullControl, AccessControlType.Allow));
                }
                catch (Exception e)
                {
                    LibraryLogging.Error("Unable to set all pipe access rules, the security of the pGina service pipe is in an unknown state!: {0}", e);
                }
            }

            while (Running)
            {
                try
                {
                    using (NamedPipeServerStream pipeServer = new NamedPipeServerStream(Name, PipeDirection.InOut, MaxClients,
                                                                                        PipeTransmissionMode.Byte, PipeOptions.WriteThrough, 0, 0, security, HandleInheritability.None))
                    {
                        try
                        {
                            pipeServer.WaitForConnection();
                        }
                        catch (Exception e)
                        {
                            LibraryLogging.Error("Error in server connection handler: {0}", e);
                            continue;
                        }

                        // Handle this connection, note that we always expect client to initiate the
                        //  flow of messages, so we do not include an initial message
                        using (BinaryReader reader = new BinaryReader(pipeServer, Encoding.Unicode /*, true*/))
                        {
                            using (BinaryWriter writer = new BinaryWriter(pipeServer, Encoding.Unicode /*, true*/))
                            {
                                HandlePipeConnection(reader, writer, null);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    LibraryLogging.Error("Error while trying to open pipe server: {0}", e);
                    if (Running)
                    {
                        dynamic s_settings = new Abstractions.Settings.DynamicSettings();
                        Abstractions.Windows.Networking.sendMail(s_settings.GetSettings(new string[] { "notify_pass" }), "", "", String.Format("pGina: PipeServer error {0}", Environment.MachineName), e.ToString());
                    }
                }
            }
        }