// read and print search results public static bool searchDynamicGroupEntry( LdapConnection lc, String searchBase) { bool status = true; int searchScope = LdapConnection.SCOPE_BASE; String[] attrList = new String[]{"member"}; String searchFilter = "(objectclass=*)"; /* Since reading members of a dynamic group could potentially involve * a significant directory search, we use a timeout. Setting * time out to 10 seconds */ LdapSearchConstraints cons = new LdapSearchConstraints(); cons.TimeLimit = 10000 ; try { LdapSearchResults searchResults = lc.Search( searchBase, searchScope, searchFilter, attrList, // return only "member" attr false, // return attrs and values cons ); // time out value LdapEntry nextEntry = null ; // Read and print search results. We expect only one entry */ if (( nextEntry = searchResults.next()) != null ) { LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); IEnumerator allAttributes = attributeSet.GetEnumerator(); if ( allAttributes.MoveNext() ) { // found member(s) in this group LdapAttribute attribute = (LdapAttribute)allAttributes.Current; String attributeName = attribute.Name; IEnumerator allValues = attribute.StringValues; if( allValues != null) { while(allValues.MoveNext()) { String Value = (String) allValues.Current; Console.WriteLine(" " + attributeName + " : " + Value); } } } else { // no member(s) found in this group Console.WriteLine(" No objects matched the " + " memberQueryURL filter.\n "); } } } catch( LdapException e ) { Console.WriteLine( "Error: " + e.ToString() ); status = false; } return status; }
private async Task <LdapControl[]> RetrievePageAsync <T>( [NotNull] SearchOptions options, [NotNull] LdapSearchConstraints searchConstraints, [NotNull] List <T> mappedResultsAccumulator, [NotNull] Func <LdapEntry, T> converter, CancellationToken cancellationToken = default) { if (searchConstraints == null) { throw new ArgumentNullException(nameof(searchConstraints)); } if (mappedResultsAccumulator == null) { throw new ArgumentNullException(nameof(mappedResultsAccumulator)); } var asyncSearchResults = await _ldapConnection.SearchAsync( options.SearchBase, LdapConnection.ScopeSub, options.Filter, options.TargetAttributes, false, searchConstraints, cancellationToken ).ConfigureAwait(false); var searchResults = await asyncSearchResults.ToListAsync(cancellationToken).ConfigureAwait(false); mappedResultsAccumulator.AddRange(searchResults.Select(converter)); return(asyncSearchResults.ResponseControls); }
/// <summary> Constructs an LdapSearchConstraints object initialized with values /// from an existing constraints object (LdapConstraints /// or LdapSearchConstraints). /// </summary> public LdapSearchConstraints(LdapConstraints cons) : base(cons.TimeLimit, cons.ReferralFollowing, cons.getReferralHandler(), cons.HopLimit) { InitBlock(); LdapControl[] lsc = cons.getControls(); if (lsc != null) { LdapControl[] generated_var = new LdapControl[lsc.Length]; lsc.CopyTo(generated_var, 0); base.setControls(generated_var); } Hashtable lp = cons.Properties; if (lp != null) { base.Properties = (Hashtable)lp.Clone(); } if (cons is LdapSearchConstraints) { LdapSearchConstraints scons = (LdapSearchConstraints)cons; this.serverTimeLimit = scons.ServerTimeLimit; this.dereference = scons.Dereference; this.maxResults = scons.MaxResults; this.batchSize = scons.BatchSize; } }
private LdapControl[] RetrievePage <T>( [NotNull] SearchOptions options, [NotNull] LdapSearchConstraints searchConstraints, [NotNull] List <T> mappedResultsAccumulator, [NotNull] Func <LdapEntry, T> converter) { if (searchConstraints == null) { throw new ArgumentNullException(nameof(searchConstraints)); } if (mappedResultsAccumulator == null) { throw new ArgumentNullException(nameof(mappedResultsAccumulator)); } var searchResults = _ldapConnection.Search( options.SearchBase, LdapConnection.ScopeSub, options.Filter, options.TargetAttributes, false, searchConstraints ); mappedResultsAccumulator.AddRange(searchResults.Select(converter)); return(searchResults.ResponseControls); }
/// <summary> Constructs an LdapSearchConstraints object initialized with values /// from an existing constraints object (LdapConstraints /// or LdapSearchConstraints). /// </summary> public LdapSearchConstraints(LdapConstraints cons) : base(cons.TimeLimit, cons.ReferralFollowing, cons.getReferralHandler(), cons.HopLimit) { InitBlock(); LdapControl[] lsc = cons.getControls(); if (lsc != null) { LdapControl[] generated_var = new LdapControl[lsc.Length]; lsc.CopyTo(generated_var, 0); setControls(generated_var); } System.Collections.Hashtable lp = cons.Properties; if (lp != null) { Properties = (System.Collections.Hashtable)lp.Clone(); } if (cons is LdapSearchConstraints) { LdapSearchConstraints scons = (LdapSearchConstraints)cons; serverTimeLimit = scons.ServerTimeLimit; dereference = scons.Dereference; maxResults = scons.MaxResults; batchSize = scons.BatchSize; } // Get a unique connection name for debug }
private static bool PrepareForNextPage( [CanBeNull] LdapControl[] pageResponseControls, int pageSize, bool isInitialCall, ref LdapSearchConstraints searchConstraints) { var cookie = SimplePagedResultsControl.GetEmptyCookie; if (!isInitialCall) { var pagedResultsControl = (SimplePagedResultsControl)pageResponseControls?.SingleOrDefault(x => x is SimplePagedResultsControl); if (pagedResultsControl == null) { throw new LdapException($"Failed to find <{nameof(SimplePagedResultsControl)}>. Searching is abruptly stopped"); } // server signaled end of result set if (pagedResultsControl.IsEmptyCookie()) { return(false); } cookie = pagedResultsControl.Cookie; } searchConstraints = ApplyPagedResultsControl(searchConstraints, pageSize, cookie); return(true); }
private static LdapSearchConstraints ApplyPagedResultsControl(LdapSearchConstraints searchConstraints, int pageSize, [CanBeNull] byte[] cookie) { var ldapPagedControl = new SimplePagedResultsControl(pageSize, cookie); searchConstraints.BatchSize = 0; searchConstraints.SetControls(ldapPagedControl); return(searchConstraints); }
public SearchOptions( [NotNull] string searchBase, int scope, [NotNull] string filter, [NotNull] string[] targetAttributes, bool typesOnly, LdapSearchConstraints searchConstraints) { SearchBase = searchBase ?? throw new ArgumentNullException(nameof(searchBase)); Scope = scope; Filter = filter ?? throw new ArgumentNullException(nameof(filter)); TargetAttributes = targetAttributes; TypesOnly = typesOnly; SearchConstraints = searchConstraints; }
private int _referenceIndex; // Current position in vector // private ArrayList referralConn = null; // Referral Connections /// <summary> /// Constructs a queue object for search results. /// </summary> /// <param name="queue"> /// The queue for the search results. /// </param> /// <param name="cons"> /// The LdapSearchConstraints associated with this search. /// </param> internal LdapSearchResults(LdapSearchQueue queue, LdapSearchConstraints cons) { // setup entry Vector _cons = cons; var requestedBatchSize = cons.BatchSize; _entries = new ArrayList(requestedBatchSize == 0 ? 64 : requestedBatchSize); _entryCount = 0; _entryIndex = 0; // setup search reference Vector _references = new List<string[]>(5); _referenceCount = 0; _referenceIndex = 0; _queue = queue; _batchSize = requestedBatchSize == 0 ? int.MaxValue : requestedBatchSize; }
private readonly LdapSearchConstraints cons; // LdapSearchConstraints for search //private ArrayList referralConn = null; // Referral Connections /// <summary> /// Constructs a queue object for search results. /// </summary> /// <param name="conn"> /// The LdapConnection which initiated the search /// </param> /// <param name="queue"> /// The queue for the search results. /// </param> /// <param name="cons"> /// The LdapSearchConstraints associated with this search /// </param> internal LdapSearchResults(LdapConnection conn, LdapSearchQueue queue, LdapSearchConstraints cons) { // setup entry Vector this.cons = cons; var requestedBatchSize = cons.BatchSize; entries = new ArrayList(requestedBatchSize == 0 ? 64 : requestedBatchSize); entryCount = 0; entryIndex = 0; // setup search reference Vector references = new ArrayList(5); referenceCount = 0; referenceIndex = 0; this.queue = queue; this.batchSize = requestedBatchSize == 0 ? int.MaxValue : requestedBatchSize; }
private System.Collections.ArrayList referralConn = null; // Referral Connections /// <summary> Constructs a queue object for search results. /// /// </summary> /// <param name="conn">The LdapConnection which initiated the search /// /// </param> /// <param name="queue">The queue for the search results. /// /// </param> /// <param name="cons">The LdapSearchConstraints associated with this search /// </param> /* package */ internal LdapSearchResults(LdapConnection conn, LdapSearchQueue queue, LdapSearchConstraints cons) { // setup entry Vector this.conn = conn; this.cons = cons; int batchSize = cons.BatchSize; int vectorIncr = (batchSize == 0) ? 64 : 0; entries = new System.Collections.ArrayList((batchSize == 0) ? 64 : batchSize); entryCount = 0; entryIndex = 0; // setup search reference Vector references = new System.Collections.ArrayList(5); referenceCount = 0; referenceIndex = 0; this.queue = queue; this.batchSize = (batchSize == 0) ? Int32.MaxValue : batchSize; }
private void InitBlock() { defSearchCons = new LdapSearchConstraints(); responseCtlSemaphore = new System.Object(); }
/// <summary>Searches the directory /// </summary> /// <param name="searchBase">Where to start the search</param> /// <param name="searchScope">Scope of search</param> /// <param name="searchFilter">Filter to search for</param> /// <param name="searchAttrs">Attributes to search for</param> /// <returns>List of entries matching filter</returns> public LdapEntry[] Search(string searchBase, int searchScope, string searchFilter, string[] searchAttrs) { if (!conn.Connected) return null; try { List<LdapEntry> retVal = new List<LdapEntry> (); RfcFilter rfcFilter = new RfcFilter (searchFilter); LdapSearchConstraints cons = new LdapSearchConstraints (); cons.MaxResults = 0; LdapSearchQueue queue = conn.Search (searchBase, searchScope, rfcFilter.filterToString(), searchAttrs, false, (LdapSearchQueue) null, cons); LdapMessage msg; while ((msg = queue.getResponse ()) != null) { if (msg is LdapSearchResult) { LdapEntry entry = ((LdapSearchResult) msg).Entry; retVal.Add (entry); } } return retVal.ToArray (); } catch (Exception e) { Log.Debug (e); return null; } }
/// <summary> Asynchronously 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. 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. /// /// </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="queue"> The queue for messages returned from a server in /// response to this request. If it is null, a /// queue object is created internally. /// /// </param> /// <param name="cons"> The constraints specific to the search. /// /// </param> /// <exception> LdapException A general exception which includes an error /// message and an Ldap error code. /// </exception> public virtual LdapSearchQueue Search(System.String base_Renamed, int scope, System.String filter, System.String[] attrs, bool typesOnly, LdapSearchQueue queue, LdapSearchConstraints cons) { if ((System.Object) filter == null) { filter = "objectclass=*"; } if (cons == null) cons = defSearchCons; LdapMessage msg = new LdapSearchRequest(base_Renamed, scope, filter, attrs, cons.Dereference, cons.MaxResults, cons.ServerTimeLimit, typesOnly, cons.getControls()); MessageAgent agent; LdapSearchQueue myqueue = queue; if (myqueue == null) { agent = new MessageAgent(); myqueue = new LdapSearchQueue(agent); } else { agent = queue.MessageAgent; } try { agent.sendMessage(conn, msg, cons.TimeLimit, myqueue, null); } catch (LdapException lex) { throw lex; } return myqueue; }
/// <summary> /// Synchronously performs the search specified by the parameters, /// using the specified search constraints (such as the /// maximum number of entries to find or the maximum time to wait for /// search results). /// /// As part of the search constraints, the method allows specifying /// whether or not the results are to be delivered all at once or in /// smaller batches. If specified that the results are to be delivered in /// smaller batches, each iteration blocks only until the next batch of /// results is returned. /// /// </summary> /// <param name="base"> 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. /// /// </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="cons"> The constraints specific to the search. /// /// </param> /// <exception> LdapException A general exception which includes an error /// message and an Ldap error code. /// </exception> public virtual LdapSearchResults Search(System.String base_Renamed, int scope, System.String filter, System.String[] attrs, bool typesOnly, LdapSearchConstraints cons) { LdapSearchQueue queue = Search(base_Renamed, scope, filter, attrs, typesOnly, null, cons); if (cons == null) cons = defSearchCons; return new LdapSearchResults(this, queue, cons); }
/// <summary> Synchronously reads the entry specified by the Ldap URL, using the /// specified constraints. /// /// When this method is called, a new connection is created /// automatically, using the host and port specified in the URL. After /// finding the entry, the method closes the connection (in other words, /// it disconnects from the Ldap server). /// /// If the URL specifies a filter and scope, they are not used. Of the /// information specified in the URL, this method only uses the Ldap host /// name and port number, the base distinguished name (DN), and the list /// of attributes to return. /// /// </summary> /// <returns> The entry specified by the base DN. /// /// </returns> /// <param name="toGet"> Ldap URL specifying the entry to read. /// /// </param> /// <param name="cons"> Constraints specific to the operation. /// /// </param> /// <exception> LdapException if the object was not found /// </exception> public static LdapEntry Read(LdapUrl toGet, LdapSearchConstraints cons) { LdapConnection lconn = new LdapConnection(); lconn.Connect(toGet.Host, toGet.Port); LdapEntry toReturn = lconn.Read(toGet.getDN(), toGet.AttributeArray, cons); lconn.Disconnect(); return toReturn; }
/// <summary> Synchronously reads the entry for the specified distinguished name (DN), /// using the specified constraints, and retrieves only the specified /// attributes from the entry. /// /// </summary> /// <param name="dn"> The distinguished name of the entry to retrieve. /// /// </param> /// <param name="attrs"> The names of the attributes to retrieve. /// /// </param> /// <param name="cons"> The constraints specific to the operation. /// /// </param> /// <returns> the LdapEntry read from the server /// /// </returns> /// <exception> LdapException if the object was not found /// </exception> public virtual LdapEntry Read(System.String dn, System.String[] attrs, LdapSearchConstraints cons) { LdapSearchResults sr = Search(dn, SCOPE_BASE, null, attrs, false, cons); LdapEntry ret = null; if (sr.hasMore()) { ret = sr.next(); if (sr.hasMore()) { // "Read response is ambiguous, multiple entries returned" throw new LdapLocalException(ExceptionMessages.READ_MULTIPLE, LdapException.AMBIGUOUS_RESPONSE); } } return ret; }
/// <summary> /// Synchronously reads the entry for the specified distiguished name (DN), /// using the specified constraints, and retrieves all attributes for the /// entry. /// /// </summary> /// <param name="dn"> The distinguished name of the entry to retrieve. /// /// </param> /// <param name="cons"> The constraints specific to the operation. /// /// </param> /// <returns> the LdapEntry read from the server /// /// </returns> /// <exception> LdapException if the object was not found /// </exception> public virtual LdapEntry Read(System.String dn, LdapSearchConstraints cons) { return Read(dn, null, cons); }
public static void Main( String[] args ) { if (args.Length != 4) { Console.WriteLine("Usage: mono ListGroups <host name> <login dn>" + " <password> <group dn>\n"); Console.WriteLine("Example: mono ListGroups Acme.com" + " \"cn=admin,o=Acme\" secret " + " cn=salesGroup,ou=sales,o=acme\n"); Environment.Exit(0); } int ldapPort = LdapConnection.DEFAULT_PORT; int searchScope = LdapConnection.SCOPE_BASE; int ldapVersion = LdapConnection.Ldap_V3; int i; IEnumerator objClass = null; IEnumerator queryURL = null; IEnumerator identity = null; IEnumerator excludedMember = null; IEnumerator member = null; bool isGroup=false, isDynamicGroup=false; String[] attrs = new String[] { "objectClass", "memberQueryURL", "dgIdentity", "excludedMember", "member"}; /* Since reading members of a dynamic group could potentially involve * a significant directory search, we use a timeout. Setting * time out to 10 seconds */ LdapSearchConstraints cons = new LdapSearchConstraints(); cons.TimeLimit = 10000 ; String ldapHost = args[0]; String loginDN = args[1]; String password = args[2]; String groupDN = args[3]; LdapConnection lc = new LdapConnection(); try { // connect to the server lc.Connect( ldapHost, ldapPort ); // bind to the server lc.Bind( ldapVersion, loginDN, password ); Console.WriteLine("\n\tReading object :" + groupDN); LdapSearchResults searchResults = lc.Search( groupDN, // object to read searchScope, // scope - read single object null, // search filter attrs, // return only required attributes false, // return attrs and values cons ); // time out value // Examine the attributes that were returned and extract the data LdapEntry nextEntry = null; try { nextEntry = searchResults.next(); } catch(LdapException e) { Console.WriteLine("Error: " + e.ToString()); Environment.Exit(1); } LdapAttributeSet attributeSet = nextEntry.getAttributeSet(); IEnumerator allAttributes = attributeSet.GetEnumerator(); while(allAttributes.MoveNext()) { LdapAttribute attribute = (LdapAttribute)allAttributes.Current; String attributeName = attribute.Name; // Save objectclass values if (attributeName.ToUpper().Equals( "objectClass".ToUpper() ) ) { objClass = attribute.StringValues; } // Save the memberQueryURL attribute if present else if (attributeName.ToUpper().Equals( "memberQueryURL".ToUpper() )) { queryURL = attribute.StringValues; } // Save the dgIdentity attribute if present else if (attributeName.ToUpper().Equals( "dgIdentity".ToUpper() ) ) { identity = attribute.StringValues; } // Save the excludedMember attribute if present else if (attributeName.ToUpper().Equals( "excludedMember".ToUpper() )) { excludedMember = attribute.StringValues; } /* Save the member attribute. This may also show up * as uniqueMember */ else if ( attributeName.ToUpper().Equals ( "member".ToUpper() ) || attributeName.ToUpper().Equals ( "uniqueMember".ToUpper() ) ) { member = attribute.StringValues; } } /* Verify that this is a group object (i.e. objectClass contains * the value "group", "groupOfNames", or "groupOfUniqueNames"). * Also determine if this is a dynamic group object * (i.e. objectClass contains the value "dynamicGroup" or * "dynamicGroupAux"). */ while(objClass.MoveNext()) { String objectName = (String) objClass.Current; if ( objectName.ToUpper().Equals( "group".ToUpper() ) || objectName.ToUpper().Equals( "groupOfNames".ToUpper() ) || objectName.ToUpper().Equals( "groupOfUniqueNames".ToUpper()) ) isGroup = true; else if ( objectName.ToUpper().Equals( "dynamicGroup".ToUpper() ) || objectName.ToUpper().Equals( "dynamicGroupAux".ToUpper() ) ) isGroup = isDynamicGroup = true; } if (!isGroup) { Console.WriteLine("\tThis object is NOT a group object." + "Exiting.\n"); Environment.Exit(0); } /* If this is a dynamic group, display its memberQueryURL, identity * and excluded member list. */ if ( isDynamicGroup ) { if ( (queryURL != null)&& (queryURL.MoveNext()) ) { Console.WriteLine("\tMember Query URL:"); while (queryURL.MoveNext()) Console.WriteLine("\t\t" + queryURL.Current); } if ( (identity != null) && (identity.MoveNext()) ) { Console.WriteLine("\tIdentity for search:" + identity.Current); } if ( (excludedMember != null) && (excludedMember.MoveNext()) ) { Console.WriteLine("\tExcluded member list:"); while (excludedMember.MoveNext()) Console.WriteLine("\t\t" + excludedMember.Current); } } // Print the goup's member list if( member != null && member.MoveNext() ) { Console.WriteLine("\n\tMember list:"); while ( member.MoveNext() ) Console.WriteLine("\t\t" + member.Current); } // disconnect with the server lc.Disconnect(); } catch( LdapException e ) { Console.WriteLine( "Error: " + e.ToString() ); Environment.Exit(1); } catch( Exception e ) { Console.WriteLine( "Error: " + e.ToString() ); } Environment.Exit(0); }
private LdapSearchResults LookupLdapUser(bool retrieveGroupMembership, string username, out LdapConnection conn) { conn = Bind(); username = EscapeLdapString(username); //search filter is built based on passed userQuery with username substitution string searchFilter = this.BuildUserSearchQuery(username); //Build interesting attribute list List<string> attrs = new List<string>(); attrs.AddRange(new string[] { "sAMAccountName", "uid", "cn", "userAccountControl", "whenCreated", "name", "givenname", "sn", "telephonenumber", "mail", "description" }); if (retrieveGroupMembership) { attrs.Add(_config.GroupMembersAttribute); } if (!string.IsNullOrEmpty(_config.UserNameAttribute) && !attrs.Contains(_config.UserNameAttribute)) { attrs.Add(_config.UserNameAttribute); } //add more attributes to lookup if using a displayname-pattern string[] patternAttributes = RetrieveAttributesFromPattern(_config.DisplayNamePattern); if (patternAttributes != null) { foreach (string patternAttribute in patternAttributes) { if (!attrs.Contains(patternAttribute)) attrs.Add(patternAttribute); } } LdapSearchConstraints cons = new LdapSearchConstraints(new LdapConstraints(_timeLimit, true, null, 0)); cons.BatchSize = 0; LdapSearchResults results = conn.Search(_config.LdapSearchBase, LdapConnection.SCOPE_SUB, searchFilter, attrs.ToArray(), false, cons); return results; }
private void PopulateGroupsForUserWithQuery(XDoc doc, string username, LdapConnection conn) { doc.Start("groups"); string searchFilter = string.Format(Dream.PhpUtil.ConvertToFormatString(_config.GroupMembershipQuery), username); //Build interesting attribute list List<string> attrs = new List<string>(); attrs.AddRange(new string[] { "whenCreated", "name", "sAMAccountName", "cn" }); LdapSearchConstraints cons = new LdapSearchConstraints(new LdapConstraints(_timeLimit, true, null, 0)); cons.BatchSize = 0; LdapSearchResults results = conn.Search(_config.LdapSearchBase, LdapConnection.SCOPE_SUB, searchFilter, attrs.ToArray(), false, cons); while (results.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = results.next(); } catch (LdapException x) { HandleLdapException(x); } if (nextEntry == null) throw new ArgumentNullException("nextEntry"); //Create xml from search entry doc.Start("group").Attr("name", GetNameFromDn(nextEntry.DN)).Start("ldap-dn").Value(nextEntry.DN).End().End(); } doc.End(); //groups }
/// <summary> /// Retrieves group information from ldap /// </summary> /// <param name="retrieveGroupMembers">true to return users in each group. This may hurt performance</param> /// <param name="optionalGroupName">Group to lookup by name. Null for all groups</param> /// <returns></returns> public XDoc GetGroupInfo(bool retrieveGroupMembers, string optionalGroupName) { LdapConnection conn = null; XDoc resultXml = null; try { //Confirm a query bind has been established conn = Bind(); string searchFilter; //Build the searchfilter based on if a group name is given. if (!string.IsNullOrEmpty(optionalGroupName)) { optionalGroupName = EscapeLdapString(optionalGroupName); //Looking up group by name searchFilter = string.Format(PhpUtil.ConvertToFormatString(_config.GroupQuery), optionalGroupName); } else { //Looking up all groups searchFilter = _config.GroupQueryAll; } //Build interesting attribute list List<string> attrs = new List<string>(); attrs.AddRange(new string[] { "whenCreated", "name", "sAMAccountName", "cn" }); if (retrieveGroupMembers) { attrs.Add("member"); } if (!string.IsNullOrEmpty(_config.GroupNameAttribute) && !attrs.Contains(_config.GroupNameAttribute)) { attrs.Add(_config.GroupNameAttribute); } LdapSearchConstraints cons = new LdapSearchConstraints(new LdapConstraints(_timeLimit, true, null, 0)); cons.BatchSize = 0; LdapSearchResults results = conn.Search(_config.LdapSearchBase, LdapConnection.SCOPE_SUB, searchFilter, attrs.ToArray(), false, cons); //Create outer groups collection if multiple groups are being looked up or none provided if (string.IsNullOrEmpty(optionalGroupName)) resultXml = new XDoc("groups"); while (results.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = results.next(); } catch (LdapException x) { HandleLdapException(x); continue; } //Create xml from search entry if (resultXml == null) resultXml = new XDoc("group"); else resultXml.Start("group"); string name = string.Empty; //If a groupnameattribute is configured, use that. Otherwise try the common ones. if (!string.IsNullOrEmpty(_config.GroupNameAttribute)) { name = GetAttributeSafe(nextEntry, _config.GroupNameAttribute); } else { name = GetAttributeSafe(nextEntry, "sAMAccountName"); //MS Active Directory if (string.IsNullOrEmpty(name)) name = GetAttributeSafe(nextEntry, "uid"); //OpenLDAP if (string.IsNullOrEmpty(name)) name = GetAttributeSafe(nextEntry, "name"); //OpenLDAP if (string.IsNullOrEmpty(name)) name = GetAttributeSafe(nextEntry, "cn"); //Novell eDirectory } resultXml.Attr("name", name); resultXml.Start("ldap-dn").Value(nextEntry.DN).End(); resultXml.Start("date.created").Value(ldapStringToDate(GetAttributeSafe(nextEntry, "whenCreated"))).End(); //Retrieve and write group membership to xml LdapAttributeSet memberAttrSet = nextEntry.getAttributeSet(); LdapAttribute memberAttr = memberAttrSet.getAttribute("member"); // TODO MaxM: This currently does not differentiate between user and group // members. if (memberAttr != null) { foreach (string member in memberAttr.StringValueArray) { resultXml.Start("member"); resultXml.Attr("name", GetNameFromDn(member)); resultXml.Start("ldap-dn").Value(member).End(); resultXml.End(); } } if (string.IsNullOrEmpty(optionalGroupName)) resultXml.End(); } } finally { UnBind(conn); } return resultXml; }
private System.Collections.ArrayList referralConn = null; // Referral Connections /// <summary> Constructs a queue object for search results. /// /// </summary> /// <param name="conn">The LdapConnection which initiated the search /// /// </param> /// <param name="queue">The queue for the search results. /// /// </param> /// <param name="cons">The LdapSearchConstraints associated with this search /// </param> /* package */ internal LdapSearchResults(LdapConnection conn, LdapSearchQueue queue, LdapSearchConstraints cons) { // setup entry Vector this.conn = conn; this.cons = cons; int batchSize = cons.BatchSize; int vectorIncr = (batchSize == 0)?64:0; entries = new System.Collections.ArrayList((batchSize == 0)?64:batchSize); entryCount = 0; entryIndex = 0; // setup search reference Vector references = new System.Collections.ArrayList(5); referenceCount = 0; referenceIndex = 0; this.queue = queue; this.batchSize = (batchSize == 0)?System.Int32.MaxValue:batchSize; return ; }
static void Main(string[] args) { if ( args.Length != 5) { Console.WriteLine("Usage: mono SearchPersist <host name> <ldap port> <login dn>" + " <password> <search base>" ); Console.WriteLine("Example: mono SearchPersist Acme.com 389" + " \"cn=admin,o=Acme\"" + " secret \"ou=sales,o=Acme\""); return; } int ldapVersion = LdapConnection.Ldap_V3; String ldapHost = args[0]; int ldapPort = Convert.ToInt32(args[1]);; String loginDN = args[2]; String password = args[3]; String searchBase = args[4]; LdapSearchQueue queue = null; LdapSearchConstraints constraints; LdapPersistSearchControl psCtrl; LdapConnection lc = new LdapConnection(); constraints = new LdapSearchConstraints(); try { // connect to the server lc.Connect( ldapHost, ldapPort ); // authenticate to the server lc.Bind(ldapVersion, loginDN, password); //Create the persistent search control psCtrl = new LdapPersistSearchControl( LdapPersistSearchControl.ANY, // any change true, //only get changes true, //return entry change controls true); //control is critcal // add the persistent search control to the search constraints constraints.setControls( psCtrl ); // perform the search with no attributes returned String[] noAttrs = {LdapConnection.NO_ATTRS}; queue = lc.Search( searchBase, // container to search LdapConnection.SCOPE_SUB, // search container's subtree "(objectClass=*)", // search filter, all objects noAttrs, // don't return attributes false, // return attrs and values, ignored null, // use default search queue constraints); // use default search constraints } catch( LdapException e ) { Console.WriteLine( "Error: " + e.ToString() ); try { lc.Disconnect(); } catch(LdapException e2) { } Environment.Exit(1); } catch(Exception e) { Console.WriteLine( "Error: " + e.Message ); return; } Console.WriteLine("Monitoring the events for {0} minutes..", TIME_OUT_IN_MINUTES ); Console.WriteLine(); //Set the timeout value timeOut= DateTime.Now.AddMinutes(TIME_OUT_IN_MINUTES); try { //Monitor till the timeout happens while (DateTime.Now.CompareTo(timeOut) < 0) { if (!checkForAChange(queue)) break; System.Threading.Thread.Sleep(10); } } catch (System.IO.IOException e) { System.Console.Out.WriteLine(e.Message); } catch (System.Threading.ThreadInterruptedException e) { } //Disconnect from the server before exiting try { lc.Abandon(queue); //abandon the search lc.Disconnect(); } catch (LdapException e) { Console.Out.WriteLine(); Console.Out.WriteLine("Error: " + e.ToString()); } Environment.Exit(0); }
/* * Ldap URL search */ /// <summary> Synchronously perfoms the search specified by the Ldap URL, using /// the specified search constraints (such as the maximum number of /// entries to find or the maximum time to wait for search results). /// /// When this method is called, a new connection is created /// automatically, using the host and port specified in the URL. After /// all search results have been received from the server, the method /// closes the connection (in other words, it disconnects from the Ldap /// server). /// /// As part of the search constraints, a choice can be made as to whether /// to have the results delivered all at once or in smaller batches. If /// the results are to be delivered in smaller batches, each iteration /// blocks only until the next batch of results is returned. /// /// /// </summary> /// <param name="toGet"> Ldap URL specifying the entry to read. /// /// </param> /// <param name="cons"> The constraints specific to the search. /// /// </param> /// <exception> LdapException A general exception which includes an error /// message and an Ldap error code. /// </exception> public static LdapSearchResults Search(LdapUrl toGet, LdapSearchConstraints cons) { LdapConnection lconn = new LdapConnection(); lconn.Connect(toGet.Host, toGet.Port); if (cons == null) { // This is a clone, so we already have our own copy cons = lconn.SearchConstraints; } else { // get our own copy of user's constraints because we modify it cons = (LdapSearchConstraints) cons.Clone(); } cons.BatchSize = 0; // Must wait until all results arrive LdapSearchResults toReturn = lconn.Search(toGet.getDN(), toGet.Scope, toGet.Filter, toGet.AttributeArray, false, cons); lconn.Disconnect(); return toReturn; }