summaryrefslogtreecommitdiff
path: root/src/main/java/com/c2kernel/lookup/ldap/LDAPLookupUtils.java
blob: 0aa0ca65a44e17046621f92dec7093e7e2abf730 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
/*
 * Lookup helper class.
 */

package com.c2kernel.lookup.ldap;

//import netscape.ldap.*;
//import netscape.ldap.util.*;
import com.c2kernel.common.ObjectAlreadyExists;
import com.c2kernel.common.ObjectCannotBeUpdated;
import com.c2kernel.common.ObjectNotFound;
import com.c2kernel.utils.Logger;
import com.novell.ldap.LDAPAttribute;
import com.novell.ldap.LDAPAttributeSet;
import com.novell.ldap.LDAPConnection;
import com.novell.ldap.LDAPDN;
import com.novell.ldap.LDAPEntry;
import com.novell.ldap.LDAPException;
import com.novell.ldap.LDAPModification;
import com.novell.ldap.LDAPSearchConstraints;
import com.novell.ldap.LDAPSearchResults;

/**
 * @version $Revision: 1.74 $ $Date: 2006/03/03 13:52:21 $
 * @author  $Author: abranson $
 */

final public class LDAPLookupUtils
{
    static final char[] META_CHARS = {'+', '=', '"', ',', '<', '>', ';', '/'};
    static final String[] META_ESCAPED = {"2B", "3D", "22", "2C", "3C", "3E", "3B", "2F"};
    static public LDAPEntry getEntry(LDAPConnection ld, String dn,int dereference)
        throws ObjectNotFound
    {
        try {
			LDAPSearchConstraints searchCons = new LDAPSearchConstraints();
	        searchCons.setBatchSize(0);
    	    searchCons.setDereference(dereference);
            LDAPEntry thisEntry = ld.read(dn,searchCons);
            if (thisEntry != null) return thisEntry;
        } catch (LDAPException ex) {
            throw new ObjectNotFound("LDAP Exception for dn:"+dn+": \n"+ex.getMessage());
        }
        throw new ObjectNotFound(dn+" does not exist");

    }
    

    /**
     * Utility method to connect to an LDAP server
     * @param lp LDAP properties to connect with
     * @return a novell LDAPConnection object
     * @throws LDAPException when the connection was unsuccessful
     */
    public static LDAPConnection createConnection(LDAPProperties lp) throws LDAPException {
        LDAPConnection ld = new LDAPConnection();

        Logger.msg(3, "LDAPLookup - connecting to " + lp.mHost);
        ld.connect(lp.mHost, Integer.valueOf(lp.mPort).intValue());

        Logger.msg(3, "LDAPLookup - authenticating user:" + lp.mUser);
        ld.bind( LDAPConnection.LDAP_V3, lp.mUser,
                 String.valueOf(lp.mPassword).getBytes());

        Logger.msg(3, "LDAPLookup - authentication successful");
        LDAPSearchConstraints searchCons = new LDAPSearchConstraints();
        searchCons.setMaxResults(0);
        ld.setConstraints(searchCons);

        return ld;
    }

    //Given a DN, return an LDAP Entry
    static public LDAPEntry getEntry(LDAPConnection ld, String dn)
        throws ObjectNotFound
    {
        return getEntry(ld, dn, LDAPSearchConstraints.DEREF_NEVER);
    }

    static public String getFirstAttributeValue(LDAPEntry anEntry, String attribute) throws ObjectNotFound
    {
        LDAPAttribute attr = anEntry.getAttribute(attribute);
        if (attr==null)
            throw new ObjectNotFound("No attributes named '"+attribute+"'");
        return (String)attr.getStringValues().nextElement();
    }

    static public String[] getAllAttributeValues(LDAPEntry anEntry, String attribute) throws ObjectNotFound
    {
        LDAPAttribute attr = anEntry.getAttribute(attribute);
        if (attr!=null)
            return attr.getStringValueArray();

        throw new ObjectNotFound("No attributes named '"+attribute+"'");

    }

    static public boolean existsAttributeValue(LDAPEntry anEntry, String attribute, String value)
    {
        LDAPAttribute attr = anEntry.getAttribute(attribute);
        if (attr!=null)
        {
            String[] attrValues = new String[attr.size()];
            attrValues = attr.getStringValueArray();
            for (int i=0;i<attr.size();i++)
                if (attrValues[i].equalsIgnoreCase(value))
                    return true;
        }
        return false;
    }
	static public boolean hasOneAttributeValue(LDAPEntry anEntry, String attribute) throws ObjectNotFound
	{
		int j =0;
		LDAPAttribute attr = anEntry.getAttribute(attribute);
		if (attr==null)
            throw new ObjectNotFound("No attributes named '"+attribute+"'");
		j=attr.size();
		return j==1;
	}

	//this is for a single-valued attribute
    static public void setAttributeValue(LDAPConnection ld, LDAPEntry anEntry, String attribute, String newValue)
    throws ObjectNotFound, ObjectCannotBeUpdated
    {
        try {
            if (!hasOneAttributeValue(anEntry, attribute))
                throw new ObjectCannotBeUpdated("Attribute "+attribute + " of entry " + anEntry.getDN()+" has more than one value");
        } catch (ObjectNotFound ex) {
            addAttributeValue(ld, anEntry, attribute, newValue);
        }
        try
        {
       		ld.modify(anEntry.getDN(),new LDAPModification(LDAPModification.REPLACE,new LDAPAttribute(attribute,newValue)));
        }
        catch (LDAPException ex)
        {
            Logger.error(ex);
            throw new ObjectCannotBeUpdated("Attribute " + attribute + " of entry " + anEntry.getDN() + " could not be modified");
        }
    }


	//this is for a multi-valued attribute eg uniqueMember
    static public void addAttributeValue(LDAPConnection ld, LDAPEntry anEntry, String attribute, String value)
    throws ObjectCannotBeUpdated
    {
        try
        {
            ld.modify(anEntry.getDN(),new LDAPModification(LDAPModification.ADD, new LDAPAttribute(attribute,value)));
        }
        catch (LDAPException ex)
        {
            Logger.error(ex);
            throw new ObjectCannotBeUpdated("Attribute " + attribute + " of entry " + anEntry.getDN() + " could not be added.");
        }
    }

    //this is for a multi-valued attribute eg uniqueMember
    static public void removeAttributeValue(LDAPConnection ld, LDAPEntry anEntry, String attribute, String value)
    throws ObjectCannotBeUpdated
    {
            try
            {
       			ld.modify(anEntry.getDN(),new LDAPModification(LDAPModification.DELETE,new LDAPAttribute(attribute,value)));
			}
            catch (LDAPException ex)
            {
                Logger.error(ex);
                throw new ObjectCannotBeUpdated("Attribute " + attribute + " of entry " + anEntry.getDN() + " could not be deleted");
            }
    }

    static public boolean exists(LDAPConnection ld, String name)
    {
        try {
            String[] attr = { LDAPConnection.NO_ATTRS };
            LDAPEntry anEntry=ld.read(name,attr);
            if (anEntry!=null)
                return true;
        } catch (LDAPException ex)
        {
            Logger.debug(9, "LDAPLookupUtils.exists("+name+": "+ex.getMessage());
            return false;
        }
        return false;
    }

    static public void addEntry(LDAPConnection ld,LDAPEntry myEntry)
    throws ObjectAlreadyExists, LDAPException
    {
        try
        {
            ld.add( myEntry );
        }
        catch( LDAPException ex ) {
            if (ex.getResultCode() == LDAPException.ENTRY_ALREADY_EXISTS)
                throw new ObjectAlreadyExists("Entry already present." + myEntry.getDN());
            throw ex;
        }
    }

    static public boolean hasChildren(LDAPConnection ld, String dn, String filter)
    {
        String[] attr = { LDAPConnection.NO_ATTRS };
        LDAPSearchConstraints searchCons = new LDAPSearchConstraints();
        searchCons.setBatchSize(0);
        searchCons.setDereference(LDAPSearchConstraints.DEREF_NEVER);

        try
        {
            LDAPSearchResults res = ld.search(dn,LDAPConnection.SCOPE_ONE,filter,attr,false,searchCons);
            if (res.hasMore())
                return true;
        }
        catch (LDAPException ex)
        {
            Logger.error(ex);
        }
        return false;
    }

    //returns list of dns
    static public String[] getChildrenDNs(LDAPConnection ld, String dn, String filter)
    {
        String[] result = null;
        String[] attr = { LDAPConnection.NO_ATTRS };
        LDAPSearchConstraints searchCons = new LDAPSearchConstraints();
        searchCons.setBatchSize(0);
        searchCons.setDereference(LDAPSearchConstraints.DEREF_NEVER);

        try
        {
            LDAPSearchResults res = ld.search(dn,LDAPConnection.SCOPE_ONE,filter,attr,false,searchCons);
            result = new String[res.getCount()];
            int i=0;
            while (res.hasMore())
            {
                LDAPEntry findEntry=res.next();
                if (findEntry!=null)
                {
                    result[i++] = new String(findEntry.getDN());
                }
            }
        }
        catch (Exception ex)
        {
            Logger.error(ex);
        }
        return result;
    }

    static public void delete(LDAPConnection ld, String dn)
    throws LDAPException
    {
        try
        {
            Logger.msg(7, "LDAPLookupUtils.delete() - "+dn);
            ld.delete(dn);
        }
        catch (LDAPException ex)
        {
            Logger.error("LDAPLookupUtils.remove() - Cannot remove "+dn+": " + ex.getMessage());
            throw ex;
        }
    }

    //param dn is the DN of the name
    //param name is the name of the node (also the RDN)
    //example: cn=lab27,o=cern.ch  lab27
    //example: cn=product, cn=domain, cn=lab27, cn= cristal2, o=cern.ch  product
    static public void createCristalContext(LDAPConnection ld, String dn)
    {
    	if (LDAPLookupUtils.exists(ld,dn))
    		return;
        try
        {
            String name = LDAPDN.explodeDN(dn,true)[0];
            LDAPAttributeSet attrs = new LDAPAttributeSet();
            attrs.add(new LDAPAttribute("cn",name));
            String objectclass_values[] = new String[1];
            objectclass_values[0] = "cristalcontext";
            if (name.equals("last"))
            	attrs.add(new LDAPAttribute("intsyskey", "0"));

    		attrs.add(new LDAPAttribute("objectclass",objectclass_values));

            LDAPLookupUtils.addEntry(ld,new LDAPEntry(dn,attrs));
        }
        catch (Exception ex)
        {
            Logger.error("LDAPLookupUtils.createCristalContext() " + ex.toString());
        }
    }

    static public void createOrganizationContext(LDAPConnection ld, String dn)
    {
    	if (LDAPLookupUtils.exists(ld,dn))
    		return;

        try
        {
            String name = LDAPDN.explodeDN(dn,true)[0];
            LDAPAttributeSet attrs = new LDAPAttributeSet();
            //No idea why this worked, or why it suddenly stopped working when we moved to maven
            //attrs.add(new LDAPAttribute("objectclass","top"));
            attrs.add(new LDAPAttribute("objectclass","organization"));
            attrs.add(new LDAPAttribute("o",name));
            LDAPLookupUtils.addEntry(ld,new LDAPEntry(dn,attrs));
        }
        catch (Exception ex)
        {
            Logger.msg(ex.toString());
        }
    }
    
    public static String escapeDN (String name) {
        //From RFC 2253 and the / character for JNDI
        if (name == null) return null;
        String escapedStr = new String(name);

        //Backslash is both a Java and an LDAP escape character, so escape it first
        escapedStr = escapedStr.replaceAll("\\\\","\\\\");

        //Positional characters - see RFC 2253
        escapedStr = escapedStr.replaceAll("^#","\\\\23");  // TODO: active directory requires hash to be escaped everywhere
        escapedStr = escapedStr.replaceAll("^ | $","\\\\20");

        for (int i=0; i<META_CHARS.length; i++) {
            escapedStr = escapedStr.replaceAll("\\"+META_CHARS[i],"\\\\"+ META_ESCAPED[i]);
        }
        if (!name.equals(escapedStr)) Logger.msg(3, "LDAP DN "+name+" escaped to "+escapedStr);
        return escapedStr;
    }
    
    public static String unescapeDN (String dn) {
        //From RFC 2253 and the / character for JNDI
        String unescapedStr = new String(dn);

        //Positional characters - see RFC 2253
        unescapedStr = unescapedStr.replaceAll("^\\\\23", "#");  // TODO: active directory requires hash to be escaped everywhere
        unescapedStr = unescapedStr.replaceAll("^\\\\20|\\\\20$", " ");

        for (int i=0; i<META_CHARS.length; i++) {
        	unescapedStr = unescapedStr.replaceAll("\\\\" + META_ESCAPED[i], ""+META_CHARS[i]);
        }

        //Any remaining escaped backslashes
        unescapedStr = unescapedStr.replaceAll("\\\\","\\");
        
        if (!dn.equals(unescapedStr)) Logger.msg(3, "LDAP DN "+dn+" unescaped to "+unescapedStr);
        return unescapedStr;
    }

    public static String escapeSearchFilter (String filter) {
        //From RFC 2254
        String escapedStr = new String(filter);

        escapedStr = escapedStr.replaceAll("\\\\","\\\\5c");
        //escapedStr = escapedStr.replaceAll("\\*","\\\\2a"); // we need stars for searching
        escapedStr = escapedStr.replaceAll("\\(","\\\\28");
        escapedStr = escapedStr.replaceAll("\\)","\\\\29");
        if (!filter.equals(escapedStr)) Logger.msg(3, "LDAP Search Filter "+filter+" escaped to "+escapedStr);
        return escapedStr;
    }
}