Ejemplo n.º 1
0
        public void TestPtrStructureConvert()
        {
            IntPtr pStructure = IntPtr.Zero;

            try
            {
                TestStructure structure = new TestStructure
                {
                    Uint64Val = 1,
                    StringVal = "hello",
                    IntPtrVal = (IntPtr)0x123455,
                    Uint32Val = 18,
                    BoolVal   = false,
                    EnumVal   = TestEnum.One
                };
                pStructure = MarshalUtils.StructureToPtr(structure);
                Assert.AreNotEqual(pStructure, IntPtr.Zero);
                TestStructure convertedStructure = MarshalUtils.PtrToStructure <TestStructure>(pStructure);
                Assert.NotNull(convertedStructure);
                AssertStructureEquals(structure, convertedStructure);
            }
            finally
            {
                MarshalUtils.SafeFreeHGlobal(pStructure);
            }
        }
Ejemplo n.º 2
0
        private SearchResultAttributeCollection GetLdapAttributes(SafeHandle ld, IntPtr entry, ref IntPtr ber)
        {
            var attributes = new SearchResultAttributeCollection();

            for (var attr = Native.ldap_first_attribute(ld, entry, ref ber);
                 attr != IntPtr.Zero;
                 attr = Native.ldap_next_attribute(ld, entry, ber))
            {
                var vals = Native.ldap_get_values_len(ld, entry, attr);
                if (vals != IntPtr.Zero)
                {
                    var attrName = Encoder.Instance.PtrToString(attr);
                    if (attrName != null)
                    {
                        var directoryAttribute = new DirectoryAttribute
                        {
                            Name = attrName
                        };
                        directoryAttribute.AddValues(MarshalUtils.BerValArrayToByteArrays(vals));
                        attributes.Add(directoryAttribute);
                    }
                    Native.ldap_value_free_len(vals);
                }

                Native.ldap_memfree(attr);
            }

            return(attributes);
        }
Ejemplo n.º 3
0
        public void MarshalUtils_StructureArrayToPtr_LDAPMod(params LdapModifyAttribute[] attributes)
        {
            var data = attributes
                       .Select(_ =>
            {
                var values = _.Values.Union(new string[] { null }).ToArray();
                var ptr    = Marshal.AllocHGlobal(IntPtr.Size * values.Length);
                MarshalUtils.StringArrayToPtr(values, ptr);
                return(new Native.LDAPMod
                {
                    mod_op = (int)_.LdapModOperation,
                    mod_type = Encoder.Instance.StringToPtr(_.Type),
                    mod_vals_u = new Native.LDAPMod.mod_vals
                    {
                        modv_strvals = ptr
                    }
                });
            })
                       .ToArray();

            var actual = Marshal.AllocHGlobal(IntPtr.Size * (data.Length + 1));

            MarshalUtils.StructureArrayToPtr(data, actual, true);

            var actualData = new List <LdapModifyAttribute>();
            var count      = 0;
            var tempPtr    = Marshal.ReadIntPtr(actual, IntPtr.Size * count);

            while (tempPtr != IntPtr.Zero)
            {
                var mod    = Marshal.PtrToStructure <Native.LDAPMod>(tempPtr);
                var length = 0;
                var values = new List <string>();
                var ptr    = Marshal.ReadIntPtr(mod.mod_vals_u.modv_strvals, IntPtr.Size * length);
                while (ptr != IntPtr.Zero)
                {
                    values.Add(Encoder.Instance.PtrToString(ptr));
                    length++;
                    ptr = Marshal.ReadIntPtr(mod.mod_vals_u.modv_strvals, IntPtr.Size * length);
                }
                actualData.Add(new LdapModifyAttribute
                {
                    Type             = Encoder.Instance.PtrToString(mod.mod_type),
                    LdapModOperation = (Native.LdapModOperation)mod.mod_op,
                    Values           = values
                });
                count++;
                tempPtr = Marshal.ReadIntPtr(actual, IntPtr.Size * count);
            }
            foreach (var ldapMod in data)
            {
                Marshal.FreeHGlobal(ldapMod.mod_vals_u.modv_strvals);
                Marshal.FreeHGlobal(ldapMod.mod_type);
            }
            Marshal.FreeHGlobal(actual);

            Assert.NotEmpty(actualData);
            Assert.Equal(attributes, actualData, new LambdaEqualityComparer <LdapModifyAttribute>((e, a) => e.LdapModOperation == a.LdapModOperation && e.Type == a.Type &&
                                                                                                  e.Values.SequenceEqual(a.Values)));
        }
Ejemplo n.º 4
0
        public void TestPtrToString()
        {
            string testString = "this is test string";

            byte[] bufferWithoutTrash = Encoding.UTF8.GetBytes(testString);
            byte[] bufferWithEmoji    = { 65, 32, /* 🤪 */ 0xf0, 0x9f, 0xa4, 0xaa };
            byte[] bufferWithNonUtf   = { 65, 32, 0xff, 32, 0x7f, 32 };
            byte[] bufferWithLatin1   = Encoding.GetEncoding("ISO-8859-1").GetBytes("hèllò");

            List <byte[]> buffers = new List <byte[]>
            {
                bufferWithoutTrash,
                bufferWithEmoji,
                bufferWithNonUtf,
                bufferWithLatin1
            };

            foreach (var buffer in buffers)
            {
                IntPtr pBuffer = IntPtr.Zero;
                try
                {
                    pBuffer = Marshal.AllocHGlobal(buffer.Length);
                    Marshal.Copy(buffer, 0, pBuffer, buffer.Length);
                    Assert.DoesNotThrow(() =>
                    {
                        MarshalUtils.PtrToString(pBuffer);
                    });
                }
                finally
                {
                    MarshalUtils.SafeFreeHGlobal(pBuffer);
                }
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// This method is called from the CoreLibs and passed to managed code
        /// </summary>
        /// <param name="attachment">Pointer to the native logger</param>
        /// <param name="logLevel">Log level</param>
        /// <param name="pMessage">Pointer to the log message</param>
        /// <param name="length">Message length</param>
        private static void AGOnDnsLogged(
            IntPtr attachment,
            AGDnsApi.ag_log_level logLevel,
            IntPtr pMessage,
            UInt32 length)
        {
            try
            {
                LogBylogLevel          logByLogLevel = LOG_LEVELS_MAPPING[logLevel];
                MarshalUtils.ag_buffer agBuffer      = new MarshalUtils.ag_buffer
                {
                    data = pMessage,
                    size = length
                };

                string message = MarshalUtils.AgBufferToString(agBuffer);
                // We have to forcibly trim trailing CR due to
                // https://bit.adguard.com/projects/ADGUARD-CORE-LIBS/repos/dns-libs/pull-requests/306/diff#platform/windows/capi/include/ag_dns.h
                message = message.TrimEnd(Environment.NewLine.ToCharArray());
                logByLogLevel(message);
            }
            catch (Exception ex)
            {
                DnsExceptionHandler.HandleManagedException(ex);
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 本接口用来开始一路ISR会话,并在参数中指定本路ISR会话用到的语法列表,本次会话所用的参数等。
        /// </summary>
        /// <param name="grammarList"></param>
        /// <param name="_params"></param>
        /// <returns>会话ID。</returns>
        public static string SessionBegin(string grammarList, string _params)
        {
            MspErrors result = 0;
            IntPtr    ptr    = QISRSessionBegin(grammarList, _params, out result);

            switch (result)
            {
            case MspErrors.MSP_SUCCESS:    //成功
                return(MarshalUtils.Ptr2Str(ptr));

                break;

            case MspErrors.MSP_ERROR_NOT_INIT:
                throw new Exception("未初始化。");

            case MspErrors.MSP_ERROR_INVALID_PARA:
                throw new Exception("无效的参数。");

            case MspErrors.MSP_ERROR_NO_LICENSE:
                throw new Exception("开始一路会话失败。");

            default:
                throw new Exception("QISR会话初始化失败,错误代码: " + result);
            }
        }
Ejemplo n.º 7
0
        public void TestDnsStampConverter()
        {
            DnsStamp dnsStamp = new DnsStamp
            {
                ProtoType     = new AGDnsApi.ag_stamp_proto_type(),
                ServerAddress = "addressTest",
                ProviderName  = "Nametest",
                DoHPath       = "DoHPathTest",
                Hashes        = new List <byte[]>
                {
                    new byte[] { 12, 34, 15 },
                    new byte[] { 10, 8, 16, 3 }
                },
                Properties = new AGDnsApi.ag_server_informal_properties()
            };
            Queue <IntPtr> allocatedPointers = new Queue <IntPtr>();

            AGDnsApi.ag_dns_stamp stampNative = DnsApiConverter.ToNativeObject(dnsStamp, allocatedPointers);
            string address = MarshalUtils.PtrToString(stampNative.ServerAddress);

            Assert.AreEqual(address, dnsStamp.ServerAddress);

            DnsStamp dnsStampConverted = DnsApiConverter.FromNativeObject(stampNative);

            Assert.AreEqual(dnsStamp.ServerAddress, dnsStampConverted.ServerAddress);
            Assert.AreEqual(dnsStamp.Hashes.Count, dnsStampConverted.Hashes.Count);
            for (int i = 0; i < dnsStamp.Hashes.Count; i++)
            {
                Assert.IsTrue(CollectionUtils.CollectionsEquals(dnsStamp.Hashes[i], dnsStampConverted.Hashes[i]));
            }
            Assert.AreEqual(dnsStamp.Hashes.Capacity, dnsStampConverted.Hashes.Capacity);
        }
Ejemplo n.º 8
0
        private LdapSearchResultReference GetLdapReference(SafeHandle ld, IntPtr msg)
        {
            var ctrls = IntPtr.Zero;

            try
            {
                var referencePtr = IntPtr.Zero;
                var rc           = Native.ldap_parse_reference(ld, msg, ref referencePtr, ref ctrls, 0);
                Native.ThrowIfError(ld, rc, nameof(Native.ldap_parse_reference));
                var arr  = MarshalUtils.GetPointerArray(referencePtr);
                var uris = arr.Select(_ => new Uri(Encoder.Instance.PtrToString(_))).ToArray();
                if (uris.Any())
                {
                    return(new LdapSearchResultReference(uris, null));
                }
            }
            finally
            {
                if (ctrls != IntPtr.Zero)
                {
                    Native.ldap_controls_free(ctrls);
                }
            }

            return(null);
        }
Ejemplo n.º 9
0
        public override int SendRequest(SafeHandle handle, DirectoryRequest request, ref int messageId)
        {
            if (request is ModifyRequest modifyRequest)
            {
                if (string.IsNullOrWhiteSpace(modifyRequest.DistinguishedName))
                {
                    throw new ArgumentNullException(nameof(modifyRequest.DistinguishedName));
                }

                var attrs = modifyRequest.Attributes.Select(ToLdapMod).ToList();

                var ptr = Marshal.AllocHGlobal(IntPtr.Size *
                                               (attrs.Count + 1)); // alloc memory for list with last element null
                MarshalUtils.StructureArrayToPtr(attrs, ptr, true);

                var result = Native.ldap_modify_ext(handle,
                                                    modifyRequest.DistinguishedName,
                                                    ptr,
                                                    IntPtr.Zero,
                                                    IntPtr.Zero,
                                                    ref messageId
                                                    );
                attrs.ForEach(_ =>
                {
                    MarshalUtils.BerValuesFree(_.mod_vals_u.modv_bvals);
                    Marshal.FreeHGlobal(_.mod_vals_u.modv_bvals);
                    Marshal.FreeHGlobal(_.mod_type);
                });
                Marshal.FreeHGlobal(ptr);

                return(result);
            }

            return(0);
        }
Ejemplo n.º 10
0
        protected override int SendRequest(SafeHandle handle, DirectoryRequest request, IntPtr serverControlArray, IntPtr clientControlArray, ref int messageId)
        {
            if (request is CompareRequest compareRequest)
            {
                if (string.IsNullOrEmpty(compareRequest.DistinguishedName) ||
                    string.IsNullOrEmpty(compareRequest.Assertion?.Name) ||
                    compareRequest.Assertion.GetRawValues().Count != 1
                    )
                {
                    throw new LdapException(new LdapExceptionData("Wrong assertion"));
                }

                var value       = compareRequest.Assertion.GetRawValues().Single();
                var stringValue = value as string;
                var berValuePtr = IntPtr.Zero;
                if (value is byte[] binaryValue && binaryValue.Length != 0)
                {
                    berValuePtr = MarshalUtils.ByteArrayToBerValue(binaryValue);
                }

                var result = Native.Compare(handle, compareRequest.DistinguishedName, compareRequest.Assertion.Name, stringValue, berValuePtr, serverControlArray, clientControlArray, ref messageId);
                MarshalUtils.BerValFree(berValuePtr);
                return(result);
            }

            return(0);
        }
Ejemplo n.º 11
0
        private static int EncodingMultiByteArrayHelper(BerSafeHandle berElement, byte[][] value, char fmt)
        {
            var stringArray = IntPtr.Zero;
            int rc;

            try
            {
                if (value != null)
                {
                    var intPtrArray = value.Select(_ =>
                    {
                        var byteArray = _ ?? new byte[0];
                        var valPtr    = Marshal.AllocHGlobal(byteArray.Length + 1);
                        Marshal.Copy(byteArray, 0, valPtr, byteArray.Length);
                        Marshal.WriteByte(valPtr, byteArray.Length, 0);
                        return(valPtr);
                    }).Concat(new[] { IntPtr.Zero }).ToArray();

                    stringArray = MarshalUtils.WriteIntPtrArray(intPtrArray);
                }

                rc = LdapNative.Instance.ber_printf_berarray(berElement, new string(fmt, 1), stringArray);
            }
            finally
            {
                MarshalUtils.FreeIntPtrArray(stringArray);
            }

            return(rc);
        }
Ejemplo n.º 12
0
        public static void Init()
        {
            IEngineSubSystem subSystem;

            Program.Core.GetSubSystem(E_ENGINE_SUB_SYSTEM.ESS_FILE_SYSTEM, out subSystem);
            IMainFileSystem mainFileSystem = subSystem as DGLE.IMainFileSystem;

            String[] registredFileSystems = MarshalUtils.MarshalString((pnt, length) =>
            {
                mainFileSystem.GetRegisteredVirtualFileSystems(pnt, out length);
                return(length);
            }).Split(';').ToList().Where(name => name.Trim().Length > 0).ToArray();

            SupportedFileSystems = new Dictionary <string, VirtualFileSystem>(registredFileSystems.Length);
            registredFileSystems.ToList().ForEach(ext =>
            {
                IFileSystem fileSystem;
                mainFileSystem.GetVirtualFileSystem(ext, out fileSystem);

                string desc = MarshalUtils.MarshalString((pnt, length) =>
                {
                    mainFileSystem.GetVirtualFileSystemDescription(ext, pnt, out length);
                    return(length);
                });

                SupportedFileSystems.Add(ext, new VirtualFileSystem(fileSystem, ext, desc));
            });
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Gets current DNS proxy version
        /// </summary>
        /// <returns></returns>
        public static string GetDnsProxyVersion()
        {
            IntPtr pDnsProxyVersion = AGDnsApi.ag_dnsproxy_version();
            string dnsProxyVersion  = MarshalUtils.PtrToString(pDnsProxyVersion);

            return(dnsProxyVersion);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Gets the DNS stamp pretty url specified by <see cref="DnsStamp"/> object
        /// </summary>
        /// <param name="dnsStamp">DNS stamp object
        /// (<seealso cref="DnsStamp"/>)</param>
        /// <returns>DNS stamp as a string</returns>
        public static string GetDnsStampPrettyUrl(DnsStamp dnsStamp)
        {
            IntPtr         pPrettyUrl        = IntPtr.Zero;
            Queue <IntPtr> allocatedPointers = new Queue <IntPtr>();

            try
            {
                AGDnsApi.ag_dns_stamp dnsStampC =
                    DnsApiConverter.ToNativeObject(dnsStamp, allocatedPointers);
                IntPtr pDnsStampC = MarshalUtils.StructureToPtr(dnsStampC, allocatedPointers);
                pPrettyUrl = AGDnsApi.ag_dns_stamp_pretty_url(pDnsStampC);
                string prettyUrl = MarshalUtils.PtrToString(pPrettyUrl);
                return(prettyUrl);
            }
            catch (Exception ex)
            {
                Logger.Verbose("Getting DNS stamp pretty url failed with an error {0}", ex);
                return(null);
            }
            finally
            {
                MarshalUtils.SafeFreeHGlobal(allocatedPointers);
                AGDnsApi.ag_str_free(pPrettyUrl);
            }
        }
Ejemplo n.º 15
0
        public override int SendRequest(SafeHandle handle, DirectoryRequest request, ref int messageId)
        {
            if (request is AddRequest addRequest)
            {
                var entry = addRequest.LdapEntry;
                if (string.IsNullOrWhiteSpace(entry.Dn))
                {
                    throw new ArgumentNullException(nameof(entry.Dn));
                }

                if (entry.Attributes == null)
                {
                    entry.Attributes = new Dictionary <string, List <string> >();
                }

                var attrs = entry.Attributes.Select(ToLdapMod).ToList();

                var ptr = Marshal.AllocHGlobal(IntPtr.Size * (attrs.Count + 1)); // alloc memory for list with last element null
                MarshalUtils.StructureArrayToPtr(attrs, ptr, true);

                return(Native.ldap_add_ext(handle,
                                           addRequest.LdapEntry.Dn,
                                           ptr,
                                           IntPtr.Zero,
                                           IntPtr.Zero,
                                           ref messageId
                                           ));
            }

            return(0);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Gets the DNS stamp string specified by <see cref="DnsStamp"/> object
        /// </summary>
        /// <param name="dnsStamp">DNS stamp object
        /// (<seealso cref="DnsStamp"/>)</param>
        /// <returns>DNS stamp as a string</returns>
        public static string GetDnsStampString(DnsStamp dnsStamp)
        {
            // Don't invoke "dnsStamp.ToString()" within this method to prevent infinite recursion
            Logger.Verbose("Start getting DNS stamp string from {0}",
                           dnsStamp.ServerAddress);
            IntPtr         pDnsStampString   = IntPtr.Zero;
            Queue <IntPtr> allocatedPointers = new Queue <IntPtr>();

            try
            {
                AGDnsApi.ag_dns_stamp dnsStampC =
                    DnsApiConverter.ToNativeObject(dnsStamp, allocatedPointers);
                IntPtr pDnsStampC = MarshalUtils.StructureToPtr(dnsStampC, allocatedPointers);
                pDnsStampString = AGDnsApi.ag_dns_stamp_to_str(pDnsStampC);
                string dnsStampString = MarshalUtils.PtrToString(pDnsStampString);
                Logger.Verbose("Getting DNS stamp string has been successfully completed");
                return(dnsStampString);
            }
            catch (Exception ex)
            {
                Logger.Verbose("Getting DNS stamp string failed with an error {0}", ex);
                return(null);
            }
            finally
            {
                MarshalUtils.SafeFreeHGlobal(allocatedPointers);
                AGDnsApi.ag_str_free(pDnsStampString);
            }
        }
Ejemplo n.º 17
0
        private static int BerScanfaString(BerSafeHandle berElement, char fmt, out object byteArray)
        {
            var result = IntPtr.Zero;

            byteArray = null;

            var rc = LdapNative.Instance.ber_scanf_ptr(berElement, new string(fmt, 1), ref result);

            try
            {
                if (rc != -1 && result != IntPtr.Zero)
                {
                    byteArray = MarshalUtils.GetBytes(result).ToArray();
                }
            }
            finally
            {
                if (result != IntPtr.Zero)
                {
                    LdapNative.Instance.ber_memfree(result);
                }
            }

            return(rc);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// <para>Sets the application name. LibVLC passes this as the user agent string</para>
        /// <para>when a protocol requires it.</para>
        /// </summary>
        /// <param name="name">human-readable application name, e.g. &quot;FooBar player 1.2.3&quot;</param>
        /// <param name="http">HTTP User Agent, e.g. &quot;FooBar/1.2.3 Python/2.6.0&quot;</param>
        /// <remarks>LibVLC 1.1.1 or later</remarks>
        public void SetUserAgent(string name, string http)
        {
            var nameUtf8 = name.ToUtf8();
            var httpUtf8 = http.ToUtf8();

            MarshalUtils.PerformInteropAndFree(() => Native.LibVLCSetUserAgent(NativeReference, nameUtf8, httpUtf8), nameUtf8, httpUtf8);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Managed implementation of CEEInfo::getClassAlignmentRequirementStatic
        /// </summary>
        private static int GetClassAlignmentRequirement(MetadataType type)
        {
            int alignment = type.Context.Target.PointerSize;

            if (type.HasLayout())
            {
                if (type.IsSequentialLayout || MarshalUtils.IsBlittableType(type))
                {
                    alignment = type.InstanceFieldAlignment.AsInt;
                }
            }

            if (type.Context.Target.Architecture == TargetArchitecture.ARM &&
                alignment < 8 && type.RequiresAlign8())
            {
                // If the structure contains 64-bit primitive fields and the platform requires 8-byte alignment for
                // such fields then make sure we return at least 8-byte alignment. Note that it's technically possible
                // to create unmanaged APIs that take unaligned structures containing such fields and this
                // unconditional alignment bump would cause us to get the calling convention wrong on platforms such
                // as ARM. If we see such cases in the future we'd need to add another control (such as an alignment
                // property for the StructLayout attribute or a marshaling directive attribute for p/invoke arguments)
                // that allows more precise control. For now we'll go with the likely scenario.
                alignment = 8;
            }

            return(alignment);
        }
Ejemplo n.º 20
0
        private static int DecodingMultiByteArrayHelper(BerSafeHandle berElement, char fmt, out byte[][] result)
        {
            int rc;
            var ptrResult = IntPtr.Zero;

            result = null;

            try
            {
                rc = LdapNative.Instance.ber_scanf_ptr(berElement, new string(fmt, 1), ref ptrResult);

                if (rc != -1 && ptrResult != IntPtr.Zero)
                {
                    result = MarshalUtils.GetPointerArray(ptrResult)
                             .Select(MarshalUtils.GetBytes)
                             .Select(_ => _.ToArray())
                             .ToArray();
                }
            }
            finally
            {
                if (ptrResult != IntPtr.Zero)
                {
                    LdapNative.Instance.ber_memfree(ptrResult);
                }
            }

            return(rc);
        }
Ejemplo n.º 21
0
        protected override int SendRequest(SafeHandle handle, DirectoryRequest request, IntPtr serverControlArray, IntPtr clientControlArray, ref int messageId)
        {
            if (request is AddRequest addRequest)
            {
                if (string.IsNullOrWhiteSpace(addRequest.DistinguishedName))
                {
                    throw new ArgumentNullException(nameof(addRequest.DistinguishedName));
                }

                var attrs = addRequest.Attributes.Select(ToLdapMod).ToList();

                var ptr = MarshalUtils.AllocHGlobalIntPtrArray(addRequest.Attributes.Count + 1);
                MarshalUtils.StructureArrayToPtr(attrs, ptr, true);

                var result = Native.ldap_add_ext(handle,
                                                 addRequest.DistinguishedName,
                                                 ptr,
                                                 serverControlArray,
                                                 clientControlArray,
                                                 ref messageId
                                                 );

                attrs.ForEach(_ =>
                {
                    MarshalUtils.BerValuesFree(_.mod_vals_u.modv_bvals);
                    Marshal.FreeHGlobal(_.mod_vals_u.modv_bvals);
                    Marshal.FreeHGlobal(_.mod_type);
                });
                Marshal.FreeHGlobal(ptr);

                return(result);
            }

            return(0);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Parses a specified DNS stamp string (<seealso cref="dnsStampStr"/>)
        /// </summary>
        /// <param name="dnsStampStr">DNS stamp string</param>
        /// <returns>DNS stamp as a <see cref="DnsStamp"/> instance</returns>
        internal static DnsStamp ParseDnsStamp(string dnsStampStr)
        {
            LOG.InfoFormat("Start parsing DNS stamp {0}", dnsStampStr);
            IntPtr pDnsStampResult = IntPtr.Zero;

            try
            {
                pDnsStampResult = AGDnsApi.ag_parse_dns_stamp(dnsStampStr);
                AGDnsApi.ag_parse_dns_stamp_result dnsStampResult =
                    MarshalUtils.PtrToStructure <AGDnsApi.ag_parse_dns_stamp_result>(pDnsStampResult);
                if (dnsStampResult.error != IntPtr.Zero)
                {
                    string error = MarshalUtils.PtrToString(dnsStampResult.error);
                    LOG.InfoFormat("Parsing DNS stamp {0} failed with an error {1}",
                                   dnsStampStr,
                                   error);
                    return(null);
                }

                LOG.Info("Parsing DNS stamp has been completed successfully");
                DnsStamp dnsStamp = DnsApiConverter.FromNativeObject(dnsStampResult.stamp);
                return(dnsStamp);
            }
            catch (Exception ex)
            {
                LOG.InfoException("Parsing DNS stamp failed with an error {0}", ex);
                return(null);
            }
            finally
            {
                AGDnsApi.ag_parse_dns_stamp_result_free(pDnsStampResult);
            }
        }
Ejemplo n.º 23
0
        public void Modify(LdapModifyEntry entry)
        {
            ThrowIfNotBound();

            if (string.IsNullOrWhiteSpace(entry.Dn))
            {
                throw new ArgumentNullException(nameof(entry.Dn));
            }

            if (entry.Attributes == null)
            {
                entry.Attributes = new List <LdapModifyAttribute>();
            }

            var attrs = entry.Attributes.Select(ToLdapMod).ToList();

            var ptr = Marshal.AllocHGlobal(IntPtr.Size * (attrs.Count + 1)); // alloc memory for list with last element null

            MarshalUtils.StructureArrayToPtr(attrs, ptr, true);

            try
            {
                ThrowIfError(_ld, ldap_modify_ext_s(_ld,
                                                    entry.Dn,
                                                    ptr,
                                                    IntPtr.Zero,
                                                    IntPtr.Zero
                                                    ), nameof(ldap_modify_ext_s));
            }
            finally
            {
                Marshal.FreeHGlobal(ptr);
                attrs.ForEach(_ => { Marshal.FreeHGlobal(_.mod_vals_u.modv_strvals); });
            }
        }
Ejemplo n.º 24
0
        private static int DecodingBerValMultiByteArrayHelper(BerSafeHandle berElement, char fmt, out byte[][] result)
        {
            int rc;
            var ptrResult = IntPtr.Zero;

            result = null;

            try
            {
                rc = LdapNative.Instance.ber_scanf_ptr(berElement, new string(fmt, 1), ref ptrResult);

                if (rc != -1 && ptrResult != IntPtr.Zero)
                {
                    result = MarshalUtils.BerValArrayToByteArrays(ptrResult).ToArray();
                }
            }
            finally
            {
                if (ptrResult != IntPtr.Zero)
                {
                    LdapNative.Instance.ber_bvecfree(ptrResult);
                }
            }

            return(rc);
        }
Ejemplo n.º 25
0
 /// <summary>
 /// Creates a binary value or ascii value metadata entry from data received from the native layer.
 /// We trust C core to give us well-formed data, so we don't perform any checks or defensive copying.
 /// </summary>
 internal static Entry CreateUnsafe(string key, byte[] valueBytes)
 {
     if (HasBinaryHeaderSuffix(key))
     {
         return(new Entry(key, null, valueBytes));
     }
     return(new Entry(key, MarshalUtils.GetStringASCII(valueBytes), null));
 }
Ejemplo n.º 26
0
 private static void FreeAttributes(IntPtr attributes)
 {
     foreach (var tempPtr in MarshalUtils.GetPointerArray(attributes))
     {
         Marshal.FreeHGlobal(tempPtr);
     }
     Marshal.FreeHGlobal(attributes);
 }
Ejemplo n.º 27
0
        /// <summary>
        /// Close log file handle
        /// </summary>
        /// <returns>true if no file to close or close operation successful, false otherwise</returns>
        public bool CloseLogFile()
        {
            if (_logFileHandle == IntPtr.Zero)
            {
                return(true);
            }

            return(MarshalUtils.Close(_logFileHandle));
        }
Ejemplo n.º 28
0
        public Dictionary(IDictionary dictionary) : this()
        {
            if (dictionary == null)
            {
                throw new NullReferenceException($"Parameter '{nameof(dictionary)} cannot be null.'");
            }

            MarshalUtils.IDictionaryToDictionary(dictionary, GetPtr());
        }
Ejemplo n.º 29
0
 /// <summary>
 /// Media discoverer constructor
 /// </summary>
 /// <param name="libVLC">libvlc instance this will be attached to</param>
 /// <param name="name">name from one of LibVLC.MediaDiscoverers</param>
 public MediaDiscoverer(LibVLC libVLC, string name)
     : base(() =>
 {
     var nameUtf8 = name.ToUtf8();
     return(MarshalUtils.PerformInteropAndFree(() =>
                                               Native.LibVLCMediaDiscovererNew(libVLC.NativeReference, nameUtf8), nameUtf8));
 }, Native.LibVLCMediaDiscovererRelease)
 {
 }
Ejemplo n.º 30
0
        public Array(IEnumerable collection) : this()
        {
            if (collection == null)
            {
                throw new NullReferenceException($"Parameter '{nameof(collection)} cannot be null.'");
            }

            MarshalUtils.EnumerableToArray(collection, GetPtr());
        }