public NativeMethodOverload(ICollection<MethodInfo> methods , JsObject prototype, IGlobal global) : base(prototype) { if (global == null) throw new ArgumentNullException("global"); m_marshaller = global.Marshaller; foreach (MethodInfo info in methods) { Name = info.Name; break; } foreach (var method in methods) { if (method.IsGenericMethodDefinition) m_generics.AddLast(method); else if (! method.ContainsGenericParameters) m_methods.AddLast(method); } m_overloads = new NativeOverloadImpl<MethodInfo, JsMethodImpl>( m_marshaller, new NativeOverloadImpl<MethodInfo, JsMethodImpl>.GetMembersDelegate(this.GetMembers), new NativeOverloadImpl<MethodInfo, JsMethodImpl>.WrapMmemberDelegate(this.WrapMember) ); }
public void Init() { var marshaller = new Marshaller<string>( (str) => { if (str == "UNSERIALIZABLE_VALUE") { // Google.Protobuf throws exception inherited from IOException throw new IOException("Error serializing the message."); } return System.Text.Encoding.UTF8.GetBytes(str); }, (payload) => { var s = System.Text.Encoding.UTF8.GetString(payload); if (s == "UNPARSEABLE_VALUE") { // Google.Protobuf throws exception inherited from IOException throw new IOException("Error parsing the message."); } return s; }); helper = new MockServiceHelper(Host, marshaller); server = helper.GetServer(); server.Start(); channel = helper.GetChannel(); }
/// <summary> /// Initializes a new instance of the <see cref="Apache.Ignite.Core.Impl.DataStructures.AtomicLong"/> class. /// </summary> /// <param name="target">The target.</param> /// <param name="marsh">The marshaller.</param> /// <param name="name">The name.</param> public AtomicSequence(IUnmanagedTarget target, Marshaller marsh, string name) : base(target, marsh) { Debug.Assert(!string.IsNullOrEmpty(name)); _name = name; }
public void TestStructure() { for (int i = 1; i <= RepeatCnt; i++) { Console.WriteLine(">>> Iteration started: " + i); // 1. Generate and shuffle objects. IList<BranchedType> objs = new List<BranchedType>(); for (int j = 0; j < 6 * ObjectsPerMode; j++) objs.Add(new BranchedType((j%6) + 1)); objs = IgniteUtils.Shuffle(objs); // 2. Create new marshaller. BinaryTypeConfiguration typeCfg = new BinaryTypeConfiguration(typeof(BranchedType)); BinaryConfiguration cfg = new BinaryConfiguration { TypeConfigurations = new List<BinaryTypeConfiguration> { typeCfg } }; Marshaller marsh = new Marshaller(cfg); // 3. Marshal all data and ensure deserialized object is fine. // Use single stream to test object offsets using (var stream = new BinaryHeapStream(128)) { var writer = marsh.StartMarshal(stream); foreach (var obj in objs) { Console.WriteLine(">>> Write object [mode=" + obj.mode + ']'); writer.WriteObject(obj); } stream.Seek(0, SeekOrigin.Begin); var reader = marsh.StartUnmarshal(stream); foreach (var obj in objs) { var other = reader.ReadObject<BranchedType>(); Assert.IsTrue(obj.Equals(other)); } } Console.WriteLine(); // 4. Ensure that all fields are recorded. var desc = marsh.GetDescriptor(typeof (BranchedType)); CollectionAssert.AreEquivalent(new[] {"mode", "f2", "f3", "f4", "f5", "f6", "f7", "f8"}, desc.WriterTypeStructure.FieldTypes.Keys); } }
/// <summary> /// Reads the schema according to this header data. /// </summary> /// <param name="stream">The stream.</param> /// <param name="position">The position.</param> /// <param name="hdr">The header.</param> /// <param name="schema">The schema.</param> /// <param name="marsh">The marshaller.</param> /// <returns> /// Schema. /// </returns> public static BinaryObjectSchemaField[] ReadSchema(IBinaryStream stream, int position, BinaryObjectHeader hdr, BinaryObjectSchema schema, Marshaller marsh) { Debug.Assert(stream != null); Debug.Assert(schema != null); Debug.Assert(marsh != null); return ReadSchema(stream, position, hdr, () => GetFieldIds(hdr, schema, marsh)); }
/// <summary> /// Creates a message sender. /// </summary> /// <param name="serverAddress">The address of server that messages will be send to.</param> public MessageSender(IPEndPoint serverAddress) { _servers = new List<ServerInfo>(); _tcpClient = new TcpClient(serverAddress); var validator = new MessageValidator(); var serializer = new MessageSerializer(); _marshaller = new Marshaller(serializer, validator); }
/// <summary> /// Initializes a new instance of the <see cref="BinarizableWriteBenchmark"/> class. /// </summary> public BinarizableWriteBenchmark() { _marsh = new Marshaller(new BinaryConfiguration { TypeConfigurations = new List<BinaryTypeConfiguration> { new BinaryTypeConfiguration(typeof (Address)) //new BinaryTypeConfiguration(typeof (TestModel)) } }); }
/// <summary> /// Initializes a new instance of the <see cref="CacheEntryFilterHolder" /> class. /// </summary> /// <param name="pred">The <see cref="ICacheEntryFilter{TK,TV}" /> to wrap.</param> /// <param name="invoker">The invoker func that takes key and value and invokes wrapped ICacheEntryFilter.</param> /// <param name="marsh">Marshaller.</param> /// <param name="keepBinary">Keep binary flag.</param> public CacheEntryFilterHolder(object pred, Func<object, object, bool> invoker, Marshaller marsh, bool keepBinary) { Debug.Assert(pred != null); Debug.Assert(invoker != null); Debug.Assert(marsh != null); _pred = pred; _invoker = invoker; _marsh = marsh; _keepBinary = keepBinary; }
/// <summary> /// Writes this instance to the stream. /// </summary> /// <param name="stream">Stream.</param> /// <param name="marsh">Marshaller.</param> public void Write(IBinaryStream stream, Marshaller marsh) { var writer = marsh.StartMarshal(stream); try { Marshal(writer); } finally { marsh.FinishMarshal(writer); } }
public JsFunctionDelegate(IJintVisitor visitor, JsFunction function, JsDictionaryObject that,Type delegateType) { if (visitor == null) throw new ArgumentNullException("visitor"); if (function == null) throw new ArgumentNullException("function"); if (delegateType == null) throw new ArgumentNullException("delegateType"); if (!typeof(Delegate).IsAssignableFrom(delegateType)) throw new ArgumentException("A delegate type is required", "delegateType"); m_visitor = visitor; m_function = function; m_delegateType = delegateType; m_that = that; m_marshaller = visitor.Global.Marshaller; }
public void TestStructure() { for (int i = 1; i <= RepeatCnt; i++) { Console.WriteLine(">>> Iteration started: " + i); // 1. Generate and shuffle objects. IList<BranchedType> objs = new List<BranchedType>(); for (int j = 0; j < 6 * ObjectsPerMode; j++) objs.Add(new BranchedType((j%6) + 1)); objs = IgniteUtils.Shuffle(objs); // 2. Create new marshaller. BinaryTypeConfiguration typeCfg = new BinaryTypeConfiguration(typeof(BranchedType)); BinaryConfiguration cfg = new BinaryConfiguration { TypeConfigurations = new List<BinaryTypeConfiguration> { typeCfg } }; Marshaller marsh = new Marshaller(cfg); // 3. Marshal all data and ensure deserialized object is fine. foreach (BranchedType obj in objs) { Console.WriteLine(">>> Write object [mode=" + obj.mode + ']'); byte[] data = marsh.Marshal(obj); BranchedType other = marsh.Unmarshal<BranchedType>(data); Assert.IsTrue(obj.Equals(other)); } Console.WriteLine(); // 4. Ensure that all fields are recorded. var desc = marsh.GetDescriptor(typeof (BranchedType)); CollectionAssert.AreEquivalent(new[] {"mode", "f2", "f3", "f4", "f5", "f6", "f7", "f8"}, desc.WriterTypeStructure.FieldTypes.Keys); } }
public NativeIndexer(Marshaller marshaller, MethodInfo[] getters, MethodInfo[] setters) { m_getOverload = new NativeOverloadImpl<MethodInfo, JsIndexerGetter>( marshaller, delegate(Type[] genericArgs, int Length) { return Array.FindAll<MethodInfo>(getters, mi => mi.GetParameters().Length == Length); }, new NativeOverloadImpl<MethodInfo, JsIndexerGetter>.WrapMmemberDelegate(marshaller.WrapIndexerGetter) ); m_setOverload = new NativeOverloadImpl<MethodInfo, JsIndexerSetter>( marshaller, delegate(Type[] genericArgs, int Length) { return Array.FindAll<MethodInfo>(setters, mi => mi.GetParameters().Length == Length); }, new NativeOverloadImpl<MethodInfo,JsIndexerSetter>.WrapMmemberDelegate(marshaller.WrapIndexerSetter) ); }
/// <summary> /// Initializes a new instance of the <see cref="BinarizableReadBenchmark"/> class. /// </summary> public BinarizableReadBenchmark() { _marsh = new Marshaller(new BinaryConfiguration { TypeConfigurations = new List<BinaryTypeConfiguration> { new BinaryTypeConfiguration(typeof (Address)), new BinaryTypeConfiguration(typeof (TestModel)) } }); _mem = _memMgr.Allocate(); var stream = _mem.GetStream(); //_marsh.StartMarshal(stream).Write(_model); _marsh.StartMarshal(stream).Write(_address); stream.SynchronizeOutput(); }
public void TestCustomPosition() { var stream = new BinaryHeapStream(16); stream.WriteLong(54); var marsh = new Marshaller(new BinaryConfiguration()); var writer = new BinaryWriter(marsh, stream); writer.WriteChar('x'); stream.Seek(0, SeekOrigin.Begin); Assert.AreEqual(54, stream.ReadLong()); var reader = new BinaryReader(marsh, stream, BinaryMode.Deserialize, null); Assert.AreEqual('x', reader.ReadChar()); }
/// <summary> /// Reads proxy method invocation data from the specified reader. /// </summary> /// <param name="stream">Stream.</param> /// <param name="marsh">Marshaller.</param> /// <param name="mthdName">Method name.</param> /// <param name="mthdArgs">Method arguments.</param> public static void ReadProxyMethod(IBinaryStream stream, Marshaller marsh, out string mthdName, out object[] mthdArgs) { var reader = marsh.StartUnmarshal(stream); var srvKeepBinary = reader.ReadBoolean(); mthdName = reader.ReadString(); if (reader.ReadBoolean()) { mthdArgs = new object[reader.ReadInt()]; if (srvKeepBinary) reader = marsh.StartUnmarshal(stream, true); for (var i = 0; i < mthdArgs.Length; i++) mthdArgs[i] = reader.ReadObject<object>(); } else mthdArgs = null; }
/// <summary> /// Initializes a new instance of the <see cref="TransactionsImpl" /> class. /// </summary> /// <param name="target">Target.</param> /// <param name="marsh">Marshaller.</param> /// <param name="localNodeId">Local node id.</param> public TransactionsImpl(IUnmanagedTarget target, Marshaller marsh, Guid localNodeId) : base(target, marsh) { _localNodeId = localNodeId; TransactionConcurrency concurrency = default(TransactionConcurrency); TransactionIsolation isolation = default(TransactionIsolation); TimeSpan timeout = default(TimeSpan); DoInOp(OpCacheConfigParameters, stream => { var reader = marsh.StartUnmarshal(stream).GetRawReader(); concurrency = (TransactionConcurrency) reader.ReadInt(); isolation = (TransactionIsolation) reader.ReadInt(); timeout = TimeSpan.FromMilliseconds(reader.ReadLong()); }); _dfltConcurrency = concurrency; _dfltIsolation = isolation; _dfltTimeout = timeout; }
public JsGlobal(JintRuntime runtime, JintEngine engine) { if (runtime == null) throw new ArgumentNullException("runtime"); _runtime = runtime; Id.SeedGlobal(this); PrototypeSink = CreatePrototypeSink(); RootSchema = new JsSchema(); Engine = engine; // The Random instance is used by Math to generate random numbers. Random = new Random(); BuildEnvironment(); GlobalScope = CreateGlobalScope(); Marshaller = new Marshaller(runtime, this); Marshaller.Initialize(); }
/// <summary> /// Reads method invocation result. /// </summary> /// <param name="stream">Stream.</param> /// <param name="marsh">Marshaller.</param> /// <param name="keepBinary">Binary flag.</param> /// <returns> /// Method invocation result, or exception in case of error. /// </returns> public static object ReadInvocationResult(IBinaryStream stream, Marshaller marsh, bool keepBinary) { Debug.Assert(stream != null); Debug.Assert(marsh != null); var mode = keepBinary ? BinaryMode.ForceBinary : BinaryMode.Deserialize; var reader = marsh.StartUnmarshal(stream, mode); object err; var res = BinaryUtils.ReadInvocationResult(reader, out err); if (err == null) return res; var binErr = err as IBinaryObject; throw binErr != null ? new ServiceInvocationException("Proxy method invocation failed with a binary error. " + "Examine BinaryCause for details.", binErr) : new ServiceInvocationException("Proxy method invocation failed with an exception. " + "Examine InnerException for details.", (Exception) err); }
public void SetUp() { TestUtils.KillProcesses(); var cfg = new IgniteConfiguration { BinaryConfiguration = new BinaryConfiguration { TypeConfigurations = new List<BinaryTypeConfiguration> { new BinaryTypeConfiguration(typeof (Empty)), new BinaryTypeConfiguration(typeof (Primitives)), new BinaryTypeConfiguration(typeof (PrimitiveArrays)), new BinaryTypeConfiguration(typeof (StringDateGuidEnum)), new BinaryTypeConfiguration(typeof (WithRaw)), new BinaryTypeConfiguration(typeof (MetaOverwrite)), new BinaryTypeConfiguration(typeof (NestedOuter)), new BinaryTypeConfiguration(typeof (NestedInner)), new BinaryTypeConfiguration(typeof (MigrationOuter)), new BinaryTypeConfiguration(typeof (MigrationInner)), new BinaryTypeConfiguration(typeof (InversionOuter)), new BinaryTypeConfiguration(typeof (InversionInner)), new BinaryTypeConfiguration(typeof (CompositeOuter)), new BinaryTypeConfiguration(typeof (CompositeInner)), new BinaryTypeConfiguration(typeof (CompositeArray)), new BinaryTypeConfiguration(typeof (CompositeContainer)), new BinaryTypeConfiguration(typeof (ToBinary)), new BinaryTypeConfiguration(typeof (Remove)), new BinaryTypeConfiguration(typeof (RemoveInner)), new BinaryTypeConfiguration(typeof (BuilderInBuilderOuter)), new BinaryTypeConfiguration(typeof (BuilderInBuilderInner)), new BinaryTypeConfiguration(typeof (BuilderCollection)), new BinaryTypeConfiguration(typeof (BuilderCollectionItem)), new BinaryTypeConfiguration(typeof (DecimalHolder)), new BinaryTypeConfiguration(TypeEmpty) }, DefaultIdMapper = new IdMapper() }, JvmClasspath = TestUtils.CreateTestClasspath(), JvmOptions = new List<string> { "-ea", "-Xcheck:jni", "-Xms4g", "-Xmx4g", "-DIGNITE_QUIET=false", "-Xnoagent", "-Djava.compiler=NONE", "-Xdebug", "-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005", "-XX:+HeapDumpOnOutOfMemoryError" }, SpringConfigUrl = "config\\binary.xml" }; _grid = (Ignite) Ignition.Start(cfg); _marsh = _grid.Marshaller; }
public string get_inner_text() { IntPtr data = webkit_dom_html_element_get_inner_text(base.Handle); return(Marshaller.PtrToStringGFree(data)); }
public JsGlobal(ExecutionVisitor visitor, Options options) : base(JsNull.Instance) { this.Options = options; this.Visitor = visitor; this["null"] = JsNull.Instance; JsObject objectProrotype = new JsObject(JsNull.Instance); JsFunction functionPrototype = new JsFunctionWrapper( delegate(JsInstance[] arguments) { return JsUndefined.Instance; }, objectProrotype ); Marshaller = new Marshaller(this); #region Global Classes this["Function"] = FunctionClass = new JsFunctionConstructor(this, functionPrototype); this["Object"] = ObjectClass = new JsObjectConstructor(this, functionPrototype, objectProrotype); ObjectClass.InitPrototype(this); this["Array"] = ArrayClass = new JsArrayConstructor(this); this["Boolean"] = BooleanClass = new JsBooleanConstructor(this); this["Date"] = DateClass = new JsDateConstructor(this); this["Error"] = ErrorClass = new JsErrorConstructor(this, "Error"); this["EvalError"] = EvalErrorClass = new JsErrorConstructor(this, "EvalError"); this["RangeError"] = RangeErrorClass = new JsErrorConstructor(this, "RangeError"); this["ReferenceError"] = ReferenceErrorClass = new JsErrorConstructor(this, "ReferenceError"); this["SyntaxError"] = SyntaxErrorClass = new JsErrorConstructor(this, "SyntaxError"); this["TypeError"] = TypeErrorClass = new JsErrorConstructor(this, "TypeError"); this["URIError"] = URIErrorClass = new JsErrorConstructor(this, "URIError"); this["Number"] = NumberClass = new JsNumberConstructor(this); this["RegExp"] = RegExpClass = new JsRegExpConstructor(this); this["String"] = StringClass = new JsStringConstructor(this); this["Math"] = MathClass = new JsMathConstructor(this); // 15.1 prototype of the global object varies on the implementation //this.Prototype = ObjectClass.PrototypeProperty; #endregion foreach (JsInstance c in this.GetValues()) { if (c is JsConstructor) { ((JsConstructor)c).InitPrototype(this); } } #region Global Properties this["NaN"] = NumberClass["NaN"]; // 15.1.1.1 this["Infinity"] = NumberClass["POSITIVE_INFINITY"]; // // 15.1.1.2 this["undefined"] = JsUndefined.Instance; // 15.1.1.3 this[JsScope.THIS] = this; #endregion #region Global Functions // every embed function should have a prototype FunctionClass.PrototypeProperty - 15. this["eval"] = new JsFunctionWrapper(Eval, FunctionClass.PrototypeProperty); // 15.1.2.1 this["parseInt"] = new JsFunctionWrapper(ParseInt, FunctionClass.PrototypeProperty); // 15.1.2.2 this["parseFloat"] = new JsFunctionWrapper(ParseFloat, FunctionClass.PrototypeProperty); // 15.1.2.3 this["isNaN"] = new JsFunctionWrapper(IsNaN, FunctionClass.PrototypeProperty); this["isFinite"] = new JsFunctionWrapper(isFinite, FunctionClass.PrototypeProperty); this["decodeURI"] = new JsFunctionWrapper(DecodeURI, FunctionClass.PrototypeProperty); this["encodeURI"] = new JsFunctionWrapper(EncodeURI, FunctionClass.PrototypeProperty); this["decodeURIComponent"] = new JsFunctionWrapper(DecodeURIComponent, FunctionClass.PrototypeProperty); this["encodeURIComponent"] = new JsFunctionWrapper(EncodeURIComponent, FunctionClass.PrototypeProperty); #endregion Marshaller.InitTypes(); }
/// <summary> /// Writes to stream. /// </summary> private static bool WriteToStream(Action <BinaryWriter> action, IBinaryStream stream, Marshaller marsh) { var writer = marsh.StartMarshal(stream); action(writer); marsh.FinishMarshal(writer); return(true); }
/// <summary> /// Initializes a new instance of the <see cref="CacheEntryFilterHolder"/> class. /// </summary> /// <param name="reader">The reader.</param> public CacheEntryFilterHolder(BinaryReader reader) { _pred = reader.ReadObject<object>(); _keepBinary = reader.ReadBoolean(); _marsh = reader.Marshaller; _invoker = GetInvoker(_pred); }
/// <summary> /// Reads the exception. /// </summary> private Exception ReadException(IBinaryStream stream) { return(ReadException(Marshaller.StartUnmarshal(stream))); }
/** <inheritdoc /> */ public ICollection <IBaselineNode> GetBaselineTopology() { return(DoInOp((int)Op.GetBaselineTopology, s => Marshaller.StartUnmarshal(s).ReadCollectionRaw(r => (IBaselineNode) new BaselineNode(r)))); }
/// <summary> /// Constructor. /// </summary> /// <param name="target">Target.</param> /// <param name="marsh">Marshaller.</param> protected PlatformDisposableTarget(IUnmanagedTarget target, Marshaller marsh) : base(target, marsh) { // No-op. }
/** <inheritDoc /> */ protected override T Unmarshal <T>(IBinaryStream stream) { return(Marshaller.Unmarshal <T>(stream, _flagKeepBinary)); }
/** <inheritDoc /> */ public ICollection <string> GetCacheNames() { return(DoOutInOp(ClientOp.CacheGetNames, null, s => Marshaller.StartUnmarshal(s).ReadStringCollection())); }
/// <summary> /// Constructor. /// </summary> /// <param name="typeId">Type ID.</param> /// <param name="typeName">Type name.</param> /// <param name="fields">Fields.</param> /// <param name="affKeyFieldName">Affinity key field name.</param> /// <param name="isEnum">Enum flag.</param> /// <param name="enumValues">Enum values.</param> /// <param name="marshaller">Marshaller.</param> public BinaryType(int typeId, string typeName, IDictionary <string, BinaryField> fields, string affKeyFieldName, bool isEnum, IDictionary <string, int> enumValues, Marshaller marshaller) { _typeId = typeId; _typeName = typeName; _affinityKeyFieldName = affKeyFieldName; _fields = fields; _isEnum = isEnum; _enumNameToValue = enumValues; if (_enumNameToValue != null) { _enumValueToName = _enumNameToValue.ToDictionary(x => x.Value, x => x.Key); } _marshaller = marshaller; }
/// <summary> /// Initializes a new instance of the <see cref="AtomicLong"/> class. /// </summary> /// <param name="target">The target.</param> /// <param name="marsh">The marshaller.</param> /// <param name="name">The name.</param> public AtomicLong(IUnmanagedTarget target, Marshaller marsh, string name) : base(target, marsh) { Debug.Assert(!string.IsNullOrEmpty(name)); _name = name; }
/// <summary> /// Illustrates various cases of automatic authorization handling. /// </summary> static void AutomaticAuth(Tpm2 tpm) { TpmHandle primHandle = CreateRsaPrimaryKey(tpm); TpmPublic keyPublic; TpmHandle keyHandle = CreateSigningDecryptionKey(tpm, primHandle, out keyPublic); byte[] message = Globs.GetRandomBytes(32); IAsymSchemeUnion decScheme = new SchemeOaep(TpmAlgId.Sha1); ISigSchemeUnion sigScheme = new SchemeRsassa(TpmAlgId.Sha1); // // TSS.Net implicitly creates an auth session to authorize keyHandle. // It uses the auth value cached in the TpmHandle object. // byte[] encrypted = tpm.RsaEncrypt(keyHandle, message, decScheme, null); Console.WriteLine("Automatic authorization of a decryption key."); // // An auth session is added automatically when TPM object is not in strict mode. // byte[] decrypted1 = tpm.RsaDecrypt(keyHandle, encrypted, decScheme, null); byte[] nonceTpm; Console.WriteLine("Session object construction."); // // If a session with specific properties is required, an AuthSession object // can be built from the session handle returned by the TPM2_StartAuthSession // command concatenated, if necessary, with session flags and unencrypted salt // value (not used in this example). // AuthSession auditSess = tpm.StartAuthSession( TpmRh.Null, // no salt TpmRh.Null, // no bind object Globs.GetRandomBytes(16), // nonceCaller null, // no salt TpmSe.Hmac, // session type new SymDef(), // no encryption/decryption TpmAlgId.Sha256, // authHash out nonceTpm) + (SessionAttr.ContinueSession | SessionAttr.Audit); /* * Alternatively one of the StartAuthSessionEx helpers can be used). E.g. * * AuthSession auditSess = tpm.StartAuthSessionEx(TpmSe.Hmac, TpmAlgId.Sha256, * SessionAttr.ContinueSession | SessionAttr.Audit); */ // // TSS.Net specific call to verify TPM auditing correctness. // tpm._SetCommandAuditAlgorithm(TpmAlgId.Sha256); Console.WriteLine("Automatic authorization using explicitly created session object."); // // Appropriate auth value is added automatically into the provided session. // // Note that the call to _Audit() is optional and is only used when one // needs the TSS.Net framework to compute the audit digest on its own (e.g. // when simulating the TPM functionality without access to an actual TPM). // byte[] decrypted2 = tpm[auditSess]._Audit() .RsaDecrypt(keyHandle, encrypted, decScheme, null); ISignatureUnion signature; Attest attest; // // A session is added automatically to authorize usage of the permanent // handle TpmRh.Endorsement. // // Note that if auth value of TpmRh.Endorsement is not empty, you need to // explicitly assign it to the tpm.EndorsementAuth property of the given // Tpm2 object. // attest = tpm.GetSessionAuditDigest(TpmRh.Endorsement, TpmRh.Null, auditSess, null, new NullSigScheme(), out signature); // // But if the corresponding auth value stored in the Tpm2 object is invalid, ... // AuthValue endorsementAuth = tpm.EndorsementAuth; tpm.EndorsementAuth = Globs.ByteArray(16, 0xde); // // ... the command will fail. // tpm._ExpectError(TpmRc.BadAuth) .GetSessionAuditDigest(TpmRh.Endorsement, TpmRh.Null, auditSess, null, new NullSigScheme(), out signature); // // Restore correct auth value. // tpm.EndorsementAuth = endorsementAuth; // // Verify that decryption worked correctly. // Debug.Assert(Globs.ArraysAreEqual(decrypted1, decrypted2)); // // Verify that auditing worked correctly. // SessionAuditInfo info = (SessionAuditInfo)attest.attested; Debug.Assert(Globs.ArraysAreEqual(info.sessionDigest, tpm._GetAuditHash().HashData)); Console.WriteLine("Auth value tracking by TSS.Net."); // // Change auth value of the decryption key. // TpmPrivate newKeyPrivate = tpm.ObjectChangeAuth(keyHandle, primHandle, AuthValue.FromRandom(16)); TpmHandle newKeyHandle = tpm.Load(primHandle, newKeyPrivate, keyPublic); // // Allow non-exclusive usage of the audit session. // auditSess.Attrs &= ~SessionAttr.AuditExclusive; // // Correct auth value (corresponding to newKeyHandle, and different from // the one used for keyHandle) will be added to auditSess. // decrypted1 = tpm[auditSess]._Audit() .RsaDecrypt(newKeyHandle, encrypted, decScheme, null); Console.WriteLine("Automatic authorization with multiple sessions."); // // Now two sessions are auto-generated (for TpmRh.Endorsement and keyHandle). // attest = tpm.GetSessionAuditDigest(TpmRh.Endorsement, keyHandle, auditSess, null, sigScheme, out signature); // // Verify that the previous command worked correctly. // bool sigOk = keyPublic.VerifySignatureOverData(Marshaller.GetTpmRepresentation(attest), signature); Debug.Assert(sigOk); // // In the following example the first session is generated based on session // type indicator (Auth.Pw), and the second one is added automatically. // attest = tpm[Auth.Pw].GetSessionAuditDigest(TpmRh.Endorsement, keyHandle, auditSess, null, sigScheme, out signature); // // Verify that the previous command worked correctly. // sigOk = keyPublic.VerifySignatureOverData(Marshaller.GetTpmRepresentation(attest), signature); Debug.Assert(sigOk); // // Release TPM resources that we do not need anymore. // tpm.FlushContext(newKeyHandle); tpm.FlushContext(auditSess); // // The following example works correctly only when TPM resource management // is not enabled (e.g. with TPM simulator, or when actual TPM is in raw mode). // if (!tpm._GetUnderlyingDevice().HasRM()) { Console.WriteLine("Using session type indicators."); // // Deplete TPM's active session storage // List <AuthSession> landfill = new List <AuthSession>(); for (;;) { tpm._AllowErrors(); AuthSession s = tpm.StartAuthSessionEx(TpmSe.Hmac, TpmAlgId.Sha256, SessionAttr.ContinueSession); if (!tpm._LastCommandSucceeded()) { break; } landfill.Add(s); } // // Check if session type indicators are processed correctly // tpm[Auth.Hmac]._ExpectError(TpmRc.SessionMemory) .RsaDecrypt(keyHandle, encrypted, new NullAsymScheme(), null); // // Password authorization protocol session uses a predefined handle value, // so it must work even when there are no free session slots in the TPM. // tpm[Auth.Pw].RsaDecrypt(keyHandle, encrypted, new NullAsymScheme(), null); // // Check if default session type defined by the TPM device is processed correctly. // bool needHmac = tpm._GetUnderlyingDevice().NeedsHMAC; tpm._GetUnderlyingDevice().NeedsHMAC = true; tpm._ExpectError(TpmRc.SessionMemory) .RsaDecrypt(keyHandle, encrypted, new NullAsymScheme(), null); tpm[Auth.Default]._ExpectError(TpmRc.SessionMemory) .RsaDecrypt(keyHandle, encrypted, new NullAsymScheme(), null); tpm._GetUnderlyingDevice().NeedsHMAC = false; tpm.RsaDecrypt(keyHandle, encrypted, new NullAsymScheme(), null); tpm[Auth.Default].RsaDecrypt(keyHandle, encrypted, new NullAsymScheme(), null); tpm._GetUnderlyingDevice().NeedsHMAC = needHmac; landfill.ForEach(s => tpm.FlushContext(s)); } // // Release TPM resources. // tpm.FlushContext(keyHandle); tpm.FlushContext(primHandle); Console.WriteLine("Done."); }
/** <inheritDoc /> */ public CacheConfiguration GetConfiguration() { return(DoInOp((int)CacheOp.GetConfig, stream => new CacheConfiguration(Marshaller.StartUnmarshal(stream)))); }
/// <summary> /// Activates an identity key within the TPM device. /// </summary> /// <remarks> /// Calls to the TPM library can potentially return a <see cref="TssException"/> or a <see cref="TpmException"/> /// if your TPM hardware does not support the relevant API call. /// </remarks> /// <param name="encryptedKey">The encrypted identity key.</param> public override void ActivateIdentityKey(byte[] encryptedKey) { if (Logging.IsEnabled) { Logging.Enter(this, $"{encryptedKey}", nameof(ActivateIdentityKey)); } Destroy(); // Take the pieces out of the container var m = new Marshaller(encryptedKey, DataRepresentation.Tpm); Tpm2bIdObject cred2b = m.Get <Tpm2bIdObject>(); byte[] encryptedSecret = new byte[m.Get <ushort>()]; encryptedSecret = m.GetArray <byte>(encryptedSecret.Length, "encryptedSecret"); TpmPrivate dupBlob = m.Get <TpmPrivate>(); byte[] encWrapKey = new byte[m.Get <ushort>()]; encWrapKey = m.GetArray <byte>(encWrapKey.Length, "encWrapKey"); ushort pubSize = m.Get <ushort>(); _idKeyPub = m.Get <TpmPublic>(); byte[] cipherText = new byte[m.Get <ushort>()]; cipherText = m.GetArray <byte>(cipherText.Length, "uriInfo"); // Setup the authorization session for the EK var policyNode = new TpmPolicySecret(TpmHandle.RhEndorsement, false, 0, Array.Empty <byte>(), Array.Empty <byte>()); var policy = new PolicyTree(_ekPub.nameAlg); policy.SetPolicyRoot(policyNode); AuthSession ekSession = _tpm2.StartAuthSessionEx(TpmSe.Policy, _ekPub.nameAlg); ekSession.RunPolicy(_tpm2, policy); // Perform the activation ekSession.Attrs &= ~SessionAttr.ContinueSession; _activationSecret = _tpm2[Array.Empty <byte>(), ekSession].ActivateCredential( new TpmHandle(TPM_20_SRK_HANDLE), new TpmHandle(TPM_20_EK_HANDLE), cred2b.credential, encryptedSecret); TpmPrivate importedKeyBlob = _tpm2.Import( new TpmHandle(TPM_20_SRK_HANDLE), _activationSecret, _idKeyPub, dupBlob, encWrapKey, new SymDefObject(TpmAlgId.Aes, 128, TpmAlgId.Cfb)); _idKeyHandle = _tpm2.Load(new TpmHandle(TPM_20_SRK_HANDLE), importedKeyBlob, _idKeyPub); // Persist the key in NV var hmacKeyHandle = new TpmHandle(AIOTH_PERSISTED_KEY_HANDLE); _tpm2.EvictControl(new TpmHandle(TpmRh.Owner), _idKeyHandle, hmacKeyHandle); // Unload the transient copy from the TPM _tpm2.FlushContext(_idKeyHandle); _idKeyHandle = hmacKeyHandle; if (Logging.IsEnabled) { Logging.Exit(this, $"{encryptedKey}", nameof(ActivateIdentityKey)); } }
/** <inheritdoc /> */ public IDictionary <TK, ICacheEntryProcessorResult <TRes> > InvokeAll <TArg, TRes>(IEnumerable <TK> keys, ICacheEntryProcessor <TK, TV, TArg, TRes> processor, TArg arg) { IgniteArgumentCheck.NotNull(keys, "keys"); IgniteArgumentCheck.NotNull(processor, "processor"); var holder = new CacheEntryProcessorHolder(processor, arg, (e, a) => processor.Process((IMutableCacheEntry <TK, TV>)e, (TArg)a), typeof(TK), typeof(TV)); return(DoOutInOpX((int)CacheOp.InvokeAll, writer => { WriteEnumerable(writer, keys); writer.Write(holder); }, (input, res) => res == True ? ReadInvokeAllResults <TRes>(Marshaller.StartUnmarshal(input, IsKeepBinary)): null, ReadException)); }
public PInvokeILStubMethodIL(ILStubMethodIL methodIL) : base(methodIL) { IsMarshallingRequired = Marshaller.IsMarshallingRequired(methodIL.OwningMethod); }
/// <summary> /// Gets the data storage metrics. /// </summary> public IDataStorageMetrics GetDataStorageMetrics() { return(DoInOp(OpDataStorageMetrics, stream => new DataStorageMetrics(Marshaller.StartUnmarshal(stream, false)))); }
/// <summary> /// Writes to stream. /// </summary> private static bool WriteToStream(Func <BinaryWriter, bool> action, IBinaryStream stream, Marshaller marsh) { var writer = marsh.StartMarshal(stream); var res = action(writer); marsh.FinishMarshal(writer); return(res); }
static HeartbeatClient() { DuplexStreamingAsyncMethod = new Method <byte[], byte[]>(MethodType.DuplexStreaming, "IMagicOnionEmbeddedHeartbeat", "Connect", MagicOnionMarshallers.ByteArrayMarshaller, MagicOnionMarshallers.ByteArrayMarshaller); DuplexStreamingAsyncRequestMarshaller = MagicOnionMarshallers.CreateZeroFormatterMarshaller(ZeroFormatter.Formatters.Formatter <ZeroFormatter.Formatters.DefaultResolver, bool> .Default); DuplexStreamingAsyncResponseMarshaller = MagicOnionMarshallers.CreateZeroFormatterMarshaller(Formatter <ZeroFormatter.Formatters.DefaultResolver, bool> .Default); }
/// <summary> /// Writes method invocation result. /// </summary> /// <param name="stream">Stream.</param> /// <param name="marsh">Marshaller.</param> /// <param name="methodResult">Method result.</param> /// <param name="invocationError">Method invocation error.</param> public static void WriteInvocationResult(IBinaryStream stream, Marshaller marsh, object methodResult, Exception invocationError) { Debug.Assert(stream != null); Debug.Assert(marsh != null); var writer = marsh.StartMarshal(stream); BinaryUtils.WriteInvocationResult(writer, invocationError == null, invocationError ?? methodResult); }
public void SetUp() { TestUtils.KillProcesses(); var cfg = new IgniteConfiguration { BinaryConfiguration = new BinaryConfiguration { TypeConfigurations = new List<BinaryTypeConfiguration> { new BinaryTypeConfiguration(typeof (Empty)), new BinaryTypeConfiguration(typeof (Primitives)), new BinaryTypeConfiguration(typeof (PrimitiveArrays)), new BinaryTypeConfiguration(typeof (StringDateGuidEnum)), new BinaryTypeConfiguration(typeof (WithRaw)), new BinaryTypeConfiguration(typeof (MetaOverwrite)), new BinaryTypeConfiguration(typeof (NestedOuter)), new BinaryTypeConfiguration(typeof (NestedInner)), new BinaryTypeConfiguration(typeof (MigrationOuter)), new BinaryTypeConfiguration(typeof (MigrationInner)), new BinaryTypeConfiguration(typeof (InversionOuter)), new BinaryTypeConfiguration(typeof (InversionInner)), new BinaryTypeConfiguration(typeof (CompositeOuter)), new BinaryTypeConfiguration(typeof (CompositeInner)), new BinaryTypeConfiguration(typeof (CompositeArray)), new BinaryTypeConfiguration(typeof (CompositeContainer)), new BinaryTypeConfiguration(typeof (ToBinary)), new BinaryTypeConfiguration(typeof (Remove)), new BinaryTypeConfiguration(typeof (RemoveInner)), new BinaryTypeConfiguration(typeof (BuilderInBuilderOuter)), new BinaryTypeConfiguration(typeof (BuilderInBuilderInner)), new BinaryTypeConfiguration(typeof (BuilderCollection)), new BinaryTypeConfiguration(typeof (BuilderCollectionItem)), new BinaryTypeConfiguration(typeof (DecimalHolder)), new BinaryTypeConfiguration(TypeEmpty), new BinaryTypeConfiguration(typeof(TestEnumRegistered)) }, DefaultIdMapper = new IdMapper() }, JvmClasspath = TestUtils.CreateTestClasspath(), JvmOptions = TestUtils.TestJavaOptions(), SpringConfigUrl = "config\\binary.xml" }; _grid = (Ignite) Ignition.Start(cfg); _marsh = _grid.Marshaller; }
/// <summary> /// Writes the event types. /// </summary> /// <param name="reader">Reader.</param> private int[] ReadEventTypes(IBinaryStream reader) { return(Marshaller.StartUnmarshal(reader).ReadIntArray()); }
public void TestWriteRead() { var marsh = new Marshaller(new BinaryConfiguration(typeof(ReadWriteAll))); marsh.Unmarshal<ReadWriteAll>(marsh.Marshal(new ReadWriteAll())); }
/// <summary> /// Verify that a TPM quote matches an expect PCR selection, is well formed, and is properly signed /// by the private key corresponding to this public key. /// </summary> /// <param name="pcrDigestAlg"></param> /// <param name="expectedSelectedPcr"></param> /// <param name="expectedPcrValues"></param> /// <param name="nonce"></param> /// <param name="quotedInfo"></param> /// <param name="signature"></param> /// <param name="qualifiedNameOfSigner"></param> /// <returns></returns> public bool VerifyQuote( TpmAlgId pcrDigestAlg, PcrSelection[] expectedSelectedPcr, Tpm2bDigest[] expectedPcrValues, byte[] nonce, Attest quotedInfo, ISignatureUnion signature, byte[] qualifiedNameOfSigner = null) { if (!(quotedInfo.attested is QuoteInfo)) { return false; } if (quotedInfo.magic != Generated.Value) { return false; } if (!quotedInfo.extraData.IsEqual(nonce)) { return false; } // Check environment of signer (name) is expected if (qualifiedNameOfSigner != null) { if (!quotedInfo.qualifiedSigner.IsEqual(qualifiedNameOfSigner)) { return false; } } // Now check the quote-specific fields var quoted = (QuoteInfo)quotedInfo.attested; // Check values pcr indices are what we expect if (!Globs.ArraysAreEqual(quoted.pcrSelect, expectedSelectedPcr)) { return false; } // Check that values in the indices above are what we expect // ReSharper disable once UnusedVariable var expected = new PcrValueCollection(expectedSelectedPcr, expectedPcrValues); var m = new Marshaller(); foreach (Tpm2bDigest d in expectedPcrValues) { m.Put(d.buffer, ""); } TpmHash expectedPcrHash = TpmHash.FromData(pcrDigestAlg, m.GetBytes()); if (!Globs.ArraysAreEqual(expectedPcrHash, quoted.pcrDigest)) { return false; } // And finally check the signature bool sigOk = VerifySignatureOverData(quotedInfo.GetTpmRepresentation(), signature); return sigOk; }
/// <summary> /// Activates a symmetric identity within the Hardware Security Module. /// </summary> /// <param name="activation">The authentication challenge key supplied by the service.</param> public override void ActivateSymmetricIdentity(byte[] activation) { Destroy(); // Take the pieces out of the container var m = new Marshaller(activation, DataRepresentation.Tpm); byte[] credentialBlob = new byte[m.Get <ushort>()]; credentialBlob = m.GetArray <byte>(credentialBlob.Length, "credentialBlob"); byte[] encryptedSecret = new byte[m.Get <ushort>()]; encryptedSecret = m.GetArray <byte>(encryptedSecret.Length, "encryptedSecret"); TpmPrivate dupBlob = m.Get <TpmPrivate>(); byte[] encWrapKey = new byte[m.Get <ushort>()]; encWrapKey = m.GetArray <byte>(encryptedSecret.Length, "encWrapKey"); UInt16 pubSize = m.Get <UInt16>(); _idKeyPub = m.Get <TpmPublic>(); byte[] cipherText = new byte[m.Get <ushort>()]; cipherText = m.GetArray <byte>(cipherText.Length, "uriInfo"); // Setup the authorization session for the EK var policyNode = new TpmPolicySecret( TpmHandle.RhEndorsement, _ekAuth ?? Array.Empty <byte>(), new AuthValue(), false, 0, Array.Empty <byte>(), Array.Empty <byte>()); var policy = new PolicyTree(_ekPub.nameAlg); policy.SetPolicyRoot(policyNode); AuthSession ekSession = _tpm2.StartAuthSessionEx(TpmSe.Policy, _ekPub.nameAlg); ekSession.RunPolicy(_tpm2, policy); // Perform the activation ekSession.Attrs &= ~SessionAttr.ContinueSession; _activationSecret = _tpm2[Array.Empty <byte>(), ekSession].ActivateCredential( new TpmHandle(TPM_20_SRK_HANDLE), new TpmHandle(TPM_20_EK_HANDLE), credentialBlob, encryptedSecret); TpmPrivate importedKeyBlob = _tpm2.Import( new TpmHandle(TPM_20_SRK_HANDLE), _activationSecret, _idKeyPub, dupBlob, encWrapKey, new SymDefObject(TpmAlgId.Aes, 128, TpmAlgId.Cfb)); _idKeyHandle = _tpm2.Load(new TpmHandle(TPM_20_SRK_HANDLE), importedKeyBlob, _idKeyPub); // Persist the key in NV TpmHandle hmacKeyHandle = new TpmHandle(AIOTH_PERSISTED_KEY_HANDLE); _tpm2.EvictControl(new TpmHandle(TpmRh.Owner), _idKeyHandle, hmacKeyHandle); // Unload the transient copy from the TPM _tpm2.FlushContext(_idKeyHandle); _idKeyHandle = hmacKeyHandle; // Unwrap the URI byte[] clearText = SymmCipher.Decrypt( new SymDefObject(TpmAlgId.Aes, 128, TpmAlgId.Cfb), _activationSecret, new byte[16], cipherText); UnicodeEncoding unicode = new UnicodeEncoding(); string uriData = unicode.GetString(clearText); int idx = uriData.IndexOf('/'); if (idx > 0) { string hostName = uriData.Substring(0, idx); string deviceId = uriData.Substring(idx + 1); // Persist the URI ProvisionUri(hostName, deviceId); } }
/// <summary> /// Initializes a new instance of the <see cref="Listenable"/> class. /// </summary> /// <param name="target">Target.</param> /// <param name="marsh">Marshaller.</param> public Listenable(IUnmanagedTarget target, Marshaller marsh) : base(target, marsh) { // No-op. }
/// <summary> /// Invokes local filter using data from specified stream. /// </summary> /// <typeparam name="T">Event object type.</typeparam> /// <param name="stream">The stream.</param> /// <param name="listener">The listener.</param> /// <returns>Filter invocation result.</returns> private bool InvokeLocalListener <T>(IBinaryStream stream, IEventListener <T> listener) where T : IEvent { var evt = EventReader.Read <T>(Marshaller.StartUnmarshal(stream)); return(listener.Invoke(evt)); }
/// <summary> /// Reads nodes from stream. /// </summary> private IList <IClusterNode> ReadNodes(IBinaryStream reader) { return(IgniteUtils.ReadNodes(Marshaller.StartUnmarshal(reader, _keepBinary))); }
/// <summary> /// Initializes a new instance of the <see cref="LocalEventFilter{T}"/> class. /// </summary> public LocalEventFilter(Marshaller marshaller, IEventFilter <T> listener) { _marshaller = marshaller; _listener = listener; }
public void SetUp() { TestUtils.KillProcesses(); var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration()) { BinaryConfiguration = new BinaryConfiguration { TypeConfigurations = new List<BinaryTypeConfiguration> { new BinaryTypeConfiguration(typeof (Empty)), new BinaryTypeConfiguration(typeof (Primitives)), new BinaryTypeConfiguration(typeof (PrimitiveArrays)), new BinaryTypeConfiguration(typeof (StringDateGuidEnum)), new BinaryTypeConfiguration(typeof (WithRaw)), new BinaryTypeConfiguration(typeof (MetaOverwrite)), new BinaryTypeConfiguration(typeof (NestedOuter)), new BinaryTypeConfiguration(typeof (NestedInner)), new BinaryTypeConfiguration(typeof (MigrationOuter)), new BinaryTypeConfiguration(typeof (MigrationInner)), new BinaryTypeConfiguration(typeof (InversionOuter)), new BinaryTypeConfiguration(typeof (InversionInner)), new BinaryTypeConfiguration(typeof (CompositeOuter)), new BinaryTypeConfiguration(typeof (CompositeInner)), new BinaryTypeConfiguration(typeof (CompositeArray)), new BinaryTypeConfiguration(typeof (CompositeContainer)), new BinaryTypeConfiguration(typeof (ToBinary)), new BinaryTypeConfiguration(typeof (Remove)), new BinaryTypeConfiguration(typeof (RemoveInner)), new BinaryTypeConfiguration(typeof (BuilderInBuilderOuter)), new BinaryTypeConfiguration(typeof (BuilderInBuilderInner)), new BinaryTypeConfiguration(typeof (BuilderCollection)), new BinaryTypeConfiguration(typeof (BuilderCollectionItem)), new BinaryTypeConfiguration(typeof (DecimalHolder)), new BinaryTypeConfiguration(TypeEmpty), new BinaryTypeConfiguration(typeof(TestEnumRegistered)), new BinaryTypeConfiguration(typeof(NameMapperTestType)) }, DefaultIdMapper = new IdMapper(), DefaultNameMapper = new NameMapper(), CompactFooter = GetCompactFooter() } }; _grid = (Ignite) Ignition.Start(cfg); _marsh = _grid.Marshaller; }
/// <summary> /// Reads events from a binary stream. /// </summary> /// <typeparam name="T">Event type.</typeparam> /// <param name="reader">Reader.</param> /// <returns>Resulting list or null.</returns> private ICollection <T> ReadEvents <T>(IBinaryStream reader) where T : IEvent { return(ReadEvents <T>(Marshaller.StartUnmarshal(reader))); }
/// <summary> /// Gets the memory metrics. /// </summary> public IMemoryMetrics GetMemoryMetrics(string memoryPolicyName) { return(DoOutInOp(OpMemoryMetricsByName, w => w.WriteString(memoryPolicyName), stream => stream.ReadBool() ? new MemoryMetrics(Marshaller.StartUnmarshal(stream, false)) : null)); }
/// <summary> /// Gets the persistent store metrics. /// </summary> public IPersistentStoreMetrics GetPersistentStoreMetrics() { return(DoInOp(OpGetPersistentStoreMetrics, stream => new PersistentStoreMetrics(Marshaller.StartUnmarshal(stream, false)))); }
public MockServiceHelper(string host = null, Marshaller<string> marshaller = null, IEnumerable<ChannelOption> channelOptions = null) { this.host = host ?? "localhost"; this.channelOptions = channelOptions; marshaller = marshaller ?? Marshallers.StringMarshaller; unaryMethod = new Method<string, string>( MethodType.Unary, ServiceName, "Unary", marshaller, marshaller); clientStreamingMethod = new Method<string, string>( MethodType.ClientStreaming, ServiceName, "ClientStreaming", marshaller, marshaller); serverStreamingMethod = new Method<string, string>( MethodType.ServerStreaming, ServiceName, "ServerStreaming", marshaller, marshaller); duplexStreamingMethod = new Method<string, string>( MethodType.DuplexStreaming, ServiceName, "DuplexStreaming", marshaller, marshaller); serviceDefinition = ServerServiceDefinition.CreateBuilder() .AddMethod(unaryMethod, (request, context) => unaryHandler(request, context)) .AddMethod(clientStreamingMethod, (requestStream, context) => clientStreamingHandler(requestStream, context)) .AddMethod(serverStreamingMethod, (request, responseStream, context) => serverStreamingHandler(request, responseStream, context)) .AddMethod(duplexStreamingMethod, (requestStream, responseStream, context) => duplexStreamingHandler(requestStream, responseStream, context)) .Build(); var defaultStatus = new Status(StatusCode.Unknown, "Default mock implementation. Please provide your own."); unaryHandler = new UnaryServerMethod<string, string>(async (request, context) => { context.Status = defaultStatus; return ""; }); clientStreamingHandler = new ClientStreamingServerMethod<string, string>(async (requestStream, context) => { context.Status = defaultStatus; return ""; }); serverStreamingHandler = new ServerStreamingServerMethod<string, string>(async (request, responseStream, context) => { context.Status = defaultStatus; }); duplexStreamingHandler = new DuplexStreamingServerMethod<string, string>(async (requestStream, responseStream, context) => { context.Status = defaultStatus; }); }
/// <summary> /// Constructor. /// </summary> /// <param name="cfg">Configuration.</param> /// <param name="name">Grid name.</param> /// <param name="proc">Interop processor.</param> /// <param name="marsh">Marshaller.</param> /// <param name="lifecycleHandlers">Lifecycle beans.</param> /// <param name="cbs">Callbacks.</param> public Ignite(IgniteConfiguration cfg, string name, IPlatformTargetInternal proc, Marshaller marsh, IList <LifecycleHandlerHolder> lifecycleHandlers, UnmanagedCallbacks cbs) : base(proc) { Debug.Assert(cfg != null); Debug.Assert(proc != null); Debug.Assert(marsh != null); Debug.Assert(lifecycleHandlers != null); Debug.Assert(cbs != null); _cfg = cfg; _name = name; _proc = proc; _marsh = marsh; _lifecycleHandlers = lifecycleHandlers; _cbs = cbs; marsh.Ignite = this; _prj = new ClusterGroupImpl(Target.OutObjectInternal((int)Op.GetClusterGroup), null); _binary = new Binary.Binary(marsh); _binaryProc = new BinaryProcessor(DoOutOpObject((int)Op.GetBinaryProcessor)); cbs.Initialize(this); // Set reconnected task to completed state for convenience. _clientReconnectTaskCompletionSource.SetResult(false); SetCompactFooter(); _pluginProcessor = new PluginProcessor(this); }
private static Marshaller[] InitializeMarshallers(MethodDesc targetMethod, InteropStateManager interopStateManager, PInvokeFlags flags) { MarshalDirection direction = MarshalDirection.Forward; MethodSignature methodSig; bool runtimeMarshallingEnabled; switch (targetMethod) { case DelegateMarshallingMethodThunk delegateMethod: methodSig = delegateMethod.DelegateSignature; direction = delegateMethod.Direction; runtimeMarshallingEnabled = MarshalHelpers.IsRuntimeMarshallingEnabled(delegateMethod.DelegateType.Module); break; case CalliMarshallingMethodThunk calliMethod: methodSig = calliMethod.TargetSignature; runtimeMarshallingEnabled = calliMethod.RuntimeMarshallingEnabled; break; default: methodSig = targetMethod.Signature; runtimeMarshallingEnabled = MarshalHelpers.IsRuntimeMarshallingEnabled(((MetadataType)targetMethod.OwningType).Module); break; } int indexOffset = 0; if (!methodSig.IsStatic && direction == MarshalDirection.Forward) { // For instance methods(eg. Forward delegate marshalling thunk), first argument is // the instance indexOffset = 1; } ParameterMetadata[] parameterMetadataArray = targetMethod.GetParameterMetadata(); Marshaller[] marshallers = new Marshaller[methodSig.Length + 1]; int parameterIndex = 0; ParameterMetadata parameterMetadata; for (int i = 0; i < marshallers.Length; i++) { Debug.Assert(parameterIndex == parameterMetadataArray.Length || i <= parameterMetadataArray[parameterIndex].Index); if (parameterIndex == parameterMetadataArray.Length || i < parameterMetadataArray[parameterIndex].Index) { // if we don't have metadata for the parameter, create a dummy one parameterMetadata = new ParameterMetadata(i, ParameterMetadataAttributes.None, null); } else { Debug.Assert(i == parameterMetadataArray[parameterIndex].Index); parameterMetadata = parameterMetadataArray[parameterIndex++]; } TypeDesc parameterType; bool isHRSwappedRetVal = false; if (i == 0) { // First item is the return type parameterType = methodSig.ReturnType; if (!flags.PreserveSig && !parameterType.IsVoid) { // PreserveSig = false can only show up an regular forward PInvokes Debug.Assert(direction == MarshalDirection.Forward); parameterType = methodSig.Context.GetByRefType(parameterType); isHRSwappedRetVal = true; } } else { parameterType = methodSig[i - 1]; } if (runtimeMarshallingEnabled) { marshallers[i] = Marshaller.CreateMarshaller(parameterType, parameterIndex, methodSig.GetEmbeddedSignatureData(), MarshallerType.Argument, parameterMetadata.MarshalAsDescriptor, direction, marshallers, interopStateManager, indexOffset + parameterMetadata.Index, flags, parameterMetadata.In, isHRSwappedRetVal ? true : parameterMetadata.Out, isHRSwappedRetVal ? false : parameterMetadata.Return ); } else { marshallers[i] = Marshaller.CreateDisabledMarshaller( parameterType, parameterIndex, MarshallerType.Argument, direction, marshallers, indexOffset + parameterMetadata.Index, flags, parameterMetadata.Return); } } return(marshallers); }
public UnaryResult(AsyncUnaryCall <byte[]> inner, Marshaller <TResponse> marshaller) { this.inner = inner; this.marshaller = marshaller; }
public void SetUp() { TestUtils.KillProcesses(); var cfg = new IgniteConfiguration { BinaryConfiguration = new BinaryConfiguration { TypeConfigurations = new List<BinaryTypeConfiguration> { new BinaryTypeConfiguration(typeof (Empty)), new BinaryTypeConfiguration(typeof (Primitives)), new BinaryTypeConfiguration(typeof (PrimitiveArrays)), new BinaryTypeConfiguration(typeof (StringDateGuidEnum)), new BinaryTypeConfiguration(typeof (WithRaw)), new BinaryTypeConfiguration(typeof (MetaOverwrite)), new BinaryTypeConfiguration(typeof (NestedOuter)), new BinaryTypeConfiguration(typeof (NestedInner)), new BinaryTypeConfiguration(typeof (MigrationOuter)), new BinaryTypeConfiguration(typeof (MigrationInner)), new BinaryTypeConfiguration(typeof (InversionOuter)), new BinaryTypeConfiguration(typeof (InversionInner)), new BinaryTypeConfiguration(typeof (CompositeOuter)), new BinaryTypeConfiguration(typeof (CompositeInner)), new BinaryTypeConfiguration(typeof (CompositeArray)), new BinaryTypeConfiguration(typeof (CompositeContainer)), new BinaryTypeConfiguration(typeof (ToBinary)), new BinaryTypeConfiguration(typeof (Remove)), new BinaryTypeConfiguration(typeof (RemoveInner)), new BinaryTypeConfiguration(typeof (BuilderInBuilderOuter)), new BinaryTypeConfiguration(typeof (BuilderInBuilderInner)), new BinaryTypeConfiguration(typeof (BuilderCollection)), new BinaryTypeConfiguration(typeof (BuilderCollectionItem)), new BinaryTypeConfiguration(typeof (DecimalHolder)), new BinaryTypeConfiguration(TypeEmpty), new BinaryTypeConfiguration(typeof(TestEnumRegistered)) }, DefaultIdMapper = new IdMapper(), CompactFooter = GetCompactFooter() }, JvmClasspath = TestUtils.CreateTestClasspath(), JvmOptions = TestUtils.TestJavaOptions(), DiscoverySpi = new TcpDiscoverySpi { IpFinder = new TcpDiscoveryStaticIpFinder { Endpoints = new[] { "127.0.0.1:47500", "127.0.0.1:47501" } } } }; _grid = (Ignite) Ignition.Start(cfg); _marsh = _grid.Marshaller; }
/// <summary> /// Initializes a new instance of <see cref="ClientRequestContext"/> class. /// </summary> /// <param name="stream">Stream.</param> /// <param name="marshaller">Marshaller.</param> /// <param name="protocolVersion">Protocol version to be used for this request.</param> public ClientRequestContext(IBinaryStream stream, Marshaller marshaller, ClientProtocolVersion protocolVersion) : base(stream, marshaller, protocolVersion) { // No-op. }
/// <summary> /// Initializes a new instance of the <see cref="IgniteConfiguration"/> class. /// </summary> /// <param name="configuration">The configuration to copy.</param> public IgniteConfiguration(IgniteConfiguration configuration) { IgniteArgumentCheck.NotNull(configuration, "configuration"); CopyLocalProperties(configuration); using (var stream = IgniteManager.Memory.Allocate().GetStream()) { var marsh = new Marshaller(configuration.BinaryConfiguration); configuration.Write(marsh.StartMarshal(stream)); stream.SynchronizeOutput(); stream.Seek(0, SeekOrigin.Begin); ReadCore(marsh.StartUnmarshal(stream)); } }
/// <summary> /// Gets a topology by version. Returns null if topology history storage doesn't contain /// specified topology version (history currently keeps the last 1000 snapshots). /// </summary> /// <param name="version">Topology version.</param> /// <returns>Collection of Ignite nodes which represented by specified topology version, /// if it is present in history storage, {@code null} otherwise.</returns> /// <exception cref="IgniteException">If underlying SPI implementation does not support /// topology history. Currently only {@link org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi} /// supports topology history.</exception> internal ICollection <IClusterNode> Topology(long version) { return(DoOutInOp(OpTopology, writer => writer.WriteLong(version), input => IgniteUtils.ReadNodes(Marshaller.StartUnmarshal(input)))); }