/// <summary>
 /// Constructor
 /// </summary>
 internal SmbServerContext()
 {
     this.shareList = new Dictionary<string, SmbServerShare>();
     this.globalCapabilities = (Capabilities)0x00;
     this.isUpdateContext = true;
     this.connectionList = new Collection<SmbServerConnection>();
 }
예제 #2
0
 public StoreApp(IDriverContext context, Capabilities capabilities, IUtils utils)
 {
     // TODO verify capabilities
     this.context = context;
     this.capabilities = capabilities;
     this.utils = utils;
 }
예제 #3
0
 protected GetFeatureInfo(Capabilities.WmsServiceDescription description, 
     GetFeatureInfoParams @params) : base(description)
 {
     if (@params == null) 
         throw new ArgumentNullException("params");
     _params = @params;
 }
예제 #4
0
        public static void Write(XmlWriter writer, Capabilities pc)
        {
            var declarations = NamespaceDeclarations(pc);

            writer.WriteStartDocument();
            var prefix = declarations.LookupPrefix(Psf.PrintCapabilities.NamespaceName);
            writer.WriteStartElement(prefix, Psf.PrintCapabilities.LocalName, Psf.PrintCapabilities.NamespaceName);
            writer.WriteAttributeString("version", "1");

            foreach (var decl in declarations)
            {
                writer.WriteAttributeString("xmlns", decl.Prefix, null, decl.Uri.NamespaceName);
            }

            foreach (var f in pc.Features)
            {
                Write(writer, f);
            }

            foreach (var p in pc.Properties)
            {
                Write(writer, p);
            }

            foreach (var p in pc.Parameters)
            {
                Write(writer, p);
            }

            writer.WriteEndElement();
            writer.Flush();
        }
예제 #5
0
 public DesktopApp(IDriverContext context, Capabilities capabilities, IUACPomptHandler uacHandler, IUtils utils)
 {
     this.context = context;
     this.capabilities = capabilities; // TODO validate capabilities
     this.uacHandler = uacHandler;
     this.utils = utils;
 }
예제 #6
0
        /// <summary>
        /// Constructor taking arguments necessary to initialize the capability
        /// </summary>
        /// <param name="dataSourceManager">data source manager controlling the current session</param>
        /// <param name="dataSource">data source from which to aquire</param>
        /// <param name="cap">The capability which shall be represented by the object</param>
        public Capability(DataSourceManager dataSourceManager, DataSource dataSource, Capabilities cap)
        {
            this.CapabilityType = (short) cap;
            this.ItemType = -1;

            this.dataSourceManager = dataSourceManager;
            this.dataSource = dataSource;
        }
예제 #7
0
		/// <summary>
		/// Constructor for recording drivers
		/// </summary>
		/// <param name="systemHandle"></param>
		/// <param name="id"></param>
		/// <param name="name"></param>
		public Driver(IntPtr systemHandle, int id, string name)
		{
			this.systemHandle = systemHandle;
			this.id = id;
			this.name = name;
			this.capabilities = Capabilities.None;
			this.speakerMode = SpeakerMode.Stereo;
		}
        public void FindPropertyByNameTest()
        {
            var pc = new Capabilities();
            pc = pc.Add(new Property(Psk.DisplayName, "value"));

            var p = pc.Properties[Psk.DisplayName];

            Assert.Equal("value", p.Value);
        }
 public BasicPrintCapabilitiesReadingTests()
 {
     Assembly assembly = this.GetType().GetTypeInfo().Assembly;
     var names = assembly.GetManifestResourceNames();
     using (var stream = assembly.GetManifestResourceStream("Kip.Tests.Data.BasicPrintCapabilities.xml"))
     {
         _actual = Capabilities.Load(stream);
     }
 }
예제 #10
0
        public void GetFeatureOptionsReturnsEmptyIfFeatureNotFound()
        {
            var pc = new Capabilities(
                new Feature(Exp.SomeFeature,
                    new Option(Exp.SomeOption1),
                    new Option(Exp.SomeOption2)));
            var options = pc.Get(Exp.OtherFeature);

            Assert.Null(options);
        }
예제 #11
0
        public void ThrowsExceptionWhenAddPropertyWithExistingNameToCapabilites()
        {
            var pc = new Capabilities();
            pc = pc.Add(new Property(Exp.SomeProperty));

            Assert.Throws<DuplicateNameException>(() =>
            {
                pc = pc.Add(new Property(Exp.SomeProperty));
            });
        }
예제 #12
0
        public void ThrowsExceptionWhenAddFeatureWithExistingNameToCapabilites()
        {
            var pc = new Capabilities();
            pc = pc.Add(new Feature(Exp.SomeFeature));

            Assert.Throws<DuplicateNameException>(() =>
            {
                pc = pc.Add(new Feature(Exp.SomeFeature));
            });
        }
예제 #13
0
		public Driver(IntPtr systemHandle, int id, string name, Capabilities capabilities, int minimumFrequency, int maximumFrequency, SpeakerMode speakerMode)
		{
			this.systemHandle = systemHandle;
			this.id = id;
			this.name = name;
			this.capabilities = capabilities;
			this.minimumFrequency = minimumFrequency;
			this.maximumFrequency = maximumFrequency;
			this.speakerMode = speakerMode;
		}
예제 #14
0
        static Device()
        {
            OpenTK.Graphics.GraphicsContext.ShareContexts = true;
            toolkit = OpenTK.Toolkit.Init();

            sharedWindow = new GameWindow(10, 10, GraphicsMode.Default, "shared context window", GameWindowFlags.Default, DisplayDevice.Default, 4, 0, GraphicsContextFlags.Default);
            sharedContext = new Context(sharedWindow.Context, sharedWindow.WindowInfo);
            sharedWindow.Disposed += (sender, args) => { throw new Exception(); };

            capabilities = new Capabilities();
        }
예제 #15
0
    public static DxCapabilities RequestCapabilities(Capabilities deviceCapabilities, DisplayMode displayMode)
    {
      int maxAnisotropy = deviceCapabilities.MaxAnisotropy;
      bool supportsFiltering = MPDirect3D.Direct3D.CheckDeviceFormat(
          deviceCapabilities.AdapterOrdinal, deviceCapabilities.DeviceType, displayMode.Format,
          Usage.RenderTarget | Usage.QueryFilter, ResourceType.Texture, Format.A8R8G8B8);

      bool supportsAlphaBlend = MPDirect3D.Direct3D.CheckDeviceFormat(deviceCapabilities.AdapterOrdinal,
          deviceCapabilities.DeviceType, displayMode.Format, Usage.RenderTarget | Usage.QueryPostPixelShaderBlending,
          ResourceType.Surface, Format.A8R8G8B8);
      bool supportsShaders = deviceCapabilities.PixelShaderVersion.Major >= 2 && deviceCapabilities.VertexShaderVersion.Major >= 2;
      return new DxCapabilities(maxAnisotropy, supportsFiltering, supportsAlphaBlend, supportsShaders);
    }
예제 #16
0
        public HandlerParams(HttpContext context, Map map, 
            Capabilities.WmsServiceDescription description,
            bool ignoreCase)
        {
            if (context == null)
                throw new ArgumentNullException("context");
            if (map == null)
                throw new ArgumentNullException("map");

            this.context = context;
            this.map = map;
            this.description = description;
            this.ignoreCase = ignoreCase;
        }
        public void RoundTripSafetyForProperties()
        {
            var pc = new Capabilities();
            var buffer = new StringBuilder();
            var writer = XmlWriter.Create(buffer);
            pc.Save(writer);

            using (var textReader = new StringReader(buffer.ToString()))
            {
                var actual = Capabilities.Load(textReader);

                Assert.NotNull(actual);
                Assert.Empty(pc.Properties);
            }
        }
예제 #18
0
        public static SmiResultCode GetCapabilities(ref Capabilities capability)
        {
            c_Capabilities c = new c_Capabilities();
            SmiResultCode result = c_GetCapabilities(ref c);

            if (result == SmiResultCode.Success)
            {
                capability.maxPeriod = c.maxPeriod;
                capability.minPeriod = c.minPeriod;
                capability.noteStyle = c.noteStyle;
                capability.pauseResume = c.pauseResume;
                capability.periodicPlay = c.periodicPlay;
                capability.startEndMag = c.startEndMag;
            }

            return result;
        }
 /// <summary>
 /// Constructor.
 /// </summary>
 public CifsServerContext()
 {
     this.domainName = Environment.UserDomainName;
     this.serverName = Environment.MachineName;
     this.capabilities = Capabilities.NONE;
     this.globalTables = new CifsServerGlobalTables();
     this.messageSigningPolicy = MessageSigningPolicyValues.MessageSigningDisabled;
     this.plaintextAuthenticationPolicy = PlaintextAuthenticationPolicyValues.Disabled;
     this.lmAuthenticationPolicy = LMAuthenticationPolicyValues.Disabled;
     this.ntlmAuthenticationPolicy =
         NTLMAuthenticationPolicyValues.NtlmEnabled | NTLMAuthenticationPolicyValues.NtlmV2Enabled;
     this.isContextUpdateEnabled = true;
     this.accountCredentials = new Collection<AccountCredential>();
     this.nlmpServerSecurityContexts = new Collection<NlmpServerSecurityContext>();
     //The following default values are based on windows implementation.
     this.maxNumberVcs = 1;
     this.maxBufferSize = 16644;
     this.maxRawSize = 65536;
     this.maxMpxCount = 50;
 }
        public void WriteValueInProperty()
        {
            var pc = new Capabilities();
            pc = pc.Add(new Property(Psk.JobName, "some job name"));

            var buffer = new StringBuilder();
            var writer = XmlWriter.Create(buffer);
            pc.Save(writer);

            var doc = XDocument.Parse(buffer.ToString());

            Assert.Equal(Psf.PrintCapabilities, doc.Root.Name);

            var prop = doc.Root.Element(Psf.Property);
            Assert.NotNull(prop);
            Assert.Equal("psk:JobName", prop.Attribute("name").Value);

            var value = prop.Element(Psf.Value);
            Assert.Equal("xsd:string", value.Attribute(Xsi.Type).Value);
            Assert.Equal("some job name", value.Value);
        }
예제 #21
0
파일: DXMain.cs 프로젝트: mdmallardi/MGE-XE
        public static void GetDeviceCaps() {
            //Device.IsUsingEventHandlers=false;

            adapter=(int)Microsoft.Win32.Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Bethesda Softworks\Morrowind", "Adapter", 0);
            if(d3d.AdapterCount <= adapter) throw new ApplicationException("Morrowind is set up to use an adapter which could not be found on your system");

            for(int i=2;i<=16;i++) {
                if(d3d.CheckDeviceMultisampleType(adapter, DeviceType.Hardware, Format.X8R8G8B8, false, (MultisampleType)i))
                    mCaps.MaxFullscreenAA=i;
                if(d3d.CheckDeviceMultisampleType(adapter, DeviceType.Hardware, Format.X8R8G8B8, true, (MultisampleType)i))
                    mCaps.MaxWindowedAA=i;
            }

            caps = d3d.GetDeviceCaps(adapter, DeviceType.Hardware);

            mCaps.MaxAF=caps.MaxAnisotropy;
            mCaps.SupportsSM1=(caps.VertexShaderVersion>=new Version(1,1))&&(caps.PixelShaderVersion>=new Version(1,4));
            mCaps.SupportsSM2=(caps.VertexShaderVersion.Major>=2)&&(caps.PixelShaderVersion.Major>=2);
            mCaps.SupportsSM3=(caps.VertexShaderVersion.Major>=3)&&(caps.PixelShaderVersion.Major>=3);
            mCaps.MaxTexSize=Math.Min(caps.MaxTextureHeight, caps.MaxTextureWidth);
            mCaps.MaxPrimitives=caps.MaxPrimitiveCount;
            mCaps.MaxIndicies=caps.MaxVertexIndex;
        }
예제 #22
0
 public bool IsOneOf(string term)
 {
     return(Capabilities.SingleOrDefault(FuncFromTerm(term)) != null);
 }
예제 #23
0
        private void BindCapabilities()
        {
            //Bind only capabilities that have not yet been added
            var capabilities = new List <string>(ClientCapabilityProvider.Instance().GetAllClientCapabilityValues().Keys.Where(capability => Capabilities.Where(c => c.Capability == capability).Count() < 1));

            capabilities.Insert(0, LocalizeString("selectCapabilityName"));
            cboCapabilityName.DataSource = capabilities;
            cboCapabilityName.DataBind();
        }
예제 #24
0
        private static OnlineMeetingType CreateOnlineMeetingTypeFromOnlineMeetingResult(OnlineMeetingResult onlineMeetingResult, Capabilities capabilities, RequestDetailsLogger logger)
        {
            List <Exception>  list = new List <Exception>();
            OnlineMeetingType onlineMeetingType = new OnlineMeetingType();

            onlineMeetingType.HelpUrl              = onlineMeetingResult.CustomizationValues.InvitationHelpUrl;
            onlineMeetingType.LegalUrl             = onlineMeetingResult.CustomizationValues.InvitationLegalUrl;
            onlineMeetingType.CustomFooterText     = onlineMeetingResult.CustomizationValues.InvitationFooterText;
            onlineMeetingType.ExternalDirectoryUri = onlineMeetingResult.DialIn.ExternalDirectoryUri;
            onlineMeetingType.InternalDirectoryUri = onlineMeetingResult.DialIn.InternalDirectoryUri;
            onlineMeetingType.LogoUrl              = onlineMeetingResult.CustomizationValues.InvitationLogoUrl;
            onlineMeetingType.WebUrl = onlineMeetingResult.OnlineMeeting.WebUrl;
            try
            {
                onlineMeetingType.AccessLevel = CreateOnlineMeeting.ConvertAccessLevel(onlineMeetingResult.OnlineMeeting.Accesslevel);
            }
            catch (ArgumentException item)
            {
                list.Add(item);
            }
            try
            {
                onlineMeetingType.LobbyBypass = CreateOnlineMeeting.ConvertLobbyBypass(onlineMeetingResult.OnlineMeeting.PstnUserLobbyBypass);
            }
            catch (ArgumentException item2)
            {
                list.Add(item2);
            }
            try
            {
                onlineMeetingType.Presenters = CreateOnlineMeeting.ConvertPresenters(onlineMeetingResult.OnlineMeeting.AutomaticLeaderAssignment);
            }
            catch (ArgumentException item3)
            {
                list.Add(item3);
            }
            if (capabilities == null)
            {
                return(onlineMeetingType);
            }
            if (onlineMeetingResult.DialIn.IsAudioConferenceProviderEnabled)
            {
                onlineMeetingType.AcpInformation = new AcpInformationType();
                onlineMeetingType.AcpInformation.ParticipantPassCode = onlineMeetingResult.DialIn.ParticipantPassCode;
                onlineMeetingType.AcpInformation.TollNumber          = onlineMeetingResult.DialIn.TollNumber;
                onlineMeetingType.AcpInformation.TollFreeNumbers     = onlineMeetingResult.DialIn.TollFreeNumbers;
            }
            else
            {
                onlineMeetingType.ConferenceId = onlineMeetingResult.OnlineMeeting.PstnMeetingId;
                List <DialInNumberType> list2 = new List <DialInNumberType>();
                foreach (Region region in capabilities.Regions)
                {
                    foreach (AccessNumber accessNumber in region.AccessNumbers)
                    {
                        DialInNumberType dialInNumberType = new DialInNumberType();
                        dialInNumberType.RegionName = region.Name;
                        dialInNumberType.Number     = accessNumber.Number;
                        try
                        {
                            dialInNumberType.Language = new CultureInfo(accessNumber.LanguageID).NativeName;
                        }
                        catch (CultureNotFoundException ex)
                        {
                            ExTraceGlobals.OnlineMeetingTracer.TraceError <int, string>(0, 0L, "CreateOnlineMeeting::CreateOnlineMeetingTypeFromOnlineMeetingResult. CultureNotFoundException occurred when creating CultureInfo from LanguageId '{0}'. Exception:'{1}'.  ", accessNumber.LanguageID, UcwaConfigurationUtilities.BuildFailureLogString(ex));
                            list.Add(new OwaException(string.Format("Unable to create cultureInfo corresponding to lcid '{0}' for region '{1}' with number '{2}'", accessNumber.LanguageID, region.Name, accessNumber.Number), ex));
                        }
                        list2.Add(dialInNumberType);
                    }
                }
                onlineMeetingType.Numbers = list2.ToArray();
            }
            if (list.Count > 0)
            {
                StringBuilder stringBuilder = new StringBuilder();
                foreach (Exception ex2 in list)
                {
                    stringBuilder.AppendFormat("{0}::", UcwaConfigurationUtilities.BuildFailureLogString(ex2));
                }
                logger.Set(CreateOnlineMeetingMetadata.Exceptions, stringBuilder.ToString());
            }
            return(onlineMeetingType);
        }
 protected AbstractGetFeatureInfoText(Capabilities.WmsServiceDescription description,
     GetFeatureInfoParams @params) : base(description, @params) { }
예제 #26
0
        protected override OnlineMeetingType ProcessOnlineMeetingResult(UserContext userContext, OnlineMeetingResult result)
        {
            OnlineMeetingType result2;

            using (this.CalendarItem)
            {
                if (this.CalendarItem == null)
                {
                    result2 = OnlineMeetingType.CreateFailedOnlineMeetingType("Unable to find existing item corresponding to id: " + this.itemId.Id);
                }
                else
                {
                    this.CalendarItem.OpenAsReadWrite();
                    this.CalendarItem.OnlineMeetingConfLink     = result.OnlineMeeting.MeetingUri;
                    this.CalendarItem.OnlineMeetingExternalLink = result.OnlineMeeting.WebUrl;
                    this.CalendarItem.OnlineMeetingInternalLink = string.Empty;
                    this.CalendarItem.UCOpenedConferenceID      = Guid.NewGuid().ToString("B");
                    this.CalendarItem.ConferenceTelURI          = OutlookAddinAdapter.GetConferenceTelUri(result);
                    Capabilities ucCapabilities = OutlookAddinAdapter.GetUcCapabilities(result, userContext.UserCulture);
                    try
                    {
                        this.CalendarItem.UCCapabilities = OutlookAddinAdapter.Serialize(ucCapabilities);
                    }
                    catch (InvalidOperationException ex)
                    {
                        base.LogAndTraceError("An error occured while serializing UCCapabilities: " + UcwaConfigurationUtilities.BuildFailureLogString(ex));
                        return(OnlineMeetingType.CreateFailedOnlineMeetingType("An error occured while serializing UCCapabilities"));
                    }
                    try
                    {
                        this.CalendarItem.UCInband = OutlookAddinAdapter.Serialize(OutlookAddinAdapter.GetUCInband(result));
                    }
                    catch (InvalidOperationException ex2)
                    {
                        base.LogAndTraceError("An error occured while serializing UCInband: " + UcwaConfigurationUtilities.BuildFailureLogString(ex2));
                        return(OnlineMeetingType.CreateFailedOnlineMeetingType("An error occured while serializing UCInband"));
                    }
                    try
                    {
                        this.CalendarItem.UCMeetingSetting = OutlookAddinAdapter.Serialize(OutlookAddinAdapter.GetUCMeetingSetting(result));
                    }
                    catch (InvalidOperationException ex3)
                    {
                        base.LogAndTraceError("An error occured while serializing UCMeetingSetting: " + UcwaConfigurationUtilities.BuildFailureLogString(ex3));
                        return(OnlineMeetingType.CreateFailedOnlineMeetingType("An error occured while serializing UCMeetingSetting"));
                    }
                    try
                    {
                        PropertyDefinitionStream updatedOutlookUserPropsPropDefStream = OutlookAddinAdapter.GetUpdatedOutlookUserPropsPropDefStream(this.CalendarItem.OutlookUserPropsPropDefStream);
                        this.CalendarItem.OutlookUserPropsPropDefStream = updatedOutlookUserPropsPropDefStream.GetByteArray();
                    }
                    catch (EndOfStreamException ex4)
                    {
                        base.LogAndTraceError("[ProcessOnlineMeetingResult] A read error occurred when parsing OutlookUserPropsPropDefStream: " + UcwaConfigurationUtilities.BuildFailureLogString(ex4));
                        return(OnlineMeetingType.CreateFailedOnlineMeetingType("A read error occured when parsing OutlookUserPropsPropDefStream"));
                    }
                    OnlineMeetingType          onlineMeetingType = CreateOnlineMeeting.CreateOnlineMeetingTypeFromOnlineMeetingResult(result, ucCapabilities, base.CallContext.ProtocolLog);
                    ConcatenatedIdAndChangeKey concatenatedId    = IdConverter.GetConcatenatedId(this.CalendarItem.Id, new MailboxId(this.MailboxSession), null);
                    onlineMeetingType.ItemId = new ItemId(concatenatedId.Id, concatenatedId.ChangeKey);
                    this.CalendarItem.Save(SaveMode.NoConflictResolutionForceSave);
                    result2 = onlineMeetingType;
                }
            }
            return(result2);
        }
예제 #27
0
 public ConnectionCredentials(string twitchUsername, string twitchOAuth, string twitchWebsocketURI = "wss://irc-ws.chat.twitch.tv:443", bool disableUsernameCheck = false, Capabilities capabilities = null) : base(twitchUsername, twitchOAuth, twitchWebsocketURI, disableUsernameCheck, capabilities)
 {
 }
 /// <summary>
 ///    Sets a flag stating the specified feature is supported.
 /// </summary>
 /// <param name="cap"></param>
 public void SetCap(Capabilities cap)
 {
     caps |= cap;
 }
예제 #29
0
        public KernelResult InitializeKip(
            ProcessCreationInfo creationInfo,
            ReadOnlySpan <int> capabilities,
            KPageList pageList,
            KResourceLimit resourceLimit,
            MemoryRegion memRegion,
            IProcessContextFactory contextFactory,
            ThreadStart customThreadStart = null)
        {
            ResourceLimit      = resourceLimit;
            _memRegion         = memRegion;
            _contextFactory    = contextFactory ?? new ProcessContextFactory();
            _customThreadStart = customThreadStart;

            AddressSpaceType addrSpaceType = (AddressSpaceType)((int)(creationInfo.Flags & ProcessCreationFlags.AddressSpaceMask) >> (int)ProcessCreationFlags.AddressSpaceShift);

            Pid = KernelContext.NewKipId();

            if (Pid == 0 || (ulong)Pid >= KernelConstants.InitialProcessId)
            {
                throw new InvalidOperationException($"Invalid KIP Id {Pid}.");
            }

            InitializeMemoryManager(creationInfo.Flags);

            bool aslrEnabled = creationInfo.Flags.HasFlag(ProcessCreationFlags.EnableAslr);

            ulong codeAddress = creationInfo.CodeAddress;

            ulong codeSize = (ulong)creationInfo.CodePagesCount * KPageTableBase.PageSize;

            KMemoryBlockSlabManager slabManager = creationInfo.Flags.HasFlag(ProcessCreationFlags.IsApplication)
                ? KernelContext.LargeMemoryBlockSlabManager
                : KernelContext.SmallMemoryBlockSlabManager;

            KernelResult result = MemoryManager.InitializeForProcess(
                addrSpaceType,
                aslrEnabled,
                !aslrEnabled,
                memRegion,
                codeAddress,
                codeSize,
                slabManager);

            if (result != KernelResult.Success)
            {
                return(result);
            }

            if (!MemoryManager.CanContain(codeAddress, codeSize, MemoryState.CodeStatic))
            {
                return(KernelResult.InvalidMemRange);
            }

            result = MemoryManager.MapPages(codeAddress, pageList, MemoryState.CodeStatic, KMemoryPermission.None);

            if (result != KernelResult.Success)
            {
                return(result);
            }

            result = Capabilities.InitializeForKernel(capabilities, MemoryManager);

            if (result != KernelResult.Success)
            {
                return(result);
            }

            return(ParseProcessInfo(creationInfo));
        }
예제 #30
0
 public override string GetConfig(Capabilities withCapabilities)
 {
     return(_config);
 }
        /// <summary>
        ///    Default constructor.
        /// </summary>
        public HardwareCaps()
        {
            caps = 0;

            systemMemorySize = GetSystemMemorySize();
        }
예제 #32
0
        public NTStatus Login(string domainName, string userName, string password, AuthenticationMethod authenticationMethod)
        {
            if (!m_isConnected)
            {
                throw new InvalidOperationException("A connection must be successfully established before attempting login");
            }

            Capabilities clientCapabilities = Capabilities.NTSMB | Capabilities.RpcRemoteApi | Capabilities.NTStatusCode | Capabilities.NTFind;

            if (m_unicode)
            {
                clientCapabilities |= Capabilities.Unicode;
            }
            if (m_largeFiles)
            {
                clientCapabilities |= Capabilities.LargeFiles;
            }
            if (m_largeRead)
            {
                clientCapabilities |= Capabilities.LargeRead;
            }

            if (m_serverChallenge != null)
            {
                SessionSetupAndXRequest request = new SessionSetupAndXRequest();
                request.MaxBufferSize = ClientMaxBufferSize;
                request.MaxMpxCount   = m_maxMpxCount;
                request.Capabilities  = clientCapabilities;
                request.AccountName   = userName;
                request.PrimaryDomain = domainName;
                byte[] clientChallenge = new byte[8];
                new Random().NextBytes(clientChallenge);
                if (authenticationMethod == AuthenticationMethod.NTLMv1)
                {
                    request.OEMPassword     = NTLMCryptography.ComputeLMv1Response(m_serverChallenge, password);
                    request.UnicodePassword = NTLMCryptography.ComputeNTLMv1Response(m_serverChallenge, password);
                }
                else if (authenticationMethod == AuthenticationMethod.NTLMv1ExtendedSessionSecurity)
                {
                    // [MS-CIFS] CIFS does not support Extended Session Security because there is no mechanism in CIFS to negotiate Extended Session Security
                    throw new ArgumentException("SMB Extended Security must be negotiated in order for NTLMv1 Extended Session Security to be used");
                }
                else // NTLMv2
                {
                    // Note: NTLMv2 over non-extended security session setup is not supported under Windows Vista and later which will return STATUS_INVALID_PARAMETER.
                    // https://msdn.microsoft.com/en-us/library/ee441701.aspx
                    // https://msdn.microsoft.com/en-us/library/cc236700.aspx
                    request.OEMPassword = NTLMCryptography.ComputeLMv2Response(m_serverChallenge, clientChallenge, password, userName, domainName);
                    NTLMv2ClientChallenge clientChallengeStructure = new NTLMv2ClientChallenge(DateTime.UtcNow, clientChallenge, AVPairUtils.GetAVPairSequence(domainName, Environment.MachineName));
                    byte[] temp     = clientChallengeStructure.GetBytesPadded();
                    byte[] proofStr = NTLMCryptography.ComputeNTLMv2Proof(m_serverChallenge, temp, password, userName, domainName);
                    request.UnicodePassword = ByteUtils.Concatenate(proofStr, temp);
                }

                TrySendMessage(request);

                SMB1Message reply = WaitForMessage(CommandName.SMB_COM_SESSION_SETUP_ANDX);
                if (reply != null)
                {
                    m_isLoggedIn = (reply.Header.Status == NTStatus.STATUS_SUCCESS);
                    return(reply.Header.Status);
                }
                return(NTStatus.STATUS_INVALID_SMB);
            }
            else // m_securityBlob != null
            {
                byte[] negotiateMessage = NTLMAuthenticationHelper.GetNegotiateMessage(m_securityBlob, domainName, authenticationMethod);
                if (negotiateMessage == null)
                {
                    return(NTStatus.SEC_E_INVALID_TOKEN);
                }

                SessionSetupAndXRequestExtended request = new SessionSetupAndXRequestExtended();
                request.MaxBufferSize = ClientMaxBufferSize;
                request.MaxMpxCount   = m_maxMpxCount;
                request.Capabilities  = clientCapabilities;
                request.SecurityBlob  = negotiateMessage;
                TrySendMessage(request);

                SMB1Message reply = WaitForMessage(CommandName.SMB_COM_SESSION_SETUP_ANDX);
                if (reply != null)
                {
                    if (reply.Header.Status == NTStatus.STATUS_MORE_PROCESSING_REQUIRED && reply.Commands[0] is SessionSetupAndXResponseExtended)
                    {
                        SessionSetupAndXResponseExtended response = (SessionSetupAndXResponseExtended)reply.Commands[0];
                        byte[] authenticateMessage = NTLMAuthenticationHelper.GetAuthenticateMessage(response.SecurityBlob, domainName, userName, password, authenticationMethod, out m_sessionKey);
                        if (authenticateMessage == null)
                        {
                            return(NTStatus.SEC_E_INVALID_TOKEN);
                        }

                        m_userID = reply.Header.UID;
                        request  = new SessionSetupAndXRequestExtended();
                        request.MaxBufferSize = ClientMaxBufferSize;
                        request.MaxMpxCount   = m_maxMpxCount;
                        request.Capabilities  = clientCapabilities;
                        request.SecurityBlob  = authenticateMessage;
                        TrySendMessage(request);

                        reply = WaitForMessage(CommandName.SMB_COM_SESSION_SETUP_ANDX);
                        if (reply != null)
                        {
                            m_isLoggedIn = (reply.Header.Status == NTStatus.STATUS_SUCCESS);
                            return(reply.Header.Status);
                        }
                    }
                    else
                    {
                        return(reply.Header.Status);
                    }
                }
                return(NTStatus.STATUS_INVALID_SMB);
            }
        }
        public static async Task <InvocationRequest> ToRpcInvocationRequest(this ScriptInvocationContext context, ILogger logger, Capabilities capabilities)
        {
            bool excludeHttpTriggerMetadata = !string.IsNullOrEmpty(capabilities.GetCapabilityState(RpcWorkerConstants.RpcHttpTriggerMetadataRemoved));

            var invocationRequest = new InvocationRequest
            {
                FunctionId   = context.FunctionMetadata.GetFunctionId(),
                InvocationId = context.ExecutionContext.InvocationId.ToString(),
                TraceContext = GetRpcTraceContext(context.Traceparent, context.Tracestate, context.Attributes, logger),
            };

            var rpcValueCache = new Dictionary <object, TypedData>();

            foreach (var input in context.Inputs)
            {
                TypedData rpcValue = null;
                if (input.val == null || !rpcValueCache.TryGetValue(input.val, out rpcValue))
                {
                    rpcValue = await input.val.ToRpc(logger, capabilities);

                    if (input.val != null)
                    {
                        rpcValueCache.Add(input.val, rpcValue);
                    }
                }

                var parameterBinding = new ParameterBinding
                {
                    Name = input.name,
                    Data = rpcValue
                };
                invocationRequest.InputData.Add(parameterBinding);
            }

            foreach (var pair in context.BindingData)
            {
                if (ShouldSkipBindingData(pair, context, excludeHttpTriggerMetadata))
                {
                    continue;
                }

                if (!rpcValueCache.TryGetValue(pair.Value, out TypedData rpcValue))
                {
                    rpcValue = await pair.Value.ToRpc(logger, capabilities);

                    rpcValueCache.Add(pair.Value, rpcValue);
                }

                invocationRequest.TriggerMetadata.Add(pair.Key, rpcValue);
            }

            return(invocationRequest);
        }
예제 #34
0
 public T GetCapability <T>() where T : OdcmCapability
 {
     return(Capabilities.SingleOrDefault(c => c.GetType() == typeof(T)) as T);
 }
예제 #35
0
 protected virtual bool ConfirmDevice(Capabilities caps, VertexProcessingType vertexProcessingType,
                                      Format adapterFormat, Format backBufferFormat)
 {
     return(true);
 }
        /// <summary>
        /// create the implicit NTLM SessionSetup request packet 
        /// </summary>
        /// <param name = "messageId">the id of message, used to identity the request and the server response. </param>
        /// <param name = "flags">
        /// The Flags field contains individual flags, as specified in [CIFS] sections 2.4.2 and 3.1.1. 
        /// </param>
        /// <param name = "flags2">
        /// The Flags2 field contains individual bit flags that, depending on the negotiated SMB dialect, indicate   
        /// various client and server capabilities. 
        /// </param>
        /// <param name = "capabilities">
        /// A set of client capabilities. These flags are a subset of those specified in section for the server   
        /// capabilities returned in the SMB_COM_NEGOTIATE response. 
        /// </param>
        /// <param name = "maxBufferSize">
        /// The maximum size, in bytes, of the client buffer for sending and receiving SMB messages. 
        /// </param>
        /// <param name = "maxMpxCount">
        /// The maximum number of pending multiplexed requests supported by the client. This value MUST be less than 
        /// or equal to the MaxMpxCount value provided by the server in the SMB_COM_NEGOTIATE response 
        /// </param>
        /// <param name = "implicitNtlmVersion">
        /// the version of smb to using: PlainTextPassword: transport password as plain-text.     the 
        /// NEGOTIATE_ENCRYPT_PASSWORDS of SecurityMode in negotiate response should set to 0. NtlmVersion1:using ntlm 
        /// v1 NtlmVersion2:using ntlm v2 
        /// </param>
        /// <param name = "domainName">the domain name of user credential </param>
        /// <param name = "userName">the name of user credential </param>
        /// <param name = "password">the password of user credential </param>
        /// <returns>A session setup packet. </returns>
        /// <exception cref = "InvalidOperationException">
        /// the implicit NTLM only support when ExtendedSessionSecurity is set to 0 
        /// </exception>
        private SmbSessionSetupImplicitNtlmAndxRequestPacket CreateSessionSetupImplicitNtlmRequest(
            ushort messageId,
            SmbHeader_Flags_Values flags,
            SmbHeader_Flags2_Values flags2,
            Capabilities capabilities,
            ushort maxBufferSize,
            ushort maxMpxCount,
            ImplicitNtlmVersion implicitNtlmVersion,
            string domainName,
            string userName,
            string password)
        {
            if (Capability.IsSupportsExtendedSecurity)
            {
                throw new InvalidOperationException(
                    "the implicit NTLM only support when ExtendedSessionSecurity is set to 0");
            }

            NTLMAuthenticationPolicyValues ntlmAuthenticationPolicyValues;
            LMAuthenticationPolicyValues lmAuthenticationPolicyValues;

            if (implicitNtlmVersion == ImplicitNtlmVersion.PlainTextPassword)
            {
                ntlmAuthenticationPolicyValues = NTLMAuthenticationPolicyValues.Disabled;
                lmAuthenticationPolicyValues = LMAuthenticationPolicyValues.Disabled;
            }
            else if (implicitNtlmVersion == ImplicitNtlmVersion.NtlmVersion1)
            {
                ntlmAuthenticationPolicyValues = NTLMAuthenticationPolicyValues.Disabled;
                lmAuthenticationPolicyValues = LMAuthenticationPolicyValues.LmEnabled;
            }
            // ntlm version 2
            else
            {
                ntlmAuthenticationPolicyValues = NTLMAuthenticationPolicyValues.NtlmV2Enabled;
                lmAuthenticationPolicyValues = LMAuthenticationPolicyValues.LmV2Enabled;
            }

            return new SmbSessionSetupImplicitNtlmAndxRequestPacket(
                this.cifsClient.CreateSessionSetupAndxRequest(
                messageId, (SmbFlags)flags, (SmbFlags2)flags2, maxBufferSize, maxMpxCount, 0, 0,
                (Cifs.Capabilities)capabilities, new CifsUserAccount(domainName, userName, password), "\0", "\0", null,
                ntlmAuthenticationPolicyValues, lmAuthenticationPolicyValues));
        }
예제 #37
0
        protected Capabilities GetCapabilities(CapabilityCategory[] categories, string stepName)
        {
            Capabilities capabilities = null;

            bool retry = false;

            BeginStep("GetCapabilities (no credentials supplied)");
            try
            {
                capabilities = Client.GetCapabilities(categories);
            }
            catch (HttpTransport.Interfaces.Exceptions.AccessDeniedException exc)
            {
                // digest authorization required
                _credentialsProvider.Security = Security.Digest;
                LogStepEvent("DUT requires Digest authentication");
                LogStepEvent("Warning: GetCapabilities should not require authentication");
                retry = true;
            }
            catch (FaultException exc)
            {
                LogFault(exc);
                if (IsAccessDeniedFault(exc))
                {
                    // WS-username quthentication required
                    _credentialsProvider.Security = Security.WS;
                    LogStepEvent("DUT requires WS-UsernameToken authentication");
                    LogStepEvent("Warning: GetCapabilities should not require authentication");
                    retry = true;
                }
            }
            catch (Exception exc)
            {
                RethrowIfStop(exc);
                LogStepEvent(string.Format("GetCapabilities failed ({0})", exc.Message));
            }
            StepPassed();
            DoRequestDelay();

            // suppress any exceptions. Return null, if somethig goes wrong.
            if (retry)
            {
                BeginStep("Get Capabilities");
                try
                {
                    capabilities = Client.GetCapabilities(categories);
                }
                catch (FaultException exc)
                {
                    LogFault(exc);
                    LogStepEvent(string.Format("GetCapabilities failed ({0})", exc.Message));
                }
                catch (Exception exc)
                {
                    RethrowIfStop(exc);
                    LogStepEvent(string.Format("GetCapabilities failed ({0})", exc.Message));
                }

                StepPassed();
                DoRequestDelay();
            }

            return(capabilities);
        }
예제 #38
0
 protected AbstractHandler(Capabilities.WmsServiceDescription description)
 {
     _description = description;
 }
예제 #39
0
        static void Main(string[] args)
        {
            DirectInput d = new DirectInput();

            List <JoystickUpdate> statusHistory = new List <JoystickUpdate>(15);

            // Runs forever, where the last thing that happened was the controller was unplugged, then it comes back and waits for a new controller.
            while (true)
            {
                // Waits until a gamepad is plugged in.
                Console.WriteLine("Searching for gamepad...");
                while (d.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices).Count == 0)
                {
                    ;
                }

                Console.WriteLine("Connecting...");
                Guid     joystickId = d.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AllDevices)[0].InstanceGuid;
                Joystick stick      = new Joystick(d, joystickId);

                Console.WriteLine("Connected to Joystick {0}!", joystickId);

                Console.WriteLine("Setting up properties...");
                stick.Properties.BufferSize = 128;
                Capabilities c = stick.Capabilities;
                Console.WriteLine("Number of axes: " + c.AxeCount);
                Console.WriteLine("Number of Buttons: " + c.ButtonCount);
                Console.WriteLine("Flags: " + c.Flags);

                Console.WriteLine("Finding Minecraft");
                Process[] processes = Process.GetProcessesByName("Minecraft");
                while (processes.Length == 0)
                {
                    Console.WriteLine("Waiting for Minecraft...");
                    Thread.Sleep(5000);
                    processes = Process.GetProcessesByName("Minecraft");
                }
                Console.WriteLine("Minecraft Located!");
                //SetForegroundWindow(hWnd);

                Console.WriteLine("Press any key to begin!");
                Console.Read();
                stick.Acquire();

                Console.WriteLine("Ready to read data!");
                while (!stick.IsDisposed)
                {
                    stick.Poll();
                    JoystickUpdate[] datas = stick.GetBufferedData();
                    foreach (JoystickUpdate state in datas)
                    {
                        if (didSomethingHappen(state))
                        {
                            Console.WriteLine(state);
                        }

                        switch (state.Offset)
                        {
                        case JoystickOffset.Y:
                            Console.WriteLine("Updating Movement!");
                            if (state.Value > 40000)
                            {
                                SendKeys.SendWait("s");
                            }
                            else if (state.Value < 25000)
                            {
                                SendKeys.SendWait("w");
                            }
                            break;

                        case JoystickOffset.X:
                            Console.WriteLine("Updating Movement!");
                            if (state.Value > 40000)
                            {
                                SendKeys.SendWait("d");
                            }
                            else if (state.Value < 25000)
                            {
                                SendKeys.SendWait("a");
                            }
                            break;

                        case JoystickOffset.Buttons0:
                            Console.WriteLine("Jumping!");
                            SendKeys.SendWait(" ");
                            break;
                        }
                    }
                }
            }

            /// Helps to eliminate noise from the controller
            bool didSomethingHappen(JoystickUpdate status)
            {
                Predicate <JoystickUpdate> findUpdateType  = new Predicate <JoystickUpdate>((JoystickUpdate update) => { return(update.Offset == status.Offset); });
                List <JoystickUpdate>      matchingHistory = statusHistory.FindAll(findUpdateType);

                if (matchingHistory.Count > 0)
                {
                    foreach (JoystickUpdate j in matchingHistory)
                    {
                        if (Math.Abs(j.Value - status.Value) > 100 && (status.Offset == JoystickOffset.X || status.Offset == JoystickOffset.Y ||
                                                                       status.Offset == JoystickOffset.RotationX || status.Offset == JoystickOffset.RotationY))
                        {
                            statusHistory[statusHistory.FindIndex(findUpdateType)] = status;
                            return(true);
                        }
                        else if (Math.Abs(j.Value - status.Value) > 1 && (status.Offset != JoystickOffset.X || status.Offset != JoystickOffset.Y ||
                                                                          status.Offset != JoystickOffset.RotationX || status.Offset != JoystickOffset.RotationY))
                        {
                            statusHistory[statusHistory.FindIndex(findUpdateType)] = status;
                            return(true);
                        }
                    }
                }
                else
                {
                    statusHistory.Add(status);
                    return(true);
                }
                return(false);
            }
        }
예제 #40
0
 public bool hasCapability(Capabilities _test)
 {
     //return false;
     return (_test & _innerCap) != Capabilities.NONE;
 }
예제 #41
0
 public static extern uint XInputGetCapabilities(
     uint dwUserIndex,              // Index of the gamer associated with the device
     uint dwFlags,                  // Input flags that identify the device type
     ref Capabilities pCapabilities // Receives the capabilities
     );
예제 #42
0
        /// <summary>
        /// Check if the target of the first texture view information is compatible with the target of the second texture view information.
        /// This follows the host API target compatibility rules.
        /// </summary>
        /// <param name="lhs">Texture information of the texture view</param
        /// <param name="rhs">Texture information of the texture view</param>
        /// <param name="caps">Host GPU capabilities</param>
        /// <returns>True if the targets are compatible, false otherwise</returns>
        public static TextureViewCompatibility ViewTargetCompatible(TextureInfo lhs, TextureInfo rhs, ref Capabilities caps)
        {
            bool result = false;

            switch (lhs.Target)
            {
            case Target.Texture1D:
            case Target.Texture1DArray:
                result = rhs.Target == Target.Texture1D ||
                         rhs.Target == Target.Texture1DArray;
                break;

            case Target.Texture2D:
                result = rhs.Target == Target.Texture2D ||
                         rhs.Target == Target.Texture2DArray;
                break;

            case Target.Texture2DArray:
                result = rhs.Target == Target.Texture2D ||
                         rhs.Target == Target.Texture2DArray;

                if (rhs.Target == Target.Cubemap || rhs.Target == Target.CubemapArray)
                {
                    return(caps.SupportsCubemapView ? TextureViewCompatibility.Full : TextureViewCompatibility.CopyOnly);
                }
                break;

            case Target.Cubemap:
            case Target.CubemapArray:
                result = rhs.Target == Target.Cubemap ||
                         rhs.Target == Target.CubemapArray;

                if (rhs.Target == Target.Texture2D || rhs.Target == Target.Texture2DArray)
                {
                    return(caps.SupportsCubemapView ? TextureViewCompatibility.Full : TextureViewCompatibility.CopyOnly);
                }
                break;

            case Target.Texture2DMultisample:
            case Target.Texture2DMultisampleArray:
                if (rhs.Target == Target.Texture2D || rhs.Target == Target.Texture2DArray)
                {
                    return(TextureViewCompatibility.CopyOnly);
                }

                result = rhs.Target == Target.Texture2DMultisample ||
                         rhs.Target == Target.Texture2DMultisampleArray;
                break;

            case Target.Texture3D:
                if (rhs.Target == Target.Texture2D)
                {
                    return(TextureViewCompatibility.CopyOnly);
                }

                result = rhs.Target == Target.Texture3D;
                break;
            }

            return(result ? TextureViewCompatibility.Full : TextureViewCompatibility.Incompatible);
        }
예제 #43
0
        /// <summary>
        /// Initialize the cache.
        /// </summary>
        internal void Initialize()
        {
            if (GraphicsConfig.EnableShaderCache && GraphicsConfig.TitleId != null)
            {
                _cacheManager = new CacheManager(CacheGraphicsApi.OpenGL, CacheHashType.XxHash128, "glsl", GraphicsConfig.TitleId, ShaderCodeGenVersion);

                bool isReadOnly = _cacheManager.IsReadOnly;

                HashSet <Hash128> invalidEntries = null;

                if (isReadOnly)
                {
                    Logger.Warning?.Print(LogClass.Gpu, "Loading shader cache in read-only mode (cache in use by another program!)");
                }
                else
                {
                    invalidEntries = new HashSet <Hash128>();
                }

                ReadOnlySpan <Hash128> guestProgramList = _cacheManager.GetGuestProgramList();

                using AutoResetEvent progressReportEvent = new AutoResetEvent(false);

                _shaderCount      = 0;
                _totalShaderCount = guestProgramList.Length;

                ShaderCacheStateChanged?.Invoke(ShaderCacheState.Start, _shaderCount, _totalShaderCount);
                Thread progressReportThread = null;

                if (guestProgramList.Length > 0)
                {
                    progressReportThread = new Thread(ReportProgress)
                    {
                        Name         = "ShaderCache.ProgressReporter",
                        Priority     = ThreadPriority.Lowest,
                        IsBackground = true
                    };

                    progressReportThread.Start(progressReportEvent);
                }

                // Make sure these are initialized before doing compilation.
                Capabilities caps = _context.Capabilities;

                int maxTaskCount = Math.Min(Environment.ProcessorCount, 8);
                int programIndex = 0;
                List <ShaderCompileTask> activeTasks = new List <ShaderCompileTask>();

                AutoResetEvent taskDoneEvent = new AutoResetEvent(false);

                // This thread dispatches tasks to do shader translation, and creates programs that OpenGL will link in the background.
                // The program link status is checked in a non-blocking manner so that multiple shaders can be compiled at once.

                while (programIndex < guestProgramList.Length || activeTasks.Count > 0)
                {
                    if (activeTasks.Count < maxTaskCount && programIndex < guestProgramList.Length)
                    {
                        // Begin a new shader compilation.
                        Hash128 key = guestProgramList[programIndex];

                        byte[] hostProgramBinary = _cacheManager.GetHostProgramByHash(ref key);
                        bool   hasHostCache      = hostProgramBinary != null;

                        IProgram hostProgram = null;

                        // If the program sources aren't in the cache, compile from saved guest program.
                        byte[] guestProgram = _cacheManager.GetGuestProgramByHash(ref key);

                        if (guestProgram == null)
                        {
                            Logger.Error?.Print(LogClass.Gpu, $"Ignoring orphan shader hash {key} in cache (is the cache incomplete?)");

                            // Should not happen, but if someone messed with the cache it's better to catch it.
                            invalidEntries?.Add(key);

                            _shaderCount = ++programIndex;

                            continue;
                        }

                        ReadOnlySpan <byte> guestProgramReadOnlySpan = guestProgram;

                        ReadOnlySpan <GuestShaderCacheEntry> cachedShaderEntries = GuestShaderCacheEntry.Parse(ref guestProgramReadOnlySpan, out GuestShaderCacheHeader fileHeader);

                        if (cachedShaderEntries[0].Header.Stage == ShaderStage.Compute)
                        {
                            Debug.Assert(cachedShaderEntries.Length == 1);

                            GuestShaderCacheEntry entry = cachedShaderEntries[0];

                            HostShaderCacheEntry[] hostShaderEntries = null;

                            // Try loading host shader binary.
                            if (hasHostCache)
                            {
                                hostShaderEntries = HostShaderCacheEntry.Parse(hostProgramBinary, out ReadOnlySpan <byte> hostProgramBinarySpan);
                                hostProgramBinary = hostProgramBinarySpan.ToArray();
                                hostProgram       = _context.Renderer.LoadProgramBinary(hostProgramBinary);
                            }

                            ShaderCompileTask task = new ShaderCompileTask(taskDoneEvent);
                            activeTasks.Add(task);

                            task.OnCompiled(hostProgram, (bool isHostProgramValid, ShaderCompileTask task) =>
                            {
                                ShaderProgram program = null;
                                ShaderProgramInfo shaderProgramInfo = null;

                                if (isHostProgramValid)
                                {
                                    // Reconstruct code holder.

                                    program           = new ShaderProgram(entry.Header.Stage, "");
                                    shaderProgramInfo = hostShaderEntries[0].ToShaderProgramInfo();

                                    ShaderCodeHolder shader = new ShaderCodeHolder(program, shaderProgramInfo, entry.Code);

                                    _cpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shader));

                                    return(true);
                                }
                                else
                                {
                                    // If the host program was rejected by the gpu driver or isn't in cache, try to build from program sources again.

                                    Task compileTask = Task.Run(() =>
                                    {
                                        IGpuAccessor gpuAccessor = new CachedGpuAccessor(_context, entry.Code, entry.Header.GpuAccessorHeader, entry.TextureDescriptors);

                                        var options = CreateTranslationOptions(DefaultFlags | TranslationFlags.Compute);
                                        program     = Translator.CreateContext(0, gpuAccessor, options).Translate(out shaderProgramInfo);
                                    });

                                    task.OnTask(compileTask, (bool _, ShaderCompileTask task) =>
                                    {
                                        ShaderCodeHolder shader = new ShaderCodeHolder(program, shaderProgramInfo, entry.Code);

                                        Logger.Info?.Print(LogClass.Gpu, $"Host shader {key} got invalidated, rebuilding from guest...");

                                        // Compile shader and create program as the shader program binary got invalidated.
                                        shader.HostShader = CompileShader(shader.Program, shader.Info);
                                        hostProgram       = _context.Renderer.CreateProgram(new IShader[] { shader.HostShader }, null);

                                        task.OnCompiled(hostProgram, (bool isNewProgramValid, ShaderCompileTask task) =>
                                        {
                                            // As the host program was invalidated, save the new entry in the cache.
                                            hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), new ShaderCodeHolder[] { shader });

                                            if (!isReadOnly)
                                            {
                                                if (hasHostCache)
                                                {
                                                    _cacheManager.ReplaceHostProgram(ref key, hostProgramBinary);
                                                }
                                                else
                                                {
                                                    Logger.Warning?.Print(LogClass.Gpu, $"Add missing host shader {key} in cache (is the cache incomplete?)");

                                                    _cacheManager.AddHostProgram(ref key, hostProgramBinary);
                                                }
                                            }

                                            _cpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shader));

                                            return(true);
                                        });

                                        return(false); // Not finished: still need to compile the host program.
                                    });

                                    return(false); // Not finished: translating the program.
                                }
                            });
                        }
                        else
                        {
                            Debug.Assert(cachedShaderEntries.Length == Constants.ShaderStages);

                            ShaderCodeHolder[]   shaders        = new ShaderCodeHolder[cachedShaderEntries.Length];
                            List <ShaderProgram> shaderPrograms = new List <ShaderProgram>();

                            TransformFeedbackDescriptor[] tfd = CacheHelper.ReadTransformFeedbackInformation(ref guestProgramReadOnlySpan, fileHeader);

                            TranslationFlags flags = DefaultFlags;

                            if (tfd != null)
                            {
                                flags |= TranslationFlags.Feedback;
                            }

                            HostShaderCacheEntry[] hostShaderEntries = null;

                            // Try loading host shader binary.
                            if (hasHostCache)
                            {
                                hostShaderEntries = HostShaderCacheEntry.Parse(hostProgramBinary, out ReadOnlySpan <byte> hostProgramBinarySpan);
                                hostProgramBinary = hostProgramBinarySpan.ToArray();
                                hostProgram       = _context.Renderer.LoadProgramBinary(hostProgramBinary);
                            }

                            ShaderCompileTask task = new ShaderCompileTask(taskDoneEvent);
                            activeTasks.Add(task);

                            GuestShaderCacheEntry[] entries = cachedShaderEntries.ToArray();

                            task.OnCompiled(hostProgram, (bool isHostProgramValid, ShaderCompileTask task) =>
                            {
                                Task compileTask = Task.Run(() =>
                                {
                                    // Reconstruct code holder.
                                    for (int i = 0; i < entries.Length; i++)
                                    {
                                        GuestShaderCacheEntry entry = entries[i];

                                        if (entry == null)
                                        {
                                            continue;
                                        }

                                        ShaderProgram program;

                                        if (entry.Header.SizeA != 0)
                                        {
                                            ShaderProgramInfo shaderProgramInfo;

                                            if (isHostProgramValid)
                                            {
                                                program           = new ShaderProgram(entry.Header.Stage, "");
                                                shaderProgramInfo = hostShaderEntries[i].ToShaderProgramInfo();
                                            }
                                            else
                                            {
                                                IGpuAccessor gpuAccessor = new CachedGpuAccessor(_context, entry.Code, entry.Header.GpuAccessorHeader, entry.TextureDescriptors);

                                                var options  = CreateTranslationOptions(flags);
                                                var options2 = CreateTranslationOptions(flags | TranslationFlags.VertexA);

                                                TranslatorContext translatorContext  = Translator.CreateContext(0, gpuAccessor, options);
                                                TranslatorContext translatorContext2 = Translator.CreateContext((ulong)entry.Header.Size, gpuAccessor, options2);

                                                program = translatorContext.Translate(out shaderProgramInfo, translatorContext2);
                                            }

                                            // NOTE: Vertex B comes first in the shader cache.
                                            byte[] code  = entry.Code.AsSpan().Slice(0, entry.Header.Size).ToArray();
                                            byte[] code2 = entry.Code.AsSpan().Slice(entry.Header.Size, entry.Header.SizeA).ToArray();

                                            shaders[i] = new ShaderCodeHolder(program, shaderProgramInfo, code, code2);
                                        }
                                        else
                                        {
                                            ShaderProgramInfo shaderProgramInfo;

                                            if (isHostProgramValid)
                                            {
                                                program           = new ShaderProgram(entry.Header.Stage, "");
                                                shaderProgramInfo = hostShaderEntries[i].ToShaderProgramInfo();
                                            }
                                            else
                                            {
                                                IGpuAccessor gpuAccessor = new CachedGpuAccessor(_context, entry.Code, entry.Header.GpuAccessorHeader, entry.TextureDescriptors);

                                                var options = CreateTranslationOptions(flags);
                                                program     = Translator.CreateContext(0, gpuAccessor, options).Translate(out shaderProgramInfo);
                                            }

                                            shaders[i] = new ShaderCodeHolder(program, shaderProgramInfo, entry.Code);
                                        }

                                        shaderPrograms.Add(program);
                                    }
                                });

                                task.OnTask(compileTask, (bool _, ShaderCompileTask task) =>
                                {
                                    // If the host program was rejected by the gpu driver or isn't in cache, try to build from program sources again.
                                    if (!isHostProgramValid)
                                    {
                                        Logger.Info?.Print(LogClass.Gpu, $"Host shader {key} got invalidated, rebuilding from guest...");

                                        List <IShader> hostShaders = new List <IShader>();

                                        // Compile shaders and create program as the shader program binary got invalidated.
                                        for (int stage = 0; stage < Constants.ShaderStages; stage++)
                                        {
                                            ShaderProgram program = shaders[stage]?.Program;

                                            if (program == null)
                                            {
                                                continue;
                                            }

                                            IShader hostShader = CompileShader(program, shaders[stage].Info);;

                                            shaders[stage].HostShader = hostShader;

                                            hostShaders.Add(hostShader);
                                        }

                                        hostProgram = _context.Renderer.CreateProgram(hostShaders.ToArray(), tfd);

                                        task.OnCompiled(hostProgram, (bool isNewProgramValid, ShaderCompileTask task) =>
                                        {
                                            // As the host program was invalidated, save the new entry in the cache.
                                            hostProgramBinary = HostShaderCacheEntry.Create(hostProgram.GetBinary(), shaders);

                                            if (!isReadOnly)
                                            {
                                                if (hasHostCache)
                                                {
                                                    _cacheManager.ReplaceHostProgram(ref key, hostProgramBinary);
                                                }
                                                else
                                                {
                                                    Logger.Warning?.Print(LogClass.Gpu, $"Add missing host shader {key} in cache (is the cache incomplete?)");

                                                    _cacheManager.AddHostProgram(ref key, hostProgramBinary);
                                                }
                                            }

                                            _gpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shaders));

                                            return(true);
                                        });

                                        return(false); // Not finished: still need to compile the host program.
                                    }
                                    else
                                    {
                                        _gpProgramsDiskCache.Add(key, new ShaderBundle(hostProgram, shaders));

                                        return(true);
                                    }
                                });

                                return(false); // Not finished: translating the program.
                            });
                        }

                        _shaderCount = ++programIndex;
                    }

                    // Process the queue.
                    for (int i = 0; i < activeTasks.Count; i++)
                    {
                        ShaderCompileTask task = activeTasks[i];

                        if (task.IsDone())
                        {
                            activeTasks.RemoveAt(i--);
                        }
                    }

                    if (activeTasks.Count == maxTaskCount)
                    {
                        // Wait for a task to be done, or for 1ms.
                        // Host shader compilation cannot signal when it is done,
                        // so the 1ms timeout is required to poll status.

                        taskDoneEvent.WaitOne(1);
                    }
                }

                if (!isReadOnly)
                {
                    // Remove entries that are broken in the cache
                    _cacheManager.RemoveManifestEntries(invalidEntries);
                    _cacheManager.FlushToArchive();
                    _cacheManager.Synchronize();
                }

                progressReportEvent.Set();
                progressReportThread?.Join();

                ShaderCacheStateChanged?.Invoke(ShaderCacheState.Loaded, _shaderCount, _totalShaderCount);

                Logger.Info?.Print(LogClass.Gpu, $"Shader cache loaded {_shaderCount} entries.");
            }
        }
예제 #44
0
        public static InvocationRequest ToRpcInvocationRequest(this ScriptInvocationContext context, bool isTriggerMetadataPopulatedByWorker, ILogger logger, Capabilities capabilities)
        {
            InvocationRequest invocationRequest = new InvocationRequest()
            {
                FunctionId   = context.FunctionMetadata.FunctionId,
                InvocationId = context.ExecutionContext.InvocationId.ToString(),
                TraceContext = GetRpcTraceContext(context.Traceparent, context.Tracestate, context.Attributes, logger),
            };

            foreach (var pair in context.BindingData)
            {
                if (pair.Value != null)
                {
                    if ((pair.Value is HttpRequest) && isTriggerMetadataPopulatedByWorker)
                    {
                        continue;
                    }
                    invocationRequest.TriggerMetadata.Add(pair.Key, pair.Value.ToRpc(logger, capabilities));
                }
            }
            foreach (var input in context.Inputs)
            {
                invocationRequest.InputData.Add(new ParameterBinding()
                {
                    Name = input.name,
                    Data = input.val.ToRpc(logger, capabilities)
                });
            }

            return(invocationRequest);
        }
예제 #45
0
        /// <summary>
        /// Initializes the Direct3D objects and sets the Available flag
        /// </summary>
        private void InitializeDirect3D()
        {
            DirectXStatus = DirectXStatus.Unavailable_Unknown;

            ReleaseDevice();
            ReleaseDirect3D();

            // assume that we can't run at all under terminal services
            if (GetSystemMetrics(SmRemotesession) != 0)
            {
                DirectXStatus = DirectXStatus.Unavailable_RemoteSession;
                return;
            }

            int renderingTier = (RenderCapability.Tier >> 16);

            if (renderingTier < 2)
            {
                DirectXStatus = DirectXStatus.Unavailable_LowTier;
                return;
            }

#if USE_XP_MODE
            _direct3D   = new Direct3D();
            UseDeviceEx = false;
#else
            try
            {
                _direct3DEx = new Direct3DEx();
                UseDeviceEx = true;
            }
            catch
            {
                try
                {
                    _direct3D   = new Direct3D();
                    UseDeviceEx = false;
                }
                catch (Direct3DX9NotFoundException)
                {
                    DirectXStatus = DirectXStatus.Unavailable_MissingDirectX;
                    return;
                }
                catch
                {
                    DirectXStatus = DirectXStatus.Unavailable_Unknown;
                    return;
                }
            }
#endif

            Result result;

            bool ok = Direct3D.CheckDeviceType(0, DeviceType.Hardware, _adapterFormat, _backbufferFormat, true, out result);
            if (!ok)
            {
                //const int D3DERR_NOTAVAILABLE = -2005530518;
                //if (result.Code == D3DERR_NOTAVAILABLE)
                //{
                //   ReleaseDirect3D();
                //   Available = Status.Unavailable_NotReady;
                //   return;
                //}
                ReleaseDirect3D();
                return;
            }

            ok = Direct3D.CheckDepthStencilMatch(0, DeviceType.Hardware, _adapterFormat, _backbufferFormat, _depthStencilFormat, out result);
            if (!ok)
            {
                ReleaseDirect3D();
                return;
            }

            Capabilities deviceCaps = Direct3D.GetDeviceCaps(0, DeviceType.Hardware);
            if ((deviceCaps.DeviceCaps & DeviceCaps.HWTransformAndLight) != 0)
            {
                _createFlags |= CreateFlags.HardwareVertexProcessing;
            }
            else
            {
                _createFlags |= CreateFlags.SoftwareVertexProcessing;
            }

            DirectXStatus = DirectXStatus.Available;
        }
예제 #46
0
        private void SaveRedirection()
        {
            IRedirection redirection           = new Redirection();
            var          redirectionController = new RedirectionController();

            if (RedirectId > Null.NullInteger)
            {
                redirection = redirectionController.GetRedirectionById(ModuleContext.PortalId, RedirectId);
            }

            redirection.Name     = txtRedirectName.Text;
            redirection.Enabled  = chkEnable.Checked;
            redirection.PortalId = ModuleContext.PortalId;
            if (optRedirectSource.SelectedValue == "Tab")
            {
                redirection.SourceTabId      = cboSourcePage.SelectedItemValueAsInt;
                redirection.IncludeChildTabs = chkChildPages.Checked;
            }
            else
            {
                redirection.SourceTabId      = -1;
                redirection.IncludeChildTabs = false;
            }

            redirection.Type = (RedirectionType)Enum.Parse(typeof(RedirectionType), optRedirectType.SelectedValue);
            if (redirection.Type == RedirectionType.SmartPhone && optRedirectType.SelectedValue != "")            //save smart phone value to other type with capability match.
            {
                if (RedirectId > Null.NullInteger)
                {
                    // Delete capabilities that no longer exist in the grid
                    foreach (var rule in redirection.MatchRules)
                    {
                        redirectionController.DeleteRule(ModuleContext.PortalId, redirection.Id, rule.Id);
                    }
                }

                redirection.Type = RedirectionType.Other;
                redirection.MatchRules.Add(new MatchRule()
                {
                    Capability = "IsSmartPhone", Expression = "True"
                });
            }
            else if (redirection.Type == RedirectionType.Other)            //Other, save new capabilities
            {
                if (RedirectId > Null.NullInteger)
                {
                    // Delete capabilities that no longer exist in the grid
                    foreach (var rule in redirection.MatchRules.Where(rule => Capabilities.All(c => c.Id != rule.Id)))
                    {
                        redirectionController.DeleteRule(ModuleContext.PortalId, redirection.Id, rule.Id);
                    }
                }

                redirection.MatchRules = Capabilities;
            }
            else if (RedirectId > Null.NullInteger && redirection.MatchRules.Count > 0)
            {
                foreach (var rule in redirection.MatchRules)
                {
                    redirectionController.DeleteRule(ModuleContext.PortalId, redirection.Id, rule.Id);
                }
            }

            redirection.TargetType = (TargetType)Enum.Parse(typeof(TargetType), optRedirectTarget.SelectedValue);
            switch (redirection.TargetType)
            {
            case TargetType.Portal:
                redirection.TargetValue = cboPortal.SelectedItem.Value;
                break;

            case TargetType.Tab:
                redirection.TargetValue = cboTargetPage.SelectedItemValueAsInt;
                break;

            case TargetType.Url:
                redirection.TargetValue = txtTargetUrl.Text;
                break;
            }

            // Save the redirect
            redirectionController.Save(redirection);
        }
예제 #47
0
        /// <summary>
        /// Converts a incompatible format to a host compatible format, or return the format directly
        /// if it is already host compatible.
        /// </summary>
        /// <remarks>
        /// This can be used to convert a incompatible compressed format to the decompressor
        /// output format.
        /// </remarks>
        /// <param name="info">Texture information</param>
        /// <param name="caps">Host GPU capabilities</param>
        /// <returns>A host compatible format</returns>
        public static FormatInfo ToHostCompatibleFormat(TextureInfo info, Capabilities caps)
        {
            if (!caps.SupportsAstcCompression)
            {
                if (info.FormatInfo.Format.IsAstcUnorm())
                {
                    return(GraphicsConfig.EnableTextureRecompression
                        ? new FormatInfo(Format.Bc7Unorm, 4, 4, 16, 4)
                        : new FormatInfo(Format.R8G8B8A8Unorm, 1, 1, 4, 4));
                }
                else if (info.FormatInfo.Format.IsAstcSrgb())
                {
                    return(GraphicsConfig.EnableTextureRecompression
                        ? new FormatInfo(Format.Bc7Srgb, 4, 4, 16, 4)
                        : new FormatInfo(Format.R8G8B8A8Srgb, 1, 1, 4, 4));
                }
            }

            if (!caps.SupportsR4G4Format && info.FormatInfo.Format == Format.R4G4Unorm)
            {
                return(new FormatInfo(Format.R4G4B4A4Unorm, 1, 1, 2, 4));
            }

            if (!HostSupportsBcFormat(info.FormatInfo.Format, info.Target, caps))
            {
                // The host API does not this compressed format.
                // We assume software decompression will be done for those textures,
                // and so we adjust the format here to match the decompressor output.
                switch (info.FormatInfo.Format)
                {
                case Format.Bc1RgbaSrgb:
                case Format.Bc2Srgb:
                case Format.Bc3Srgb:
                case Format.Bc7Srgb:
                    return(new FormatInfo(Format.R8G8B8A8Srgb, 1, 1, 4, 4));

                case Format.Bc1RgbaUnorm:
                case Format.Bc2Unorm:
                case Format.Bc3Unorm:
                case Format.Bc7Unorm:
                    return(new FormatInfo(Format.R8G8B8A8Unorm, 1, 1, 4, 4));

                case Format.Bc4Unorm:
                    return(new FormatInfo(Format.R8Unorm, 1, 1, 1, 1));

                case Format.Bc4Snorm:
                    return(new FormatInfo(Format.R8Snorm, 1, 1, 1, 1));

                case Format.Bc5Unorm:
                    return(new FormatInfo(Format.R8G8Unorm, 1, 1, 2, 2));

                case Format.Bc5Snorm:
                    return(new FormatInfo(Format.R8G8Snorm, 1, 1, 2, 2));

                case Format.Bc6HSfloat:
                case Format.Bc6HUfloat:
                    return(new FormatInfo(Format.R16G16B16A16Float, 1, 1, 8, 4));
                }
            }

            return(info.FormatInfo);
        }
예제 #48
0
        public KernelResult Initialize(
            ProcessCreationInfo creationInfo,
            ReadOnlySpan <int> capabilities,
            KResourceLimit resourceLimit,
            MemoryRegion memRegion,
            IProcessContextFactory contextFactory,
            ThreadStart customThreadStart = null)
        {
            ResourceLimit      = resourceLimit;
            _memRegion         = memRegion;
            _contextFactory    = contextFactory ?? new ProcessContextFactory();
            _customThreadStart = customThreadStart;
            IsApplication      = creationInfo.Flags.HasFlag(ProcessCreationFlags.IsApplication);

            ulong personalMmHeapSize = GetPersonalMmHeapSize((ulong)creationInfo.SystemResourcePagesCount, memRegion);

            ulong codePagesCount = (ulong)creationInfo.CodePagesCount;

            ulong neededSizeForProcess = personalMmHeapSize + codePagesCount * KPageTableBase.PageSize;

            if (neededSizeForProcess != 0 && resourceLimit != null)
            {
                if (!resourceLimit.Reserve(LimitableResource.Memory, neededSizeForProcess))
                {
                    return(KernelResult.ResLimitExceeded);
                }
            }

            void CleanUpForError()
            {
                if (neededSizeForProcess != 0 && resourceLimit != null)
                {
                    resourceLimit.Release(LimitableResource.Memory, neededSizeForProcess);
                }
            }

            PersonalMmHeapPagesCount = (ulong)creationInfo.SystemResourcePagesCount;

            KMemoryBlockSlabManager slabManager;

            if (PersonalMmHeapPagesCount != 0)
            {
                slabManager = new KMemoryBlockSlabManager(PersonalMmHeapPagesCount * KPageTableBase.PageSize);
            }
            else
            {
                slabManager = creationInfo.Flags.HasFlag(ProcessCreationFlags.IsApplication)
                    ? KernelContext.LargeMemoryBlockSlabManager
                    : KernelContext.SmallMemoryBlockSlabManager;
            }

            AddressSpaceType addrSpaceType = (AddressSpaceType)((int)(creationInfo.Flags & ProcessCreationFlags.AddressSpaceMask) >> (int)ProcessCreationFlags.AddressSpaceShift);

            Pid = KernelContext.NewProcessId();

            if (Pid == -1 || (ulong)Pid < KernelConstants.InitialProcessId)
            {
                throw new InvalidOperationException($"Invalid Process Id {Pid}.");
            }

            InitializeMemoryManager(creationInfo.Flags);

            bool aslrEnabled = creationInfo.Flags.HasFlag(ProcessCreationFlags.EnableAslr);

            ulong codeAddress = creationInfo.CodeAddress;

            ulong codeSize = codePagesCount * KPageTableBase.PageSize;

            KernelResult result = MemoryManager.InitializeForProcess(
                addrSpaceType,
                aslrEnabled,
                !aslrEnabled,
                memRegion,
                codeAddress,
                codeSize,
                slabManager);

            if (result != KernelResult.Success)
            {
                CleanUpForError();

                return(result);
            }

            if (!MemoryManager.CanContain(codeAddress, codeSize, MemoryState.CodeStatic))
            {
                CleanUpForError();

                return(KernelResult.InvalidMemRange);
            }

            result = MemoryManager.MapPages(
                codeAddress,
                codePagesCount,
                MemoryState.CodeStatic,
                KMemoryPermission.None);

            if (result != KernelResult.Success)
            {
                CleanUpForError();

                return(result);
            }

            result = Capabilities.InitializeForUser(capabilities, MemoryManager);

            if (result != KernelResult.Success)
            {
                CleanUpForError();

                return(result);
            }

            result = ParseProcessInfo(creationInfo);

            if (result != KernelResult.Success)
            {
                CleanUpForError();
            }

            return(result);
        }
예제 #49
0
        internal static void DecodeFrame(byte[] frameIn, out FrameData frameData)
        {
            SpinelDecoder mDecoder    = new SpinelDecoder();
            object        ncpResponse = null;

            mDecoder.Init(frameIn);

            byte header = mDecoder.FrameHeader;

            if ((SpinelHeaderFlag & header) != SpinelHeaderFlag)
            {
                throw new SpinelFormatException("Header parsing error.");
            }

            uint   command    = mDecoder.FrameCommand;
            uint   propertyId = mDecoder.FramePropertyId;
            object tempObj    = null;

            switch ((SpinelProperties)propertyId)
            {
            //********************************************************************************
            //
            //          Core properties
            //
            //********************************************************************************

            case SpinelProperties.SPINEL_PROP_NCP_VERSION:
                ncpResponse = mDecoder.ReadUtf8();
                break;

            case SpinelProperties.SPINEL_PROP_LAST_STATUS:
                ncpResponse = mDecoder.ReadUintPacked();
                break;

            case SpinelProperties.SPINEL_PROP_INTERFACE_TYPE:
                ncpResponse = mDecoder.ReadUintPacked();
                break;

            case SpinelProperties.SPINEL_PROP_VENDOR_ID:
                ncpResponse = mDecoder.ReadUintPacked();
                break;

            case SpinelProperties.SPINEL_PROP_PROTOCOL_VERSION:

                tempObj = mDecoder.ReadFields("ii");

                if (tempObj != null)
                {
                    ArrayList protocol = (ArrayList)tempObj;
                    ncpResponse = (uint[])protocol.ToArray(typeof(uint));
                }

                break;

            case SpinelProperties.SPINEL_PROP_CAPS:

                tempObj = mDecoder.ReadFields("A(i)");

                if (tempObj != null)
                {
                    ArrayList      caps      = (ArrayList)tempObj;
                    Capabilities[] capsArray = new Capabilities[caps.Count];
                    int            index     = 0;

                    foreach (var capsValue in caps)
                    {
                        capsArray[index] = (Capabilities)(uint)(capsValue);
                        index++;
                    }

                    ncpResponse = capsArray;
                }

                break;

            //********************************************************************************
            //
            //          Phy properties
            //
            //********************************************************************************
            case SpinelProperties.SPINEL_PROP_PHY_TX_POWER:
                ncpResponse = mDecoder.Readint8();
                break;

            //********************************************************************************
            //
            //          Net properties
            //
            //********************************************************************************

            case SpinelProperties.SPINEL_PROP_NET_NETWORK_NAME:
                ncpResponse = mDecoder.ReadUtf8();
                break;

            case SpinelProperties.SPINEL_PROP_NET_SAVED:
                ncpResponse = mDecoder.ReadBool();
                break;

            case SpinelProperties.SPINEL_PROP_NET_IF_UP:
                ncpResponse = mDecoder.ReadBool();
                break;

            case SpinelProperties.SPINEL_PROP_NET_STACK_UP:
                ncpResponse = mDecoder.ReadBool();
                break;

            case SpinelProperties.SPINEL_PROP_NET_REQUIRE_JOIN_EXISTING:
                ncpResponse = mDecoder.ReadBool();
                break;

            case SpinelProperties.SPINEL_PROP_NET_KEY_SEQUENCE_COUNTER:
                ncpResponse = mDecoder.ReadUint32();
                break;

            case SpinelProperties.SPINEL_PROP_NET_XPANID:
                ncpResponse = mDecoder.ReadData();
                break;

            case SpinelProperties.SPINEL_PROP_NET_ROLE:
                ncpResponse = mDecoder.ReadUint8();
                break;

            case SpinelProperties.SPINEL_PROP_NET_NETWORK_KEY:
                ncpResponse = mDecoder.ReadData();
                break;

            //********************************************************************************
            //
            //          Mac properties
            //
            //********************************************************************************

            case SpinelProperties.SPINEL_PROP_MAC_SCAN_STATE:
                ncpResponse = mDecoder.ReadUint8();
                break;

            case SpinelProperties.SPINEL_PROP_MAC_SCAN_MASK:
                tempObj = mDecoder.ReadFields("A(C)");

                if (tempObj != null)
                {
                    ArrayList channels = (ArrayList)tempObj;
                    ncpResponse = (byte[])channels.ToArray(typeof(byte));
                }

                break;

            case SpinelProperties.SPINEL_PROP_MAC_SCAN_PERIOD:
                ncpResponse = mDecoder.ReadUint16();
                break;

            case SpinelProperties.SPINEL_PROP_MAC_SCAN_BEACON:
                ncpResponse = mDecoder.ReadFields("Cct(ESSC)t(iCUdd)");
                break;

            case SpinelProperties.SPINEL_PROP_MAC_ENERGY_SCAN_RESULT:
                ncpResponse = mDecoder.ReadFields("Cc");
                break;



            case SpinelProperties.SPINEL_PROP_MSG_BUFFER_COUNTERS:

                tempObj = mDecoder.ReadFields("SSSSSSSSSSSSSSSS");

                if (tempObj != null)
                {
                    ArrayList counters = (ArrayList)tempObj;
                    ncpResponse = (ushort[])counters.ToArray(typeof(ushort));
                }

                break;

            case SpinelProperties.SPINEL_PROP_PHY_CHAN:
                ncpResponse = mDecoder.ReadUint8();
                break;

            case SpinelProperties.SPINEL_PROP_PHY_CHAN_SUPPORTED:
                tempObj = mDecoder.ReadFields("A(C)");

                if (tempObj != null)
                {
                    ArrayList channels = (ArrayList)tempObj;
                    ncpResponse = (byte[])channels.ToArray(typeof(byte));
                }

                break;

            case SpinelProperties.SPINEL_PROP_IPV6_ADDRESS_TABLE:

                tempObj = mDecoder.ReadFields("A(t(6CLL))");
                ArrayList ipAddresses = new ArrayList();

                if (tempObj != null)
                {
                    ArrayList addressArray = tempObj as ArrayList;

                    foreach (ArrayList addrInfo in addressArray)
                    {
                        object[]    ipProps = addrInfo.ToArray();
                        IPv6Address ipaddr  = ipProps[0] as IPv6Address;
                        ipAddresses.Add(ipaddr);
                    }
                }

                if (ipAddresses.Count > 0)
                {
                    ncpResponse = ipAddresses.ToArray(typeof(IPv6Address));
                }

                break;

            case SpinelProperties.SPINEL_PROP_MAC_15_4_PANID:
                ncpResponse = mDecoder.ReadUint16();
                break;

            case SpinelProperties.SPINEL_PROP_MCU_POWER_STATE:
                ncpResponse = mDecoder.ReadUint8();
                break;


            case SpinelProperties.SPINEL_PROP_STREAM_NET:
                tempObj = mDecoder.ReadFields("dD");
                if (tempObj != null)
                {
                    ArrayList responseArray = tempObj as ArrayList;
                    ncpResponse = responseArray[0];
                }
                break;

            case SpinelProperties.SPINEL_PROP_IPV6_LL_ADDR:
                IPv6Address ipaddrLL = mDecoder.ReadIp6Address();
                ncpResponse = ipaddrLL;
                break;

            case SpinelProperties.SPINEL_PROP_IPV6_ML_ADDR:
                IPv6Address ipaddrML = mDecoder.ReadIp6Address();
                ncpResponse = ipaddrML;
                break;

            case SpinelProperties.SPINEL_PROP_MAC_15_4_LADDR:
                EUI64 eui64 = mDecoder.ReadEui64();
                ncpResponse = eui64;
                break;

            case SpinelProperties.SPINEL_PROP_HWADDR:
                EUI64 hwaddr = mDecoder.ReadEui64();
                ncpResponse = hwaddr;
                break;

            //case SpinelProperties.SPINEL_PROP_IPV6_ML_PREFIX:
            //    ncpResponse = mDecoder.ReadFields("6C");
            //    break;


            //********************************************************************************
            //
            //          Thread properties
            //
            //********************************************************************************


            case SpinelProperties.SPINEL_PROP_THREAD_CHILD_TABLE:
                tempObj = mDecoder.ReadFields("A(ESLLCCcCc)");
                break;

            case SpinelProperties.SPINEL_PROP_THREAD_NEIGHBOR_TABLE:


                tempObj = mDecoder.ReadFields("A(t(ESLCcCbLLc))");
                break;

            default:
                Console.WriteLine($"Prop id not found in swich {propertyId}.");
                break;
            }

            frameData = new FrameData(mDecoder.FramePropertyId, mDecoder.FrameHeader, mDecoder.GetFrameLoad(), ncpResponse);
        }
예제 #50
0
 /// <summary>
 /// Test hook for overriding the client's capabilities
 /// </summary>
 internal void DisableCapabilities(Capabilities capabilities)
 {
     _clientCapabilities &= ~capabilities;
 }
예제 #51
0
        public static Capabilities  CreateCapabilities(string href)
        {
            #region ServiceIdentification
            LanguageStringType[] titles = new LanguageStringType[]
            {
                new LanguageStringType()
                {
                    Value = "Web Map Tile Service"
                }
            };
            LanguageStringType[] abstracts = new LanguageStringType[]
            {
                new LanguageStringType()
                {
                    Value = "Service that contrains the map access interface to some TileMatrixSets"
                }
            };
            LanguageStringType[] keyword1 = new LanguageStringType[]
            {
                new LanguageStringType()
                {
                    Value = "tile"
                }
            };
            KeywordsType keywordsType1 = new KeywordsType()
            {
                Keyword = keyword1
            };
            LanguageStringType[] keyword2 = new LanguageStringType[]
            {
                new LanguageStringType()
                {
                    Value = "map"
                }
            };
            KeywordsType keywordsType2 = new KeywordsType()
            {
                Keyword = keyword2
            };
            KeywordsType[] keywords = new KeywordsType[]
            {
                keywordsType1, keywordsType2
            };
            CodeType serviceType = new CodeType()
            {
                Value = "OGC WMTS"
            };
            string[] serviceTypeVersion = new string[]
            {
                "1.0.0"
            };
            string   fees = "none";
            string[] accessConstraints = new string[]
            {
                "none"
            };
            ServiceIdentification serviceIdentification = new ServiceIdentification()
            {
                Title              = titles,
                Abstract           = abstracts,
                Keywords           = keywords,
                ServiceType        = serviceType,
                ServiceTypeVersion = serviceTypeVersion,
                Fees = fees,
                AccessConstraints = accessConstraints
            };
            #endregion

            #region ServiceProvider
            string             poroviderName    = "SharpMapServer";
            OnlineResourceType providerSiteType = new OnlineResourceType()
            {
                href = href
            };
            string[]      voices     = new string[] { "0000-00000000" };
            string[]      facsimiles = new string[] { "0001-00000001" };
            TelephoneType phone      = new TelephoneType()
            {
                Voice     = voices,
                Facsimile = facsimiles
            };
            string[]    deliveryPoints        = new string[] { "jinjiang" };
            string      city                  = "chengdu";
            string      administrativeArea    = "sichuan";
            string      country               = "china";
            string[]    electronicMailAddress = new string[] { "*****@*****.**" };
            string      postalCode            = "123456";
            AddressType address               = new AddressType()
            {
                DeliveryPoint         = deliveryPoints,
                City                  = city,
                AdministrativeArea    = administrativeArea,
                Country               = country,
                ElectronicMailAddress = electronicMailAddress,
                PostalCode            = postalCode
            };
            ContactType contactInfo = new ContactType()
            {
                Phone   = phone,
                Address = address
            };
            string individualName = "lc";
            string positionName   = "Senior Software Engineer";
            ResponsiblePartySubsetType serviceContact = new ResponsiblePartySubsetType()
            {
                IndividualName = individualName,
                PositionName   = positionName,
                ContactInfo    = contactInfo
            };
            ServiceProvider serviceProvider = new ServiceProvider()
            {
                ProviderName   = poroviderName,
                ProviderSite   = providerSiteType,
                ServiceContact = serviceContact
            };
            #endregion

            #region OperationsMetadata
            Operation   getCapabilitiesOperation = CapabilitiesHelper.GetOperation(href, "GetCapabilities");
            Operation   getTileOperation         = CapabilitiesHelper.GetOperation(href, "GetTile");
            Operation   getFeatureinfoOperation  = CapabilitiesHelper.GetOperation(href, "GetFeatureinfo");
            Operation[] operations = new Operation[]
            {
                getCapabilitiesOperation,
                getTileOperation,
                getFeatureinfoOperation
            };
            OperationsMetadata operationsMetadata = new OperationsMetadata()
            {
                Operation = operations
            };
            #endregion

            Capabilities capabilities = new Capabilities()
            {
                ServiceIdentification = serviceIdentification,
                ServiceProvider       = serviceProvider,
                OperationsMetadata    = operationsMetadata
            };
            return(capabilities);
        }
 internal XRObjectTrackingSubsystemDescriptor(string id, Type implementationType, Capabilities capabilities)
 {
     this.id = id;
     this.subsystemImplementationType = implementationType;
     this.capabilities = capabilities;
 }
 /// <summary>
 ///    Returns true if the current hardware supports the requested feature.
 /// </summary>
 /// <param name="cap">Feature to query (i.e. Dot3 bump mapping)</param>
 /// <returns></returns>
 public bool CheckCap(Capabilities cap)
 {
     return (caps & cap) > 0;
 }
예제 #54
0
        /// <summary>
        /// Gets a texture creation information from texture information.
        /// This can be used to create new host textures.
        /// </summary>
        /// <param name="info">Texture information</param>
        /// <param name="caps">GPU capabilities</param>
        /// <param name="scale">Texture scale factor, to be applied to the texture size</param>
        /// <returns>The texture creation information</returns>
        public static TextureCreateInfo GetCreateInfo(TextureInfo info, Capabilities caps, float scale)
        {
            FormatInfo formatInfo = TextureCompatibility.ToHostCompatibleFormat(info, caps);

            if (info.Target == Target.TextureBuffer)
            {
                // We assume that the host does not support signed normalized format
                // (as is the case with OpenGL), so we just use a unsigned format.
                // The shader will need the appropriate conversion code to compensate.
                switch (formatInfo.Format)
                {
                case Format.R8Snorm:
                    formatInfo = new FormatInfo(Format.R8Sint, 1, 1, 1, 1);
                    break;

                case Format.R16Snorm:
                    formatInfo = new FormatInfo(Format.R16Sint, 1, 1, 2, 1);
                    break;

                case Format.R8G8Snorm:
                    formatInfo = new FormatInfo(Format.R8G8Sint, 1, 1, 2, 2);
                    break;

                case Format.R16G16Snorm:
                    formatInfo = new FormatInfo(Format.R16G16Sint, 1, 1, 4, 2);
                    break;

                case Format.R8G8B8A8Snorm:
                    formatInfo = new FormatInfo(Format.R8G8B8A8Sint, 1, 1, 4, 4);
                    break;

                case Format.R16G16B16A16Snorm:
                    formatInfo = new FormatInfo(Format.R16G16B16A16Sint, 1, 1, 8, 4);
                    break;
                }
            }

            int width  = info.Width / info.SamplesInX;
            int height = info.Height / info.SamplesInY;

            int depth = info.GetDepth() * info.GetLayers();

            if (scale != 1f)
            {
                width  = (int)MathF.Ceiling(width * scale);
                height = (int)MathF.Ceiling(height * scale);
            }

            return(new TextureCreateInfo(
                       width,
                       height,
                       depth,
                       info.Levels,
                       info.Samples,
                       formatInfo.BlockWidth,
                       formatInfo.BlockHeight,
                       formatInfo.BytesPerPixel,
                       formatInfo.Format,
                       info.DepthStencilMode,
                       info.Target,
                       info.SwizzleR,
                       info.SwizzleG,
                       info.SwizzleB,
                       info.SwizzleA));
        }
        /// <summary>
        /// constructor
        /// </summary>
        internal SmbServerConnection()
        {
            this.requestList = new Dictionary<ushort, SmbPacket>();
            this.sessionTable = new Collection<SmbServerSession>();
            this.serverSendSequenceNumber = new Dictionary<ServerSendSequenceNumberKey, uint>();

            // on initialize, ServerNextReceiveSequenceNumber is set to the following value.
            this.serverNextReceiveSequenceNumber = 2;

            // Windows clients and servers expect 8-byte encryption keys.
            this.ntlmEncryptionKey = new byte[8];

            this.isSigningActive = true;
            this.clientCapabilities = (Capabilities)0;

            this.serverCapabilities = Capabilities.CAP_EXTENDED_SECURITY | Capabilities.CAP_LWIO
                | Capabilities.CAP_LARGE_READX | Capabilities.CAP_LARGE_WRITE | Capabilities.CAP_INFOLEVEL_PASSTHRU
                | Capabilities.CAP_NT_FIND | Capabilities.CAP_LOCK_AND_READ | Capabilities.CAP_LEVEL_II_OPLOCKS
                | Capabilities.CAP_STATUS32 | Capabilities.CAP_RPC_REMOTE_APIS | Capabilities.CAP_NT_SMBS
                | Capabilities.CAP_LARGE_FILES | Capabilities.CAP_UNICODE;

            this.capability = new SmbServerCapability();
        }
예제 #56
0
        /// <summary>
        /// Reads information from WMAppManifest.xml.
        /// </summary>
        /// <returns></returns>
        public bool Read()
        {
            if (_fileName == null)
            {
                throw new Exception("File name is empty");
            }
            GenerateTempFolder();
            UpdateView();
            //Cleanup();

            error = XapReadError.NotRead;

            string TempFileName     = _fileName;
            bool   deleteFile       = false;
            IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();

            XDocument reader = null;

            StreamResourceInfo xapStream = null;

            try
            {
                if (TempFileName.Contains("\\"))
                {
                    string shortname = _fileName.Substring(_fileName.LastIndexOf("\\") + 1).Replace("%20", " ");
                    if (shortname.Contains(" "))
                    {
                        bool res = Functions.CopyFile(_fileName, "\\Temp\\temp.xap");
                        if (res == false)
                        {
                            error = XapReadError.CouldNotCopyFile;
                            throw new Exception("Could not copy file");
                        }
                        TempFileName = "\\Temp\\temp.xap";
                        deleteFile   = true;
                    }
                }
                var uri = new Uri(TempFileName, UriKind.Relative);
                xapStream = Application.GetResourceStream(uri);
                if (xapStream == null)
                {
                    error = XapReadError.OpenError;
                    throw new Exception("Couldn't read XAP");
                }
                _fileSize = xapStream.Stream.Length;

                // Input WMAppManifest not always has valid encoding. Let's try different ones to find the best.
                var stream = Application.GetResourceStream(xapStream, new Uri("WMAppManifest.xml", UriKind.Relative)).Stream;
                if (stream == null)
                {
                    error = XapReadError.CouldNotOpenWMAppManifest;
                    throw new Exception("Couldn't open WMAppManifest");
                }
                byte[] bytes = new byte[stream.Length];
                stream.Read(bytes, 0, bytes.Length);
                stream.Close();
                stream = null;
                var encodings = new System.Text.Encoding[3] {
                    Encoding.UTF8, Encoding.Unicode, Encoding.BigEndianUnicode
                };
                bool correctEncodingFound = false;
                for (int i = 0; i < encodings.Length; ++i)
                {
                    try
                    {
                        Encoding enc  = encodings[i];
                        string   text = enc.GetString(bytes, 0, bytes.Length);
                        text = text.Replace("utf-16", "utf-8");
                        byte[] newBytes = Encoding.UTF8.GetBytes(text);

                        var memStream = new MemoryStream(newBytes);
                        reader = XDocument.Load(memStream);
                        memStream.Close();
                        memStream = null;
                    }
                    catch (Exception ex)
                    {
                        continue;
                    }
                    correctEncodingFound = true;
                    break;
                }
                if (!correctEncodingFound)
                {
                    error = XapReadError.InvalidEncoding;
                    throw new Exception("Invalid WMAppManifest.xml encoding");
                }
            }
            catch (Exception ex)
            {
                if (error == XapReadError.NotRead)
                {
                    error = XapReadError.OpenError;
                }
                if (deleteFile == true)
                {
                    Functions.RemoveFile(TempFileName);
                }
                UpdateView();
                return(false);
            }
            _isSigned = false;
            try
            {
                var rs = Application.GetResourceStream(xapStream, new Uri("WMAppPRHeader.xml", UriKind.Relative));
                if (rs != null)
                {
                    _isSigned = true;
                    rs.Stream.Close();
                }
            }
            catch (Exception ex)
            {
                _isSigned = false;
            }
            var  nodes          = reader.Descendants().Descendants <XElement>();
            bool AppNodeFound   = false;
            bool ProductIdFound = false;

            foreach (var node in nodes)
            {
                string uri = node.BaseUri;
                if (node.Name.LocalName == "App")
                {
                    AppNodeFound = true;

                    var attrs = node.Attributes();
                    foreach (var attr in attrs)
                    {
                        switch (attr.Name.LocalName)
                        {
                        case "ProductID":
                            _productId     = attr.Value;
                            ProductIdFound = true;
                            break;

                        case "Title":
                            _title = attr.Value;
                            break;

                        case "Version":
                            _version = attr.Value;
                            break;

                        case "Author":
                            _author = attr.Value;
                            break;

                        case "Description":
                            _description = attr.Value;
                            break;

                        case "Publisher":
                            _publisher = attr.Value;
                            break;

                        case "Genre":
                            _genre = attr.Value;
                            break;
                        }
                    }

                    _title       = ExtractResourceString(xapStream, _title);
                    _version     = ExtractResourceString(xapStream, _version);
                    _author      = ExtractResourceString(xapStream, _author);
                    _description = ExtractResourceString(xapStream, _description);
                    _publisher   = ExtractResourceString(xapStream, _publisher);

                    var elems = node.Elements();
                    foreach (var elem in elems)
                    {
                        switch (elem.Name.LocalName)
                        {
                        case "IconPath":
                            _applicationIcon = elem.Value;
                            if (ExtractFile(xapStream, isf, _applicationIcon) == true)
                            {
                                string shortFileName = ShortenFileName(_applicationIcon);
                                _applicationIcon = shortFileName;
                            }
                            break;

                        case "Capabilities":
                            var caps = elem.Elements();
                            foreach (var cap in caps)
                            {
                                Capabilities.Add(cap.Attribute("Name").Value);
                            }
                            break;
                        }
                    }
                }
            }
            xapStream.Stream.Close();
            xapStream.Stream.Dispose();
            xapStream = null;
            reader    = null;


            if (!AppNodeFound)
            {
                error = XapReadError.NoAppElement;
            }
            else if (!ProductIdFound)
            {
                error = XapReadError.NoProductId;
            }
            if (error == XapReadError.NotRead)
            {
                error = XapReadError.Success;
            }

            if (deleteFile == true)
            {
                Functions.RemoveFile(TempFileName);
            }
            UpdateView();
            return(true);
        }
        /// <summary>
        /// Create session setup request packet. Using the Extended Session Security mechanism. This is the long 
        /// parameter packet Api for creating all Extended Security authenticate packet. 
        /// </summary>
        /// <param name = "messageId">the id of message, used to identity the request and the server response. </param>
        /// <param name = "sessionUid">
        /// Set this value to 0 to request a new session setup, or set this value to a previously established session  
        /// identifier to request reauthenticating an existing session. 
        /// </param>
        /// <param name = "flags">
        /// The Flags field contains individual flags, as specified in [CIFS] sections 2.4.2 and 3.1.1. 
        /// </param>
        /// <param name = "flags2">
        /// The Flags2 field contains individual bit flags that, depending on the negotiated SMB dialect, indicate   
        /// various client and server capabilities. 
        /// </param>
        /// <param name = "capabilities">
        /// A set of client capabilities. These flags are a subset of those specified in section for the server   
        /// capabilities returned in the SMB_COM_NEGOTIATE response. 
        /// </param>
        /// <param name = "maxBufferSize">
        /// The maximum size, in bytes, of the client buffer for sending and receiving SMB messages. 
        /// </param>
        /// <param name = "securityPackage">the package name of security. </param>
        /// <param name = "serverName">the server name to authenticate </param>
        /// <param name = "domainName">the domain name of user credential </param>
        /// <param name = "userName">the name of user credential </param>
        /// <param name = "password">the password of user credential </param>
        /// <returns>A session setup packet. </returns>
        /// <exception cref = "InvalidOperationException">the ExtendedSessionSecurity must set to 1 </exception>
        private SmbSessionSetupAndxRequestPacket CreateSessionSetupRequest(
            ushort messageId,
            ushort sessionUid,
            SmbHeader_Flags_Values flags,
            SmbHeader_Flags2_Values flags2,
            Capabilities capabilities,
            ushort maxBufferSize,
            SmbSecurityPackage securityPackage,
            string serverName,
            string domainName,
            string userName,
            string password)
        {
            if (!Capability.IsSupportsExtendedSecurity)
            {
                throw new InvalidOperationException("the ExtendedSessionSecurity must set to 1");
            }

            SmbSessionSetupAndxRequestPacket packet = new SmbSessionSetupAndxRequestPacket();

            // create smb packet header
            packet.SmbHeader = CifsMessageUtils.CreateSmbHeader(
                SmbCommand.SMB_COM_SESSION_SETUP_ANDX, messageId, sessionUid, 0, (SmbFlags)flags, (SmbFlags2)flags2);

            // update smb parameters
            SMB_COM_SESSION_SETUP_ANDX_Request_SMB_Parameters smbParameters = packet.SmbParameters;

            smbParameters.MaxBufferSize = maxBufferSize;
            smbParameters.Capabilities = (uint)capabilities;

            // update smb data
            SMB_COM_SESSION_SETUP_ANDX_Request_SMB_Data smbData = packet.SmbData;

            #region Generate the security blob, using Negotiate, Kerberos or Ntlm

            // get the default connection
            SmbClientConnection connection =
                this.Context.GetConnection(this.ConnectionId) as SmbClientConnection;
            if (connection == null)
            {
                return null;
            }

            // initialize gss api.
            if (connection.GssApi == null)
            {
                string serverPrincipal = GSS_API_TARGET_NAME_PREFIX + serverName;

                switch (securityPackage)
                {
                    case SmbSecurityPackage.NTLM:
                        connection.GssApi = new NlmpClientSecurityContext(
                            new NlmpClientCredential(serverPrincipal, domainName, userName, password));
                        break;

                    case SmbSecurityPackage.Kerberos:
                        connection.GssApi = new SspiClientSecurityContext(
                            SecurityPackageType.Kerberos,
                            new AccountCredential(domainName, userName, password),
                            serverPrincipal, ClientSecurityContextAttribute.Connection,
                            SecurityTargetDataRepresentation.SecurityNetworkDrep);
                        break;

                    default:
                        connection.GssApi = new SspiClientSecurityContext(
                            SecurityPackageType.Negotiate,
                            new AccountCredential(domainName, userName, password),
                            serverPrincipal, ClientSecurityContextAttribute.Connection,
                            SecurityTargetDataRepresentation.SecurityNetworkDrep);
                        break;
                }
            }

            // initialize the token.
            // if ntlm, this is used to generate the negotiate and authenticate token.
            // if kerberos, this is used to generate the token which is sent to server.
            connection.GssApi.Initialize(connection.SecurityBlob);

            // update connection
            this.Context.AddOrUpdateConnection(connection);

            // store token to security blob of packet
            byte[] securityBlob = connection.GssApi.Token;
            smbParameters.SecurityBlobLength = (ushort)securityBlob.Length;
            smbData.SecurityBlob = new byte[securityBlob.Length];
            Array.Copy(securityBlob, smbData.SecurityBlob, securityBlob.Length);

            #endregion

            // initialize default values
            smbData.Pad = new byte[0];
            if (Capability.IsUnicode && smbParameters.SecurityBlobLength % SmbCapability.TWO_BYTES_ALIGN == 0)
            {
                smbData.Pad = new byte[1];
            }
            // null terminate.
            smbData.NativeOS = new byte[2];
            smbData.NativeLanMan = new byte[2];

            // update smbData.ByteCount
            smbData.ByteCount = 0;
            if (smbData.SecurityBlob != null)
            {
                smbData.ByteCount += (ushort)smbData.SecurityBlob.Length;
            }
            if (smbData.Pad != null)
            {
                smbData.ByteCount += (ushort)smbData.Pad.Length;
            }
            if (smbData.NativeOS != null)
            {
                smbData.ByteCount += (ushort)smbData.NativeOS.Length;
            }
            if (smbData.NativeLanMan != null)
            {
                smbData.ByteCount += (ushort)smbData.NativeLanMan.Length;
            }

            // store the parameters and data to packet.
            packet.SmbParameters = smbParameters;
            packet.SmbData = smbData;

            // upate context
            this.Context.SetSecurityPackage(securityPackage);

            return packet;
        }
예제 #58
0
        public KernelResult Initialize(
            ProcessCreationInfo creationInfo,
            int[]               caps,
            KResourceLimit resourceLimit,
            MemoryRegion memRegion)
        {
            ResourceLimit = resourceLimit;
            _memRegion    = memRegion;

            ulong personalMmHeapSize = GetPersonalMmHeapSize((ulong)creationInfo.PersonalMmHeapPagesCount, memRegion);

            ulong codePagesCount = (ulong)creationInfo.CodePagesCount;

            ulong neededSizeForProcess = personalMmHeapSize + codePagesCount * KMemoryManager.PageSize;

            if (neededSizeForProcess != 0 && resourceLimit != null)
            {
                if (!resourceLimit.Reserve(LimitableResource.Memory, neededSizeForProcess))
                {
                    return(KernelResult.ResLimitExceeded);
                }
            }

            void CleanUpForError()
            {
                if (neededSizeForProcess != 0 && resourceLimit != null)
                {
                    resourceLimit.Release(LimitableResource.Memory, neededSizeForProcess);
                }
            }

            PersonalMmHeapPagesCount = (ulong)creationInfo.PersonalMmHeapPagesCount;

            KMemoryBlockAllocator memoryBlockAllocator;

            if (PersonalMmHeapPagesCount != 0)
            {
                memoryBlockAllocator = new KMemoryBlockAllocator(PersonalMmHeapPagesCount * KMemoryManager.PageSize);
            }
            else
            {
                memoryBlockAllocator = (MmuFlags & 0x40) != 0
                    ? System.LargeMemoryBlockAllocator
                    : System.SmallMemoryBlockAllocator;
            }

            AddressSpaceType addrSpaceType = (AddressSpaceType)((creationInfo.MmuFlags >> 1) & 7);

            InitializeMemoryManager(addrSpaceType, memRegion);

            bool aslrEnabled = ((creationInfo.MmuFlags >> 5) & 1) != 0;

            ulong codeAddress = creationInfo.CodeAddress;

            ulong codeSize = codePagesCount * KMemoryManager.PageSize;

            KernelResult result = MemoryManager.InitializeForProcess(
                addrSpaceType,
                aslrEnabled,
                !aslrEnabled,
                memRegion,
                codeAddress,
                codeSize,
                memoryBlockAllocator);

            if (result != KernelResult.Success)
            {
                CleanUpForError();

                return(result);
            }

            if (!ValidateCodeAddressAndSize(codeAddress, codeSize))
            {
                CleanUpForError();

                return(KernelResult.InvalidMemRange);
            }

            result = MemoryManager.MapNewProcessCode(
                codeAddress,
                codePagesCount,
                MemoryState.CodeStatic,
                MemoryPermission.None);

            if (result != KernelResult.Success)
            {
                CleanUpForError();

                return(result);
            }

            result = Capabilities.InitializeForUser(caps, MemoryManager);

            if (result != KernelResult.Success)
            {
                CleanUpForError();

                return(result);
            }

            Pid = System.GetProcessId();

            if (Pid == -1 || (ulong)Pid < Horizon.InitialProcessId)
            {
                throw new InvalidOperationException($"Invalid Process Id {Pid}.");
            }

            result = ParseProcessInfo(creationInfo);

            if (result != KernelResult.Success)
            {
                CleanUpForError();
            }

            return(result);
        }
예제 #59
0
        public KernelResult InitializeKip(
            ProcessCreationInfo creationInfo,
            int[]               caps,
            KPageList pageList,
            KResourceLimit resourceLimit,
            MemoryRegion memRegion)
        {
            ResourceLimit = resourceLimit;
            _memRegion    = memRegion;

            AddressSpaceType addrSpaceType = (AddressSpaceType)((creationInfo.MmuFlags >> 1) & 7);

            InitializeMemoryManager(addrSpaceType, memRegion);

            bool aslrEnabled = ((creationInfo.MmuFlags >> 5) & 1) != 0;

            ulong codeAddress = creationInfo.CodeAddress;

            ulong codeSize = (ulong)creationInfo.CodePagesCount * KMemoryManager.PageSize;

            KMemoryBlockAllocator memoryBlockAllocator = (MmuFlags & 0x40) != 0
                ? System.LargeMemoryBlockAllocator
                : System.SmallMemoryBlockAllocator;

            KernelResult result = MemoryManager.InitializeForProcess(
                addrSpaceType,
                aslrEnabled,
                !aslrEnabled,
                memRegion,
                codeAddress,
                codeSize,
                memoryBlockAllocator);

            if (result != KernelResult.Success)
            {
                return(result);
            }

            if (!ValidateCodeAddressAndSize(codeAddress, codeSize))
            {
                return(KernelResult.InvalidMemRange);
            }

            result = MemoryManager.MapPages(
                codeAddress,
                pageList,
                MemoryState.CodeStatic,
                MemoryPermission.None);

            if (result != KernelResult.Success)
            {
                return(result);
            }

            result = Capabilities.InitializeForKernel(caps, MemoryManager);

            if (result != KernelResult.Success)
            {
                return(result);
            }

            Pid = System.GetKipId();

            if (Pid == 0 || (ulong)Pid >= Horizon.InitialProcessId)
            {
                throw new InvalidOperationException($"Invalid KIP Id {Pid}.");
            }

            result = ParseProcessInfo(creationInfo);

            return(result);
        }
예제 #60
0
        /// <summary>
        /// Checks if the view format of the first texture format is compatible with the format of the second.
        /// In general, the formats are considered compatible if the bytes per pixel values are equal,
        /// but there are more complex rules for some formats, like compressed or depth-stencil formats.
        /// This follows the host API copy compatibility rules.
        /// </summary>
        /// <param name="lhs">Texture information of the texture view</param>
        /// <param name="rhs">Texture information of the texture view</param>
        /// <param name="caps">Host GPU capabilities</param>
        /// <returns>The view compatibility level of the texture formats</returns>
        public static TextureViewCompatibility ViewFormatCompatible(TextureInfo lhs, TextureInfo rhs, Capabilities caps)
        {
            if (FormatCompatible(lhs, rhs, caps))
            {
                if (lhs.FormatInfo.IsCompressed != rhs.FormatInfo.IsCompressed)
                {
                    return(TextureViewCompatibility.CopyOnly);
                }
                else
                {
                    return(TextureViewCompatibility.Full);
                }
            }

            return(TextureViewCompatibility.Incompatible);
        }