public string[] SearchAndGetDN(String searchDN, LdapScope scope, string filter, string[] attributes, int attrsOnly, ref ILdapMessage ldMsg)
        {
            string[]     dn;
            ILdapMessage searchRequest = null;

            MaintainSession(delegate() {
                searchRequest = ldConn.LdapSearchExtS(searchDN, (int)scope, filter, attributes, attrsOnly, IntPtr.Zero, 0);
            });
            ldMsg = searchRequest;
            if (ldMsg == null)
            {
                throw new Exception("Failed to do LDAP Search possibly due to lost connection. Close connection and try again");
            }
            List <ILdapEntry> entries = ldMsg.GetEntries();

            if (entries.Count <= 0)
            {
                return(null);
            }
            dn = new string[entries.Count];
            int i = 0;

            foreach (LdapEntry entry in entries)
            {
                dn [i++] = entry.getDN();
            }
            (ldMsg as LdapMessage).FreeMessage();
            return(dn);
        }
示例#2
0
 public IEnumerable<LdapEntry> Search(string searchBase, LdapScope scope,string filter)
 {
     var lsc = connection.Search(searchBase, (int)scope, filter, null, false);
     while (lsc.hasMore())
     {
         yield return lsc.next();
     }
 }
示例#3
0
        public IEnumerable <LdapEntry> Search(string searchBase, LdapScope scope, string filter)
        {
            var lsc = connection.Search(searchBase, (int)scope, filter, null, false);

            while (lsc.hasMore())
            {
                yield return(lsc.next());
            }
        }
示例#4
0
        /// <summary>
        ///     Performs the search specified by the parameters,
        ///     also allowing specification of constraints for the search (such
        ///     as the maximum number of entries to find or the maximum time to
        ///     wait for search results).
        /// </summary>
        /// <param name="base">The base distinguished name to search from.</param>
        /// <param name="scope">The scope of the entries to search.</param>
        /// <param name="filter">The search filter specifying the search criteria.</param>
        /// <param name="attrs">The names of attributes to retrieve.</param>
        /// <param name="typesOnly">
        ///     If true, returns the names but not the values of
        ///     the attributes found.  If false, returns the
        ///     names and values for attributes found.
        /// </param>
        /// <param name="ct">The cancellation token.</param>
        /// <returns>
        ///     A <see cref="Task" /> representing the asynchronous operation.
        /// </returns>
        public async Task <LdapSearchResults> Search(string @base, LdapScope scope, string filter = "objectClass=*", string[] attrs = null, bool typesOnly = false, CancellationToken ct = default)
        {
            // TODO: Add Search options
            var msg = new LdapSearchRequest(@base, scope, filter, attrs, 0, 1000, 0, typesOnly, null);

            await RequestLdapMessage(msg, ct);

            return(new LdapSearchResults(Messages, msg.MessageId));
        }
示例#5
0
 public LdapEntry SearchOne(string searchBase, LdapScope scope, string filter)
 {
     var lsc = connection.Search(searchBase, (int)scope, filter, null, false);
     LdapEntry result = null;
     while (lsc.hasMore())
     {
         result = lsc.next();
         break;
     }
     return result;
 }
示例#6
0
        public LdapEntry SearchOne(string searchBase, LdapScope scope, string filter)
        {
            var       lsc    = connection.Search(searchBase, (int)scope, filter, null, false);
            LdapEntry result = null;

            while (lsc.hasMore())
            {
                result = lsc.next();
                break;
            }
            return(result);
        }
示例#7
0
 public RfcSearchRequest(string basePath, LdapScope scope, int derefAliases, int sizeLimit, int timeLimit, bool typesOnly, string filter, string[] attributes)
     : base(8)
 {
     Add(basePath);
     Add(new Asn1Enumerated(scope));
     Add(new Asn1Enumerated(derefAliases));
     Add(new Asn1Integer(sizeLimit));
     Add(new Asn1Integer(timeLimit));
     Add(new Asn1Boolean(typesOnly));
     Add(new RfcFilter(filter));
     Add(new RfcAttributeDescriptionList(attributes));
 }
示例#8
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LdapSearchRequest"/> class.
 /// </summary>
 /// <param name="ldapBase">The base distinguished name to search from.</param>
 /// <param name="scope">The scope of the entries to search. The following
 /// are the valid options:.
 /// <ul><li>SCOPE_BASE - searches only the base DN</li><li>SCOPE_ONE - searches only entries under the base DN</li><li>
 /// SCOPE_SUB - searches the base DN and all entries
 /// within its subtree
 /// </li></ul></param>
 /// <param name="filter">The search filter specifying the search criteria.</param>
 /// <param name="attrs">The names of attributes to retrieve.
 /// operation exceeds the time limit.</param>
 /// <param name="dereference">Specifies when aliases should be dereferenced.
 /// Must be one of the constants defined in
 /// LdapConstraints, which are DEREF_NEVER,
 /// DEREF_FINDING, DEREF_SEARCHING, or DEREF_ALWAYS.</param>
 /// <param name="maxResults">The maximum number of search results to return
 /// for a search request.
 /// The search operation will be terminated by the server
 /// with an LdapException.SIZE_LIMIT_EXCEEDED if the
 /// number of results exceed the maximum.</param>
 /// <param name="serverTimeLimit">The maximum time in seconds that the server
 /// should spend returning search results. This is a
 /// server-enforced limit.  A value of 0 means
 /// no time limit.</param>
 /// <param name="typesOnly">If true, returns the names but not the values of
 /// the attributes found.  If false, returns the
 /// names and values for attributes found.</param>
 /// <param name="cont">Any controls that apply to the search request.
 /// or null if none.</param>
 /// <seealso cref="LdapConnection.Search"></seealso>
 public LdapSearchRequest(
     string ldapBase,
     LdapScope scope,
     string filter,
     string[] attrs,
     int dereference,
     int maxResults,
     int serverTimeLimit,
     bool typesOnly,
     LdapControl[] cont)
     : base(
         LdapOperation.SearchRequest,
         new RfcSearchRequest(ldapBase, scope, dereference, maxResults, serverTimeLimit, typesOnly, filter, attrs),
         cont)
 {
 }
        public List <ILdapEntry> SearchAndGetEntries(String searchDN, LdapScope scope, string filter, string[] attribsToReturn, int attrsOnly, ref ILdapMessage ldMsg)
        {
            List <ILdapEntry> entries;
            ILdapMessage      searchRequest = null;

            //Cannot free ldMsg in this function  as we lose the references to entries. Free the ldMsg in the calling function.
            MaintainSession(delegate() {
                searchRequest = ldConn.LdapSearchExtS(searchDN, (int)scope, filter, attribsToReturn, attrsOnly, IntPtr.Zero, 0);
            });
            ldMsg = searchRequest;
            if (ldMsg == null)
            {
                throw new Exception("Failed to do LDAP Search possibly due to lost connection. Close connection and try again");
            }
            entries = ldMsg.GetEntries();
            return(entries);
        }
示例#10
0
        private bool TrySearchSimple(string searchBase, LdapScope scope, string searchFilter, out List <LdapObject> results,
                                     string[] attributes = null, int limit = -1, LdapSearchConstraints searchConstraints = null)
        {
            try
            {
                results = SearchSimple(searchBase, scope, searchFilter, attributes, limit, searchConstraints);

                return(true);
            }
            catch (Exception ex)
            {
                _log.ErrorFormat("TrySearchSimple() failed. Error: {0}", ex);
            }

            results = null;
            return(false);
        }
示例#11
0
        public List <ILdapEntry> SearchAndGetEntries(String searchDN, LdapScope scope, string filter, string[] attribsToReturn, int attrsOnly, ref ILdapMessage ldMsg)
        {
            List <ILdapEntry> entries;
            ILdapMessage      searchRequest = null;

            //Cannot free ldMsg in this function  as we lose the references to entries. Free the ldMsg in the calling function.
            MaintainSession(delegate()
            {
                searchRequest = ldConn.LdapSearchExtS(searchDN, (int)scope, filter, attribsToReturn, attrsOnly, IntPtr.Zero, 0);
            });
            ldMsg = searchRequest;
            if (ldMsg == null)
            {
                throw new Exception(VMDirConstants.ERR_SERVER_CONNECTION_LOST);
            }
            entries = ldMsg.GetEntries();
            return(entries);
        }
示例#12
0
        public TextQueryDTO(string searchBase, LdapScope searchScope, string filterString, string[] attrToReturn,

                            int attrOnly, IntPtr timeOut, int sizeLimit)

        {
            this.SearchBase = searchBase;

            this.SearchScope = searchScope;

            this.AttrToReturn = attrToReturn;

            this.AttrOnly = attrOnly;

            this.TimeOut = timeOut;

            this.SizeLimit = sizeLimit;

            this.FilterString = filterString;
        }
        public void Search(String searchDN, LdapScope scope, string filter, string[] attribsToReturn, int attrsOnly, Action <ILdapMessage, List <ILdapEntry> > fn)
        {
            List <ILdapEntry> entries;
            ILdapMessage      searchRequest = null;

            MaintainSession(delegate()
            {
                searchRequest = ldConn.LdapSearchExtS(searchDN, (int)scope, filter, attribsToReturn, attrsOnly, IntPtr.Zero, 0);
            });
            if (searchRequest == null)
            {
                throw new Exception("Failed to do LDAP Search possibly due to lost connection. Close connection and try again");
            }

            entries = searchRequest.GetEntries();
            if (fn != null)
            {
                fn(searchRequest, entries);
            }
        }
示例#14
0
        public BuildQueryDTO(string searchBase, LdapScope searchScope, LogicalOp op, List <FilterDTO> condList,

                             string[] attrToReturn, int attrOnly, IntPtr timeOut, int sizeLimit)

        {
            this.SearchBase = searchBase;

            this.SearchScope = searchScope;

            this.AttrToReturn = attrToReturn;

            this.AttrOnly = attrOnly;

            this.TimeOut = timeOut;

            this.SizeLimit = sizeLimit;

            this.Operator = op;

            this.CondList = condList;
        }
示例#15
0
        public List <LdapObject> SearchSimple(string searchBase, LdapScope scope, string searchFilter,
                                              string[] attributes = null, int limit = -1, LdapSearchConstraints searchConstraints = null)
        {
            if (!IsConnected)
            {
                Connect();
            }

            if (searchBase == null)
            {
                searchBase = "";
            }

            var entries = new List <LdapEntry>();

            if (string.IsNullOrEmpty(searchFilter))
            {
                return(new List <LdapObject>());
            }

            if (attributes == null)
            {
                if (string.IsNullOrEmpty(LdapUniqueIdAttribute))
                {
                    attributes = new[]
                    {
                        "*", LdapConstants.RfcLDAPAttributes.ENTRY_DN, LdapConstants.RfcLDAPAttributes.ENTRY_UUID,
                        LdapConstants.RfcLDAPAttributes.NS_UNIQUE_ID, LdapConstants.RfcLDAPAttributes.GUID
                    };
                }
                else
                {
                    attributes = new[] { "*", LdapUniqueIdAttribute };
                }
            }

            var ldapSearchConstraints = searchConstraints ?? new LdapSearchConstraints
            {
                // Maximum number of search results to return.
                // The value 0 means no limit. The default is 1000.
                MaxResults = limit == -1 ? 0 : limit,
                // Returns the number of results to block on during receipt of search results.
                // This should be 0 if intermediate results are not needed, and 1 if results are to be processed as they come in.
                //BatchSize = 0,
                // The maximum number of referrals to follow in a sequence during automatic referral following.
                // The default value is 10. A value of 0 means no limit.
                HopLimit = 0,
                // Specifies whether referrals are followed automatically
                // Referrals of any type other than to an LDAP server (for example, a referral URL other than ldap://something) are ignored on automatic referral following.
                // The default is false.
                ReferralFollowing = true,
                // The number of seconds to wait for search results.
                // Sets the maximum number of seconds that the server is to wait when returning search results.
                //ServerTimeLimit = 600000, // 10 minutes
                // Sets the maximum number of milliseconds the client waits for any operation under these constraints to complete.
                // If the value is 0, there is no maximum time limit enforced by the API on waiting for the operation results.
                //TimeLimit = 600000 // 10 minutes
            };

            // initially, cookie must be set to an empty string
            var pageSize = 2;

            sbyte[] cookie = Array.ConvertAll(Encoding.ASCII.GetBytes(""), b => unchecked ((sbyte)b));
            var     i      = 0;

            do
            {
                var requestControls = new LdapControl[1];
                requestControls[0] = new LdapPagedResultsControl(pageSize, cookie);
                ldapSearchConstraints.setControls(requestControls);
                _ldapConnection.Constraints = ldapSearchConstraints;

                var res = _ldapConnection.Search(searchBase,
                                                 (int)scope, searchFilter, attributes, false, (LdapSearchConstraints)null);

                while (res.hasMore())
                {
                    LdapEntry nextEntry;
                    try
                    {
                        nextEntry = res.next();

                        if (nextEntry == null)
                        {
                            continue;
                        }
                    }
                    catch (LdapException ex)
                    {
                        if (ex is LdapReferralException)
                        {
                            continue;
                        }

                        if (!string.IsNullOrEmpty(ex.Message) && ex.Message.Contains("Sizelimit Exceeded"))
                        {
                            break;
                        }

                        _log.ErrorFormat("SearchSimple({0}) error: {1}", searchFilter, ex);
                        continue;
                    }

                    _log.DebugFormat("{0}. DN: {1}", ++i, nextEntry.DN);

                    entries.Add(nextEntry);

                    if (string.IsNullOrEmpty(LdapUniqueIdAttribute))
                    {
                        LdapUniqueIdAttribute = GetLdapUniqueId(nextEntry);
                    }
                }

                // Server should send back a control irrespective of the
                // status of the search request
                var controls = res.ResponseControls;
                if (controls == null)
                {
                    _log.Debug("No controls returned");
                    cookie = null;
                }
                else
                {
                    // Multiple controls could have been returned
                    foreach (LdapControl control in controls)
                    {
                        /* Is this the LdapPagedResultsResponse control? */
                        if (!(control is LdapPagedResultsResponse))
                        {
                            continue;
                        }

                        var response = new LdapPagedResultsResponse(control.ID,
                                                                    control.Critical, control.getValue());

                        cookie = response.Cookie;
                    }
                }
                // if cookie is empty, we are done.
            } while (cookie != null && cookie.Length > 0);

            var result = entries.ToLdapObjects(LdapUniqueIdAttribute);

            return(result);
        }
示例#16
0
        public static List <string> GetObjectClassList(VMDirServerDTO ServerDTO, string searchBase, LdapScope searchScope)
        {
            QueryDTO qdto   = new TextQueryDTO(searchBase, searchScope, VMDirConstants.SEARCH_ALL_OC, null, 0, IntPtr.Zero, 0);
            var      ocList = new List <string>();

            ServerDTO.Connection.Search(qdto,
                                        (l, e) =>
            {
                if (e.Count > 0)
                {
                    ocList = new List <string>(e[0].getAttributeValues(VMDirConstants.ATTR_OBJECT_CLASS).Select(x => x.StringValue).ToArray());
                }
            });
            return(ocList);
        }
示例#17
0
        public List <LdapObject> Search(string searchBase, LdapScope scope, string searchFilter,
                                        string[] attributes = null, int limit = -1, LdapSearchConstraints searchConstraints = null)
        {
            if (!IsConnected)
            {
                Connect();
            }

            if (searchBase == null)
            {
                searchBase = "";
            }

            var entries = new List <LdapEntry>();

            if (string.IsNullOrEmpty(searchFilter))
            {
                return(new List <LdapObject>());
            }

            if (attributes == null)
            {
                if (string.IsNullOrEmpty(LdapUniqueIdAttribute))
                {
                    attributes = new[]
                    {
                        "*", LdapConstants.RfcLDAPAttributes.ENTRY_DN, LdapConstants.RfcLDAPAttributes.ENTRY_UUID,
                        LdapConstants.RfcLDAPAttributes.NS_UNIQUE_ID, LdapConstants.RfcLDAPAttributes.GUID
                    };
                }
                else
                {
                    attributes = new[] { "*", LdapUniqueIdAttribute };
                }
            }

            var ldapSearchConstraints = searchConstraints ?? new LdapSearchConstraints
            {
                // Maximum number of search results to return.
                // The value 0 means no limit. The default is 1000.
                MaxResults = limit == -1 ? 0 : limit,
                // Returns the number of results to block on during receipt of search results.
                // This should be 0 if intermediate results are not needed, and 1 if results are to be processed as they come in.
                //BatchSize = 0,
                // The maximum number of referrals to follow in a sequence during automatic referral following.
                // The default value is 10. A value of 0 means no limit.
                HopLimit = 0,
                // Specifies whether referrals are followed automatically
                // Referrals of any type other than to an LDAP server (for example, a referral URL other than ldap://something) are ignored on automatic referral following.
                // The default is false.
                ReferralFollowing = true,
                // The number of seconds to wait for search results.
                // Sets the maximum number of seconds that the server is to wait when returning search results.
                //ServerTimeLimit = 600000, // 10 minutes
                // Sets the maximum number of milliseconds the client waits for any operation under these constraints to complete.
                // If the value is 0, there is no maximum time limit enforced by the API on waiting for the operation results.
                //TimeLimit = 600000 // 10 minutes
            };

            var queue = _ldapConnection.Search(searchBase,
                                               (int)scope, searchFilter, attributes, false, ldapSearchConstraints);

            while (queue.hasMore())
            {
                LdapEntry nextEntry;
                try
                {
                    nextEntry = queue.next();

                    if (nextEntry == null)
                    {
                        continue;
                    }
                }
                catch (LdapException ex)
                {
                    if (!string.IsNullOrEmpty(ex.Message) && ex.Message.Contains("Sizelimit Exceeded"))
                    {
                        if (!string.IsNullOrEmpty(Login) && !string.IsNullOrEmpty(Password) && limit == -1)
                        {
                            _log.Warn("The size of the search results is limited. Start TrySearchSimple()");

                            List <LdapObject> simpleResults;

                            if (TrySearchSimple(searchBase, scope, searchFilter, out simpleResults, attributes, limit,
                                                searchConstraints))
                            {
                                if (entries.Count >= simpleResults.Count)
                                {
                                    break;
                                }

                                return(simpleResults);
                            }
                        }

                        break;
                    }

                    _log.ErrorFormat("Search({0}) error: {1}", searchFilter, ex);
                    continue;
                }

                entries.Add(nextEntry);

                if (string.IsNullOrEmpty(LdapUniqueIdAttribute))
                {
                    LdapUniqueIdAttribute = GetLdapUniqueId(nextEntry);
                }
            }

            var result = entries.ToLdapObjects(LdapUniqueIdAttribute);

            return(result);
        }
示例#18
0
 public List <LdapObject> Search(LdapScope scope, string searchFilter,
                                 string[] attributes = null, int limit = -1, LdapSearchConstraints searchConstraints = null)
 {
     return(Search("", scope, searchFilter, attributes, limit, searchConstraints));
 }
        public List<ILdapEntry> SearchAndGetEntries (String searchDN, LdapScope scope, string filter, string[] attribsToReturn, int attrsOnly, ref ILdapMessage ldMsg)
        {
            List<ILdapEntry> entries;
            ILdapMessage searchRequest = null;

            //Cannot free ldMsg in this function  as we lose the references to entries. Free the ldMsg in the calling function.
            MaintainSession (delegate() {
                searchRequest = ldConn.LdapSearchExtS (searchDN, (int)scope, filter, attribsToReturn, attrsOnly, IntPtr.Zero, 0);
            });
            ldMsg = searchRequest;
            if (ldMsg == null)
                throw new Exception ("Failed to do LDAP Search possibly due to lost connection. Close connection and try again");
            entries = ldMsg.GetEntries ();
            return entries;
        }
 public string[] SearchAndGetDN (String searchDN, LdapScope scope, string filter, string[] attributes, int attrsOnly, ref ILdapMessage ldMsg)
 {
     string[] dn;
     ILdapMessage searchRequest = null;
     MaintainSession (delegate() {
         searchRequest = ldConn.LdapSearchExtS (searchDN, (int)scope, filter, attributes, attrsOnly, IntPtr.Zero, 0);
     });
     ldMsg = searchRequest;
     if (ldMsg == null)
         throw new Exception ("Failed to do LDAP Search possibly due to lost connection. Close connection and try again");
     List<ILdapEntry> entries = ldMsg.GetEntries ();
     if (entries.Count <= 0)
         return null;
     dn = new string[entries.Count];
     int i = 0;
     foreach (LdapEntry entry in entries) {
         dn [i++] = entry.getDN ();
     }
     (ldMsg as LdapMessage).FreeMessage ();
     return dn;
 }