mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

Matthew Swift
30.25.2013 ad636a8035cc19f5a412b6b97b3f95ba37d0fe9a
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at legal-notices/CDDLv1_0.txt
 * or http://forgerock.org/license/CDDLv1.0.html.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at legal-notices/CDDLv1_0.txt.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information:
 *      Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 *
 *      Copyright 2013 ForgeRock AS.
 */
package org.forgerock.opendj.ldap;
 
import static org.forgerock.opendj.ldap.Attributes.singletonAttribute;
import static org.forgerock.opendj.ldap.Entries.modifyEntry;
import static org.forgerock.opendj.ldap.ErrorResultException.newErrorResult;
import static org.forgerock.opendj.ldap.responses.Responses.newBindResult;
import static org.forgerock.opendj.ldap.responses.Responses.newCompareResult;
import static org.forgerock.opendj.ldap.responses.Responses.newResult;
import static org.forgerock.opendj.ldap.responses.Responses.newSearchResultEntry;
 
import java.io.IOException;
import java.util.NavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
 
import org.forgerock.i18n.LocalizedIllegalArgumentException;
import org.forgerock.opendj.ldap.controls.AssertionRequestControl;
import org.forgerock.opendj.ldap.controls.PostReadRequestControl;
import org.forgerock.opendj.ldap.controls.PostReadResponseControl;
import org.forgerock.opendj.ldap.controls.PreReadRequestControl;
import org.forgerock.opendj.ldap.controls.PreReadResponseControl;
import org.forgerock.opendj.ldap.controls.SubtreeDeleteRequestControl;
import org.forgerock.opendj.ldap.requests.AddRequest;
import org.forgerock.opendj.ldap.requests.BindRequest;
import org.forgerock.opendj.ldap.requests.CompareRequest;
import org.forgerock.opendj.ldap.requests.DeleteRequest;
import org.forgerock.opendj.ldap.requests.ExtendedRequest;
import org.forgerock.opendj.ldap.requests.GenericBindRequest;
import org.forgerock.opendj.ldap.requests.ModifyDNRequest;
import org.forgerock.opendj.ldap.requests.ModifyRequest;
import org.forgerock.opendj.ldap.requests.Request;
import org.forgerock.opendj.ldap.requests.SearchRequest;
import org.forgerock.opendj.ldap.requests.SimpleBindRequest;
import org.forgerock.opendj.ldap.responses.BindResult;
import org.forgerock.opendj.ldap.responses.CompareResult;
import org.forgerock.opendj.ldap.responses.ExtendedResult;
import org.forgerock.opendj.ldap.responses.Result;
import org.forgerock.opendj.ldap.schema.Schema;
import org.forgerock.opendj.ldif.EntryReader;
 
/**
 * A simple in memory back-end which can be used for testing. It is not intended
 * for production use due to various limitations. The back-end implementations
 * supports the following:
 * <ul>
 * <li>add, bind (simple), compare, delete, modify, and search operations, but
 * not modifyDN nor extended operations
 * <li>assertion, pre-, and post- read controls, subtree delete control, and
 * permissive modify control
 * <li>thread safety - supports concurrent operations
 * </ul>
 * It does not support the following:
 * <ul>
 * <li>high performance
 * <li>secure password storage
 * <li>schema checking
 * <li>persistence
 * <li>indexing
 * </ul>
 * This class can be used in conjunction with the factories defined in
 * {@link Connections} to create simpler servers as well as mock LDAP
 * connections. For example, to create a mock LDAP connection factory:
 *
 * <pre>
 * MemoryBackend backend = new MemoryBackend();
 * Connection connection = newInternalConnectionFactory(newServerConnectionFactory(backend), null)
 *         .getConnection();
 * </pre>
 */
public final class MemoryBackend implements RequestHandler<RequestContext> {
    private final DecodeOptions decodeOptions;
    private final ConcurrentSkipListMap<DN, Entry> entries = new ConcurrentSkipListMap<DN, Entry>();
    private final Object writeLock = new Object();
    private final Schema schema;
 
    /**
     * Creates a new empty memory backend which will use the default schema.
     */
    public MemoryBackend() {
        this(Schema.getDefaultSchema());
    }
 
    /**
     * Creates a new memory backend which will use the default schema, and will
     * contain the entries read from the provided entry reader.
     *
     * @param reader
     *            The entry reader.
     * @throws IOException
     *             If an unexpected IO error occurred while reading the entries.
     */
    public MemoryBackend(final EntryReader reader) throws IOException {
        this(Schema.getDefaultSchema(), reader);
    }
 
    /**
     * Creates a new empty memory backend which will use the provided schema.
     *
     * @param schema
     *            The schema to use for decoding filters, etc.
     */
    public MemoryBackend(final Schema schema) {
        this.schema = schema;
        this.decodeOptions = new DecodeOptions().setSchema(schema);
    }
 
    /**
     * Creates a new memory backend which will use the provided schema, and will
     * contain the entries read from the provided entry reader.
     *
     * @param schema
     *            The schema to use for decoding filters, etc.
     * @param reader
     *            The entry reader.
     * @throws IOException
     *             If an unexpected IO error occurred while reading the entries.
     */
    public MemoryBackend(final Schema schema, final EntryReader reader) throws IOException {
        this.schema = schema;
        this.decodeOptions = new DecodeOptions().setSchema(schema);
        if (reader != null) {
            try {
                while (reader.hasNext()) {
                    final Entry entry = reader.readEntry();
                    final DN dn = entry.getName();
                    if (entries.containsKey(dn)) {
                        throw new ErrorResultIOException(newErrorResult(
                                ResultCode.ENTRY_ALREADY_EXISTS, "Attempted to add the entry '"
                                        + dn.toString() + "' multiple times"));
                    } else {
                        entries.put(dn, entry);
                    }
                }
            } finally {
                reader.close();
            }
        }
    }
 
    @Override
    public void handleAdd(final RequestContext requestContext, final AddRequest request,
            final IntermediateResponseHandler intermediateResponseHandler,
            final ResultHandler<Result> resultHandler) {
        try {
            synchronized (writeLock) {
                final DN dn = request.getName();
                final DN parent = dn.parent();
                if (entries.containsKey(dn)) {
                    throw newErrorResult(ResultCode.ENTRY_ALREADY_EXISTS, "The entry '"
                            + dn.toString() + "' already exists");
                } else if (!entries.containsKey(parent)) {
                    noSuchObject(parent);
                } else {
                    entries.put(dn, request);
                }
            }
            resultHandler.handleResult(getResult(request, null, request));
        } catch (final ErrorResultException e) {
            resultHandler.handleErrorResult(e);
        }
    }
 
    @Override
    public void handleBind(final RequestContext requestContext, final int version,
            final BindRequest request,
            final IntermediateResponseHandler intermediateResponseHandler,
            final ResultHandler<BindResult> resultHandler) {
        try {
            final Entry entry;
            synchronized (writeLock) {
                final DN username = DN.valueOf(request.getName(), schema);
                final byte[] password;
                if (request instanceof SimpleBindRequest) {
                    password = ((SimpleBindRequest) request).getPassword();
                } else if (request instanceof GenericBindRequest
                        && request.getAuthenticationType() == BindRequest.AUTHENTICATION_TYPE_SIMPLE) {
                    password = ((GenericBindRequest) request).getAuthenticationValue();
                } else {
                    throw newErrorResult(ResultCode.PROTOCOL_ERROR,
                            "non-SIMPLE authentication not supported: "
                                    + request.getAuthenticationType());
                }
                entry = getRequiredEntry(null, username);
                if (!entry.containsAttribute("userPassword", password)) {
                    throw newErrorResult(ResultCode.INVALID_CREDENTIALS, "Wrong password");
                }
            }
            resultHandler.handleResult(getBindResult(request, entry, entry));
        } catch (final LocalizedIllegalArgumentException e) {
            resultHandler.handleErrorResult(newErrorResult(ResultCode.PROTOCOL_ERROR, e));
        } catch (final EntryNotFoundException e) {
            /*
             * Usually you would not include a diagnostic message, but we'll add
             * one here because the memory back-end is not intended for
             * production use.
             */
            resultHandler.handleErrorResult(newErrorResult(ResultCode.INVALID_CREDENTIALS,
                    "Unknown user"));
        } catch (final ErrorResultException e) {
            resultHandler.handleErrorResult(e);
        }
    }
 
    @Override
    public void handleCompare(final RequestContext requestContext, final CompareRequest request,
            final IntermediateResponseHandler intermediateResponseHandler,
            final ResultHandler<CompareResult> resultHandler) {
        try {
            final Entry entry;
            final Attribute assertion;
            synchronized (writeLock) {
                final DN dn = request.getName();
                entry = getRequiredEntry(request, dn);
                assertion =
                        singletonAttribute(request.getAttributeDescription(), request
                                .getAssertionValue());
            }
            resultHandler.handleResult(getCompareResult(request, entry, entry.containsAttribute(
                    assertion, null)));
        } catch (final ErrorResultException e) {
            resultHandler.handleErrorResult(e);
        }
    }
 
    @Override
    public void handleDelete(final RequestContext requestContext, final DeleteRequest request,
            final IntermediateResponseHandler intermediateResponseHandler,
            final ResultHandler<Result> resultHandler) {
        try {
            final Entry entry;
            synchronized (writeLock) {
                final DN dn = request.getName();
                entry = getRequiredEntry(request, dn);
                if (request.getControl(SubtreeDeleteRequestControl.DECODER, decodeOptions) != null) {
                    // Subtree delete.
                    entries.subMap(dn, dn.child(RDN.maxValue())).clear();
                } else {
                    // Must be leaf.
                    final DN next = entries.higherKey(dn);
                    if (next == null || !next.isChildOf(dn)) {
                        entries.remove(dn);
                    } else {
                        throw newErrorResult(ResultCode.NOT_ALLOWED_ON_NONLEAF);
                    }
                }
            }
            resultHandler.handleResult(getResult(request, entry, null));
        } catch (final DecodeException e) {
            resultHandler.handleErrorResult(newErrorResult(ResultCode.PROTOCOL_ERROR, e));
        } catch (final ErrorResultException e) {
            resultHandler.handleErrorResult(e);
        }
    }
 
    @Override
    public <R extends ExtendedResult> void handleExtendedRequest(
            final RequestContext requestContext, final ExtendedRequest<R> request,
            final IntermediateResponseHandler intermediateResponseHandler,
            final ResultHandler<R> resultHandler) {
        resultHandler.handleErrorResult(newErrorResult(ResultCode.UNWILLING_TO_PERFORM,
                "Extended request operation not supported"));
    }
 
    @Override
    public void handleModify(final RequestContext requestContext, final ModifyRequest request,
            final IntermediateResponseHandler intermediateResponseHandler,
            final ResultHandler<Result> resultHandler) {
        try {
            final Entry entry;
            final Entry newEntry;
            synchronized (writeLock) {
                final DN dn = request.getName();
                entry = getRequiredEntry(request, dn);
                newEntry = new LinkedHashMapEntry(entry);
                entries.put(dn, modifyEntry(newEntry, request));
            }
            resultHandler.handleResult(getResult(request, entry, newEntry));
        } catch (final ErrorResultException e) {
            resultHandler.handleErrorResult(e);
        }
    }
 
    @Override
    public void handleModifyDN(final RequestContext requestContext, final ModifyDNRequest request,
            final IntermediateResponseHandler intermediateResponseHandler,
            final ResultHandler<Result> resultHandler) {
        resultHandler.handleErrorResult(newErrorResult(ResultCode.UNWILLING_TO_PERFORM,
                "ModifyDN request operation not supported"));
    }
 
    @Override
    public void handleSearch(final RequestContext requestContext, final SearchRequest request,
            final IntermediateResponseHandler intermediateResponseHandler,
            final SearchResultHandler resultHandler) {
        try {
            final DN dn = request.getName();
            final Entry baseEntry = getRequiredEntry(request, dn);
            final SearchScope scope = request.getScope();
            final Filter filter = request.getFilter();
            final Matcher matcher = filter.matcher(schema);
            final AttributeFilter attributeFilter =
                    new AttributeFilter(request.getAttributes(), schema).typesOnly(request
                            .isTypesOnly());
            if (scope.equals(SearchScope.BASE_OBJECT)) {
                if (matcher.matches(baseEntry).toBoolean()) {
                    sendEntry(attributeFilter, resultHandler, baseEntry);
                }
            } else if (scope.equals(SearchScope.SINGLE_LEVEL)) {
                final NavigableMap<DN, Entry> subtree =
                        entries.subMap(dn, dn.child(RDN.maxValue()));
                for (final Entry entry : subtree.values()) {
                    // Check for cancellation.
                    requestContext.checkIfCancelled(false);
                    final DN childDN = entry.getName();
                    if (childDN.isChildOf(dn)) {
                        if (matcher.matches(entry).toBoolean()
                                && !sendEntry(attributeFilter, resultHandler, entry)) {
                            // Caller has asked to stop sending results.
                            break;
                        }
                    }
                }
            } else if (scope.equals(SearchScope.WHOLE_SUBTREE)) {
                final NavigableMap<DN, Entry> subtree =
                        entries.subMap(dn, dn.child(RDN.maxValue()));
                for (final Entry entry : subtree.values()) {
                    // Check for cancellation.
                    requestContext.checkIfCancelled(false);
                    if (matcher.matches(entry).toBoolean()
                            && !sendEntry(attributeFilter, resultHandler, entry)) {
                        // Caller has asked to stop sending results.
                        break;
                    }
                }
            } else {
                throw newErrorResult(ResultCode.PROTOCOL_ERROR,
                        "Search request contains an unsupported search scope");
            }
            resultHandler.handleResult(newResult(ResultCode.SUCCESS));
        } catch (final ErrorResultException e) {
            resultHandler.handleErrorResult(e);
        }
    }
 
    private <R extends Result> R addResultControls(final Request request, final Entry before,
            final Entry after, final R result) throws ErrorResultException {
        try {
            // Add pre-read response control if requested.
            final PreReadRequestControl preRead =
                    request.getControl(PreReadRequestControl.DECODER, decodeOptions);
            if (preRead != null) {
                if (preRead.isCritical() && before == null) {
                    throw newErrorResult(ResultCode.UNAVAILABLE_CRITICAL_EXTENSION);
                } else {
                    final AttributeFilter filter =
                            new AttributeFilter(preRead.getAttributes(), schema);
                    result.addControl(PreReadResponseControl.newControl(filter
                            .filteredViewOf(before)));
                }
            }
 
            // Add post-read response control if requested.
            final PostReadRequestControl postRead =
                    request.getControl(PostReadRequestControl.DECODER, decodeOptions);
            if (postRead != null) {
                if (postRead.isCritical() && after == null) {
                    throw newErrorResult(ResultCode.UNAVAILABLE_CRITICAL_EXTENSION);
                } else {
                    final AttributeFilter filter =
                            new AttributeFilter(postRead.getAttributes(), schema);
                    result.addControl(PostReadResponseControl.newControl(filter
                            .filteredViewOf(after)));
                }
            }
            return result;
        } catch (final DecodeException e) {
            throw newErrorResult(ResultCode.PROTOCOL_ERROR, e);
        }
    }
 
    private BindResult getBindResult(final BindRequest request, final Entry before,
            final Entry after) throws ErrorResultException {
        return addResultControls(request, before, after, newBindResult(ResultCode.SUCCESS));
    }
 
    private CompareResult getCompareResult(final CompareRequest request, final Entry entry,
            final boolean compareResult) throws ErrorResultException {
        return addResultControls(
                request,
                entry,
                entry,
                newCompareResult(compareResult ? ResultCode.COMPARE_TRUE : ResultCode.COMPARE_FALSE));
    }
 
    private Entry getRequiredEntry(final Request request, final DN dn) throws ErrorResultException {
        final Entry entry = entries.get(dn);
        if (entry == null) {
            noSuchObject(dn);
        } else if (request != null) {
            AssertionRequestControl control;
            try {
                control = request.getControl(AssertionRequestControl.DECODER, decodeOptions);
            } catch (final DecodeException e) {
                throw newErrorResult(ResultCode.PROTOCOL_ERROR, e);
            }
            if (control != null) {
                final Filter filter = control.getFilter();
                final Matcher matcher = filter.matcher(schema);
                if (!matcher.matches(entry).toBoolean()) {
                    throw newErrorResult(ResultCode.ASSERTION_FAILED, "The filter '"
                            + filter.toString() + "' did not match the entry '"
                            + entry.getName().toString() + "'");
                }
            }
        }
        return entry;
    }
 
    private Result getResult(final Request request, final Entry before, final Entry after)
            throws ErrorResultException {
        return addResultControls(request, before, after, newResult(ResultCode.SUCCESS));
    }
 
    private void noSuchObject(final DN dn) throws ErrorResultException {
        throw newErrorResult(ResultCode.NO_SUCH_OBJECT, "The entry '" + dn.toString()
                + "' does not exist");
    }
 
    private boolean sendEntry(final AttributeFilter filter,
            final SearchResultHandler resultHandler, final Entry entry) {
        return resultHandler.handleEntry(newSearchResultEntry(filter.filteredViewOf(entry)));
    }
}