public static string GetProfileDir(SecurityIdentifier sid) { //"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 == sid.ToString()) { using(RegistryKey subKey = Registry.LocalMachine.OpenSubKey(string.Format("{0}\\{1}", ROOT_PROFILE_KEY, keyName))) { return (string) subKey.GetValue("ProfileImagePath", null, RegistryValueOptions.None); } } } throw new KeyNotFoundException(string.Format("Unable to find value for: {0}", sid)); } else { throw new KeyNotFoundException(string.Format("Unable to open registry key")); } } }
/// <summary> /// Creates user credentials /// </summary> /// <param name="username"></param> public CertificateUserCredential(string username) { #if SQLCLR SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null); UserID = sid.ToString(); #else UserID = UserInfo.UserNameToSID(username); #endif }
/// <summary> /// Creates user credentials /// </summary> /// <param name="username"></param> /// <param name="userToken"></param> public IntegratedSecurityUserCredential(string username, Guid userToken) { Username = username; #if SQLCLR SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null); UserID = sid.ToString(); #else UserID = UserInfo.UserNameToSID(username); #endif UserToken = userToken; }
private Paragraph PropParagraph(string name, System.Collections.ICollection props) { Paragraph p = new Paragraph(); bool appendSeparator = false; if (props != null) { foreach (dynamic value in props.Cast <object>().OrderBy(x => x.ToString())) { if (appendSeparator) { p.Inlines.Add("\r\n"); } else { appendSeparator = true; } string valueString = ((Object)value).ToString(); if (name == "userAccountControl:") { p.Inlines.Add(new Run(GetUserAccountControl(value))); } else if (valueString == "System.__ComObject") { try { // Try an ADSI Large Integer Object o = value; Object low = o.GetType().InvokeMember("LowPart", System.Reflection.BindingFlags.GetProperty, null, o, null); Object high = o.GetType().InvokeMember("HighPart", System.Reflection.BindingFlags.GetProperty, null, o, null); //long dateValue = (value.HighPart * &H100000000) + value.LowPart; long dateValue = ((long)((int)high) << 32) + (long)((int)low); DateTime dt = DateTime.FromFileTime(dateValue); if (dt.ToString("dd-MMM-yyyy HH:mm") != "01-Jan-1601 11:00") { if (dt.Year == 1601) { p.Inlines.Add(dt.ToString("HH:mm")); } else { p.Inlines.Add(dt.ToString("dd-MMM-yyyy HH:mm")); } } } catch { p.Inlines.Add(valueString); } } else if (valueString == "System.Byte[]") { byte[] bytes = value as byte[]; if (bytes.Length == 16) { Guid guid = new Guid(bytes); p.Inlines.Add(guid.ToString("B")); } else if (bytes.Length == 28) { try { System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(bytes, 0); p.Inlines.Add(sid.ToString()); } catch { p.Inlines.Add(valueString); } } else { System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes); try { BitmapImage photoBitmap = new BitmapImage(); photoBitmap.BeginInit(); photoBitmap.StreamSource = ms; photoBitmap.EndInit(); Image img = new Image(); img.Source = photoBitmap; img.Stretch = Stretch.None; p.Inlines.Add(img); } catch { p.Inlines.Add(valueString); } } } else { if (valueString.StartsWith("CN=") || valueString.ToLower().StartsWith("http://")) { //string display = Regex.Match(valueString + ",", "CN=(.*?),").Groups[1].Captures[0].Value; //Hyperlink h = new Hyperlink(new Run(display)); Hyperlink h = new Hyperlink(new Run(valueString)); h.NavigateUri = new Uri(valueString, valueString.ToLower().StartsWith("http://") ? UriKind.Absolute : UriKind.Relative); h.Click += new RoutedEventHandler(HyperlinkClicked); //p.TextIndent = -20; //p.Margin = new Thickness(20, p.Margin.Top, p.Margin.Right, p.Margin.Bottom); p.Inlines.Add(h); } else { p.Inlines.Add(new Run(valueString)); } } } } return(p); }
public static string GetobjectSid(SearchResultAttributeCollection attributes) { object[] obj = null; try { obj = attributes["objectSid"].GetValues(Type.GetType("System.Byte[]")); } catch { //unable to get objectSid attribute, value unset return null; } if (obj.Length > 1) { throw new Exception("objectSid has more than one entry."); } SecurityIdentifier objectSid = new SecurityIdentifier((byte[])obj[0], 0); return objectSid.ToString(); }
static void Main(string[] args) { // domainSid: WindowsIdentity.GetCurrent().User.AccountDomainSid); if (args.Length > 0) { if (args[0].StartsWith("-?") || args[0].StartsWith("-h") || args[0].StartsWith("-help") || args[0].StartsWith("/?") || args[0].StartsWith("/h") || args[0].StartsWith("/help")) { ShowHelp(); } else if (Enum.IsDefined(typeof(WellKnownSidType), args[0])) { try { WellKnownSidType sidType = (WellKnownSidType)Enum.Parse(typeof(WellKnownSidType), args[0], false); SecurityIdentifier sid = null; if (args[0].StartsWith("Account")) { sid = new SecurityIdentifier(sidType, WindowsIdentity.GetCurrent().User.AccountDomainSid); } else { sid = new SecurityIdentifier(sidType, null); } NTAccount NTUser = (NTAccount)sid.Translate(typeof(System.Security.Principal.NTAccount)); Console.WriteLine("[" + sidType.ToString() + "]"); Console.WriteLine("Name=" + NTUser.ToString()); Console.WriteLine("Shortname=" + NTUser.ToString().Substring(NTUser.ToString().IndexOf("\\")+1)); Console.WriteLine("SID=" + sid.ToString()); Console.WriteLine("IsAccountSid=" + sid.IsAccountSid().ToString().ToUpper()); } catch (Exception ex) { Console.WriteLine(ex.Message); } } else { if (args[0].StartsWith("S-")) { try { SecurityIdentifier sid = new SecurityIdentifier(args[0]); NTAccount NTUser = (NTAccount)sid.Translate(typeof(System.Security.Principal.NTAccount)); Console.WriteLine("[" + sid.ToString() + "]"); Console.WriteLine("Name=" + NTUser.ToString()); Console.WriteLine("Shortname=" + NTUser.ToString().Substring(NTUser.ToString().IndexOf("\\") + 1)); Console.WriteLine("SID=" + sid.ToString()); Console.WriteLine("IsAccountSid=" + sid.IsAccountSid().ToString().ToUpper()); } catch (Exception ex) { Console.WriteLine(ex.Message); } } else { try { NTAccount NTUser = new NTAccount(args[0]); SecurityIdentifier sid = (SecurityIdentifier)NTUser.Translate(typeof(SecurityIdentifier)); Console.WriteLine("[" + NTUser.ToString() + "]"); Console.WriteLine("Name=" + NTUser.ToString()); Console.WriteLine("Shortname=" + NTUser.ToString().Substring(NTUser.ToString().IndexOf("\\") + 1)); Console.WriteLine("SID=" + sid.ToString()); Console.WriteLine("IsAccountSid=" + sid.IsAccountSid().ToString().ToUpper()); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } } else { ShowHelp(); } }
// // HandleContextHashValue helper for hashtable structured query builder. // Constructs and returns UserID XPath portion as a string. // Handles both SIDs and domain account names. // Writes an error and returns an empty string if the SID or account names are not valid. // private string HandleContextHashValue(Object value) { SecurityIdentifier sidCandidate = null; try { sidCandidate = new SecurityIdentifier(value.ToString()); } catch (ArgumentException) { WriteDebug(string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("InvalidSIDFormat"), value)); } if (sidCandidate == null) { try { NTAccount acct = new NTAccount(value.ToString()); sidCandidate = (SecurityIdentifier)acct.Translate(typeof(SecurityIdentifier)); } catch (ArgumentException exc) { string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("InvalidContext"), value.ToString()); Exception outerExc = new Exception(msg, exc); WriteError(new ErrorRecord(outerExc, "InvalidContext", ErrorCategory.InvalidArgument, null)); return ""; } } return string.Format(CultureInfo.InvariantCulture, "(System/Security[@UserID='{0}'])", sidCandidate.ToString()); }
public Sid(SecurityIdentifier sid) { this.sid = sid; SecurityIdentifier = sid.ToString(); BinaryLength = sid.BinaryLength; }
/// <summary> /// Gets the names and IDs of all central access policies available on the machine. /// </summary> /// <remarks> /// Function 'LsaQueryCAPs' is not available in OneCoreUAP and NanoServer. /// </remarks> /// <param name="instance"> /// The PSObject argument is ignored. /// </param> /// <returns> /// The names and IDs of all central access policies available on the machine. /// </returns> public static string[] GetAllCentralAccessPolicies(PSObject instance) { IntPtr caps = IntPtr.Zero; try { // Retrieve all CAPs. uint capCount = 0; uint rs = NativeMethods.LsaQueryCAPs( null, 0, out caps, out capCount); if (rs != NativeMethods.STATUS_SUCCESS) { throw new Win32Exception((int)rs); } Dbg.Diagnostics.Assert(capCount < 0xFFFF, "Too many central access policies"); if (capCount == 0 || caps == IntPtr.Zero) { return null; } // Add CAP names and IDs to a string array. string[] policies = new string[capCount]; NativeMethods.CENTRAL_ACCESS_POLICY cap = new NativeMethods.CENTRAL_ACCESS_POLICY(); IntPtr capPtr = caps; for (uint capIdx = 0; capIdx < capCount; capIdx++) { // Retrieve CAP name. Dbg.Diagnostics.Assert(capPtr != IntPtr.Zero, "Invalid central access policies array"); cap = ClrFacade.PtrToStructure<NativeMethods.CENTRAL_ACCESS_POLICY>(capPtr); // LSA_UNICODE_STRING is composed of WCHARs, but its length is given in bytes. policies[capIdx] = "\"" + Marshal.PtrToStringUni( cap.Name.Buffer, cap.Name.Length / 2) + "\""; // Retrieve CAPID. IntPtr pCapId = cap.CAPID; Dbg.Diagnostics.Assert(pCapId != IntPtr.Zero, "Invalid central access policies array"); bool ret = NativeMethods.IsValidSid(pCapId); if (!ret) { throw new Win32Exception(Marshal.GetLastWin32Error()); } SecurityIdentifier sid = new SecurityIdentifier(pCapId); policies[capIdx] += " (" + sid.ToString() + ")"; capPtr += Marshal.SizeOf(cap); } return policies; } finally { uint rs = NativeMethods.LsaFreeMemory(caps); Dbg.Diagnostics.Assert(rs == NativeMethods.STATUS_SUCCESS, "LsaFreeMemory failed: " + rs.ToString(CultureInfo.CurrentCulture)); } }
/// <summary> /// Sets the ExchangeImpersonation soap header on the binding prior to a /// call /// </summary> /// <param name="sid">SID of user to "Act As"</param> /// public void SetExchangeImpersonation(SecurityIdentifier sid) { ExchangeImpersonationType header = new ExchangeImpersonationType(); header.ConnectingSID = new ConnectingSIDType(); header.ConnectingSID.SID = sid.ToString(); this.ExchangeImpersonation = header; }
public static string[] GetAllCentralAccessPolicies(PSObject instance) { unsafe { string[] strArrays; IntPtr zero = IntPtr.Zero; try { int num = 0; int num1 = NativeMethods.LsaQueryCAPs(null, 0, out zero, out num); if (num1 == 0) { if (num == 0 || zero == IntPtr.Zero) { strArrays = null; } else { string[] strArrays1 = new string[num]; IntPtr intPtr = zero; uint num2 = 0; while (num2 < num) { NativeMethods.CENTRAL_ACCESS_POLICY structure = (NativeMethods.CENTRAL_ACCESS_POLICY)Marshal.PtrToStructure(intPtr, typeof(NativeMethods.CENTRAL_ACCESS_POLICY)); strArrays1[num2] = string.Concat("\"", Marshal.PtrToStringUni(structure.Name.Buffer, structure.Name.Length / 2), "\""); IntPtr cAPID = structure.CAPID; bool flag = NativeMethods.IsValidSid(cAPID); if (flag) { SecurityIdentifier securityIdentifier = new SecurityIdentifier(cAPID); string[] strArrays2 = strArrays1; string[] strArrays3 = strArrays2; uint num3 = num2; IntPtr intPtr1 = (IntPtr)num3; strArrays2[num3] = string.Concat(strArrays3[intPtr1.ToInt32()], " (", securityIdentifier.ToString(), ")"); intPtr = intPtr + Marshal.SizeOf(structure); num2++; } else { throw new Win32Exception(Marshal.GetLastWin32Error()); } } strArrays = strArrays1; } } else { throw new Win32Exception(num1); } } finally { NativeMethods.LsaFreeMemory(zero); } return strArrays; } }
/// <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; }
internal void Attach(Guid programId, int attachTimeout, int detachPingInterval, out string hostName, out string uri, out int controllerThreadId, out bool isSynchronousAttach) { lock (this.syncRoot) { hostName = string.Empty; uri = string.Empty; controllerThreadId = 0; isSynchronousAttach = false; if (!this.isZombie) { if (this.isAttached) { this.Detach(); } this.isAttached = true; this.programId = programId; this.debugControllerThread = new DebugControllerThread(); this.instanceTable = new InstanceTable(this.debugControllerThread.ManagedThreadId); this.typeToGuid = new Dictionary<Type, Guid>(); this.xomlHashToGuid = new Dictionary<byte[], Guid>(new DigestComparer()); this.debugControllerThread.RunThread(this.instanceTable); IDictionary properties = new Hashtable(); properties["typeFilterLevel"] = "Full"; BinaryServerFormatterSinkProvider serverSinkProvider = new BinaryServerFormatterSinkProvider(properties, null); Hashtable hashtable = new Hashtable(); hashtable["name"] = string.Empty; hashtable["portName"] = this.programId.ToString(); IdentityReference reference = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null).Translate(typeof(NTAccount)); hashtable["authorizedGroup"] = reference.ToString(); this.channel = new IpcChannel(hashtable, null, serverSinkProvider); ChannelServices.RegisterChannel(this.channel, true); RemotingServices.Marshal(this, this.programId.ToString()); hostName = this.hostName; uri = this.channel.GetUrlsForUri(this.programId.ToString())[0]; controllerThreadId = this.debugControllerThread.ThreadId; isSynchronousAttach = !this.isServiceContainerStarting; this.attachTimeout = attachTimeout; this.attachTimer = new Timer(new TimerCallback(this.AttachTimerCallback), null, attachTimeout, detachPingInterval); } } }
/// <summary> /// Rename a local user. /// </summary> /// <param name="sid"> /// A <see cref="SecurityIdentifier"/> objects identifying /// the local user to be renamed. /// </param> /// <param name="newName"> /// A string containing the new name for the local user. /// </param> /// <exception cref="UserNotFoundException"> /// Thrown when the specified user cannot be found. /// </exception> internal void RenameLocalUser(SecurityIdentifier sid, string newName) { context = new Context(ContextOperation.Rename, ContextObjectType.User, sid.ToString(), sid); RenameUser(sid, newName); }
/// <summary> /// Find a user by SID and return a <see cref="SamRidEnumeration"/> object /// representing the user. /// </summary> /// <param name="sid">A <see cref="SecurityIdentifier"/> object identifying /// the user to search for.</param> /// <returns> /// A SamRidEnumeration object representing the user. /// </returns> /// <exception cref="UserNotFoundException"> /// Thrown when the specified user is not found. /// </exception> /// <remarks> /// This method saves some time and effort over the GetUser method /// because it does not have to open a user to populate a full LocalUser /// object. /// </remarks> private SamRidEnumeration GetUserSre(SecurityIdentifier sid) { foreach (var sre in EnumerateUsers()) if (RidToSid(sre.domainHandle, sre.RelativeId) == sid) return sre; throw new UserNotFoundException(sid.ToString(), sid); }
/// <summary> /// Enable or disable a Local User /// </summary> /// <param name="sid"> /// A <see cref="SecurityIdentifier"/> object identifying the user to enable or disable. /// </param> /// <param name="enable"> /// One of the <see cref="Enabling"/> enumeration values, indicating whether to /// enable or disable the user. /// </param> internal void EnableLocalUser(SecurityIdentifier sid, Enabling enable) { context = new Context(enable == Enabling.Enable ? ContextOperation.Enable : ContextOperation.Disable, ContextObjectType.User, sid.ToString(), sid); EnableUser(sid, enable); }
/// <summary> /// Retrieve a local group by SID /// </summary> /// <param name="sid"> /// A <see cref="SecurityIdentifier"/> object identifying the desired group. /// </param> /// <returns> /// A <see cref="LocalGroup"/> object containing information about /// the local group. /// </returns> /// <exception cref="GroupNotFoundException"> /// Thrown when the specified group cannot be found. /// </exception> internal LocalGroup GetLocalGroup(SecurityIdentifier sid) { context = new Context(ContextOperation.Get, ContextObjectType.Group, sid.ToString(), sid); foreach (var sre in EnumerateGroups()) if (RidToSid(sre.domainHandle, sre.RelativeId) == sid) return MakeLocalGroupObject(sre); // return a populated group throw new GroupNotFoundException(sid.ToString(), context.target); }
private string HandleContextHashValue(object value) { SecurityIdentifier identifier = null; try { identifier = new SecurityIdentifier(value.ToString()); } catch (ArgumentException) { base.WriteDebug(string.Format(CultureInfo.InvariantCulture, this._resourceMgr.GetString("InvalidSIDFormat"), new object[] { value })); } if (identifier == null) { try { NTAccount account = new NTAccount(value.ToString()); identifier = (SecurityIdentifier) account.Translate(typeof(SecurityIdentifier)); } catch (ArgumentException exception) { Exception exception2 = new Exception(string.Format(CultureInfo.InvariantCulture, this._resourceMgr.GetString("InvalidContext"), new object[] { value.ToString() }), exception); base.WriteError(new ErrorRecord(exception2, "InvalidContext", ErrorCategory.InvalidArgument, null)); return ""; } } return string.Format(CultureInfo.InvariantCulture, "(System/Security[@UserID='{0}'])", new object[] { identifier.ToString() }); }
/// <summary> /// Remove a local group. /// </summary> /// <param name="sid"> /// A <see cref="SecurityIdentifier"/> object identifying the /// local group to be removed. /// </param> /// <exception cref="GroupNotFoundException"> /// Thrown when the specified group cannot be found. /// </exception> internal void RemoveLocalGroup(SecurityIdentifier sid) { context = new Context(ContextOperation.Remove, ContextObjectType.Group, sid.ToString(), sid); RemoveGroup(sid); }
public Sid(byte[] binaryForm, int offset) { sid = new SecurityIdentifier(binaryForm, offset); BinaryLength = sid.BinaryLength; SecurityIdentifier = sid.ToString(); }
/// <summary> /// Retrieve members of a Local group. /// </summary> /// <param name="groupSid"> /// A <see cref="SecurityIdentifier"/> object identifying the group whose members /// are requested. /// </param> /// <returns> /// An IEnumerable of <see cref="LocalPrincipal"/> objects containing the group's /// members. /// </returns> internal IEnumerable<LocalPrincipal> GetLocalGroupMembers(SecurityIdentifier groupSid) { context = new Context(ContextOperation.GetMember, ContextObjectType.Group, groupSid.ToString(), groupSid); return GetGroupMembers(groupSid); }
private bool IsAdministrator(Principal p) { SecurityIdentifier adminSid = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null); PrincipalContext ctx = new PrincipalContext(ContextType.Machine); bool isMember = p.IsMemberOf(ctx, IdentityType.Sid, adminSid.ToString()); return isMember; }
/// <summary> /// Remove members from a local group. /// </summary> /// <param name="groupSid"> /// A <see cref="SecurityIdentifier"/> object identifying the group from /// which to remove members /// </param> /// <param name="member"> /// An Object of type <see cref="LocalPrincipal"/> identifying /// the member to be removed. /// </param> /// <returns> /// An Exception object indicating any errors encountered. /// </returns> /// <exception cref="GroupNotFoundException"> /// Thrown if the group could not be found. /// </exception> internal Exception RemoveLocalGroupMember(SecurityIdentifier groupSid, LocalPrincipal member) { context = new Context(ContextOperation.RemoveMember, ContextObjectType.Group, groupSid.ToString(), groupSid); return RemoveGroupMember(groupSid, member); }
private String ResolveAccountName(SecurityIdentifier SID) { try { return SID.Translate(typeof(NTAccount)).Value; } catch (Exception) { return SID.ToString(); } }
/// <summary> /// Retrieve a local user by SID /// </summary> /// <param name="sid"> /// A <see cref="SecurityIdentifier"/> object identifying the desired user. /// </param> /// <returns> /// A <see cref="LocalUser"/> object containing information about /// the local user. /// </returns> /// <exception cref="UserNotFoundException"> /// Thrown when the specified user cannot be found. /// </exception> internal LocalUser GetLocalUser(SecurityIdentifier sid) { context = new Context(ContextOperation.Get, ContextObjectType.User, sid.ToString(), sid); foreach (var sre in EnumerateUsers()) if (RidToSid(sre.domainHandle, sre.RelativeId) == sid) return MakeLocalUserObject(sre); // return a populated user throw new UserNotFoundException(sid.ToString(), sid); }
/// <summary> /// Remove members from a group specified by SID. /// </summary> /// <param name="groupSid"> /// A <see cref="SecurityIdentifier"/> object identifying the group /// from which the members will be removed. /// </param> private void ProcessSid(SecurityIdentifier groupSid) { foreach (var member in this.Member) { LocalPrincipal principal = MakePrincipal(groupSid.ToString(), member); if (null != principal) { var ex = sam.RemoveLocalGroupMember(groupSid, principal); if (null != ex) { WriteError(ex.MakeErrorRecord()); } } } }
/// <summary> /// Remove a local user. /// </summary> /// <param name="sid"> /// A <see cref="SecurityIdentifier"/> object identifying /// the local user to be removed. /// </param> /// <exception cref="UserNotFoundException"> /// Thrown when the specified user cannot be found. /// </exception> internal void RemoveLocalUser(SecurityIdentifier sid) { context = new Context(ContextOperation.Remove, ContextObjectType.User, sid.ToString(), sid); RemoveUser(sid); }
public static bool DeleteProfile(SecurityIdentifier sid) { return SafeNativeMethods.DeleteProfile(sid.ToString(), null, null); }
/// <summary> /// Called by a connection when it has received an intact and complete message in wire-format. /// Parses the supplied byte-array to generate a typed message for processing. /// On return from this routine the connection is free to overwrite the buffer contents. /// /// </summary> /// <param name="conn">Connection (think TCP to specific network agent) on which message arrived.</param> /// <param name="buff">Buffer encoding the message.</param> /// <param name="offset">Offset to start of message in the supplied buffer.</param> /// <param name="length">Length of message encoding in supplied buffer</param> public void ReceiveMessage(Connection conn, MessageTypes messageType, byte[] buff, int offset, int length) { switch (messageType) { case MessageTypes.MessageTypeRegister: { MessageRegister msgRegister = MessageRegister.CreateFromNetBytes(buff, offset); TenantId = msgRegister.TenantId; client.CallbackMessageRegister(conn, msgRegister.TenantId, msgRegister.AlertVec); MessageAck ack = new MessageAck(msgRegister.SeqNo, MessageTypes.MessageTypeRegisterAck, (uint)OktoResultCodes.OKTO_RESULT_SUCCESS); SendSynchronous(conn, ack.Serialize); conn.BeginReceive(); break; } case MessageTypes.MessageTypeIoFlowCreate: { MessageIoFlowCreate msgFlowc = MessageIoFlowCreate.CreateFromNetBytes(buff, offset); lock (LockLocal) { foreach (IoFlowMessageParams flowc in msgFlowc.ListParams) { Console.WriteLine("Agent MessageIoFlowCreate({0},{1})", flowc.FlowId, flowc.ParameterString); if (DictFlowCreateParams.ContainsKey(flowc.FlowId)) { throw new ArgumentOutOfRangeException(string.Format("Agent flowc dup FlowId {0}", flowc.FlowId)); } DictFlowCreateParams.Add(flowc.FlowId, flowc); } } MessageAck ack = new MessageAck(msgFlowc.SeqNo, MessageTypes.MessageTypeIoFlowCreateAck, (uint)OktoResultCodes.OKTO_RESULT_SUCCESS); SendSynchronous(conn, ack.Serialize); conn.BeginReceive(); break; } case MessageTypes.MessageTypeRapFsCreate: { MessageRapFsCreate msgRapc = MessageRapFsCreate.CreateFromNetBytes(buff, offset); lock (LockLocal) { foreach (MsgRapArg rapc in msgRapc.ListMsgRapArg) { Console.WriteLine("Agent MessageRapFsCreate({0},{1},{2})", rapc.FlowId, rapc.stringSid, rapc.ShareOrVolume); if (!DictFlowCreateParams.ContainsKey(rapc.FlowId)) { throw new ArgumentOutOfRangeException(string.Format("Agent rapc invalid FlowId {0}", rapc.FlowId)); } if (DictRapCreateParams.ContainsKey(rapc.FlowId)) { throw new ArgumentOutOfRangeException(string.Format("Agent rapc dup FlowId {0}", rapc.FlowId)); } if (!DictFlowCreateParams.ContainsKey(rapc.FlowId)) { throw new ArgumentOutOfRangeException(string.Format("Agent rapc unmatched FlowId {0}", rapc.FlowId)); } DictRapCreateParams.Add(rapc.FlowId, rapc); } } // // Params look reasonable and FlowCreate and RapCreate match up. // Now we can invite the client to create its IoFlows. // OktoResultCodes result = client.CallbackIoFlowCreate(DictFlowCreateParams, DictRapCreateParams); MessageAck ack = new MessageAck(msgRapc.SeqNo, MessageTypes.MessageTypeRapFsCreateAck, (uint)result); SendSynchronous(conn, ack.Serialize); conn.BeginReceive(); break; } case MessageTypes.MessageTypeStatsZero: { MessageStatsZero msgZero = MessageStatsZero.CreateFromNetBytes(buff, offset); OktoResultCodes result = client.CallbackMessageStatsZero(); MessageAck ack = new MessageAck(msgZero.SeqNo, MessageTypes.MessageTypeStatsZeroAck, (uint)result); SendSynchronous(conn, ack.Serialize); conn.BeginReceive(); break; } case MessageTypes.MessageTypeIoFlowUpdate: { MessageIoFlowUpdate msgFlowc = MessageIoFlowUpdate.CreateFromNetBytes(buff, offset); lock (LockLocal) { foreach (IoFlowMessageParams flowu in msgFlowc.ListParams) { if (!DictFlowCreateParams.ContainsKey(flowu.FlowId)) { throw new ArgumentOutOfRangeException(string.Format("Agent flowu invalid FlowId {0}", flowu.FlowId)); } } } OktoResultCodes result = client.CallbackMessageIoFlowUpdate(msgFlowc.ListParams); MessageAck ack = new MessageAck(msgFlowc.SeqNo, MessageTypes.MessageTypeIoFlowUpdateAck, (uint)result); SendSynchronous(conn, ack.Serialize); conn.BeginReceive(); break; } case MessageTypes.MessageTypeTenantDelete: { MessageTenantDelete msgTend = MessageTenantDelete.CreateFromNetBytes(buff, offset); OktoResultCodes result = client.CallbackMessageTenantDelete(); MessageAck ack = new MessageAck(msgTend.SeqNo, MessageTypes.MessageTypeTenantDeleteAck, (uint)result); SendSynchronous(conn, ack.Serialize); conn.BeginReceive(); break; } case MessageTypes.MessageTypeIoFlowStatsQuery: { MessageIoFlowStatsQuery msgStatsQ = MessageIoFlowStatsQuery.CreateFromNetBytes(buff, offset); List <IoFlowMessageParams> listStats = client.CallbackMessageIoFlowStatsQuery(); lock (LockLocal) { foreach (IoFlowMessageParams stats in listStats) { if (!DictFlowCreateParams.ContainsKey(stats.FlowId)) { throw new ArgumentOutOfRangeException(string.Format("Stats reply invalid FlowId {0}", stats.FlowId)); } } } MessageIoFlowStatsReply msgStatsReply = new MessageIoFlowStatsReply(msgStatsQ.SeqNo, listStats, TenantId); SendSynchronous(conn, msgStatsReply.Serialize); conn.BeginReceive(); break; } case MessageTypes.MessageTypeNameToStringSidBatchQuery: { MessageNameToStringSidBatchQuery msgSidBatchQuery = MessageNameToStringSidBatchQuery.CreateFromNetBytes(buff, offset); Dictionary <string, string> DictVmNameToSid = new Dictionary <string, string>(); System.Security.Principal.SecurityIdentifier sid = null; foreach (string vmName in msgSidBatchQuery.ListVmNames) { //XXXET: following two lines are for account names of type europe\ sid = VmSID.GetVMnameSid(vmName); if (sid == null) { try { NTAccount ntaccount = new NTAccount(vmName); sid = (SecurityIdentifier)ntaccount.Translate(typeof(SecurityIdentifier)); } catch (Exception e) { Debug.Assert(0 == 1, e.Message); } } Console.WriteLine("MessageTypeNameToStringSidBatchQuery: {0} sid {1}", vmName, sid.ToString()); DictVmNameToSid.Add(vmName, sid.ToString()); } MessageVmNameToStringSidBatchReply msgSidReply = new MessageVmNameToStringSidBatchReply(msgSidBatchQuery.SeqNo, (uint)OktoResultCodes.OKTO_RESULT_SUCCESS, DictVmNameToSid); SendSynchronous(conn, msgSidReply.Serialize); conn.BeginReceive(); break; } default: { string msg = string.Format("ReceiveMessage: unexpected message type {0}", messageType); throw new ApplicationException(msg); } } // switch }