001/*
002 * (C) Copyright 2006-2014 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Nuxeo - initial API and implementation
018 *
019 */
020
021package org.nuxeo.ecm.directory.ldap;
022
023import java.io.IOException;
024import java.io.Serializable;
025import java.text.ParseException;
026import java.text.SimpleDateFormat;
027import java.util.ArrayList;
028import java.util.Arrays;
029import java.util.Calendar;
030import java.util.Collection;
031import java.util.Collections;
032import java.util.Date;
033import java.util.HashMap;
034import java.util.LinkedList;
035import java.util.List;
036import java.util.Map;
037import java.util.Properties;
038import java.util.Set;
039import java.util.SimpleTimeZone;
040
041import javax.naming.Context;
042import javax.naming.LimitExceededException;
043import javax.naming.NameNotFoundException;
044import javax.naming.NamingEnumeration;
045import javax.naming.NamingException;
046import javax.naming.SizeLimitExceededException;
047import javax.naming.directory.Attribute;
048import javax.naming.directory.Attributes;
049import javax.naming.directory.BasicAttribute;
050import javax.naming.directory.BasicAttributes;
051import javax.naming.directory.DirContext;
052import javax.naming.directory.SearchControls;
053import javax.naming.directory.SearchResult;
054import javax.naming.ldap.InitialLdapContext;
055
056import org.apache.commons.lang.StringUtils;
057import org.apache.commons.logging.Log;
058import org.apache.commons.logging.LogFactory;
059import org.nuxeo.ecm.core.api.Blob;
060import org.nuxeo.ecm.core.api.Blobs;
061import org.nuxeo.ecm.core.api.DataModel;
062import org.nuxeo.ecm.core.api.DocumentModel;
063import org.nuxeo.ecm.core.api.DocumentModelList;
064import org.nuxeo.ecm.core.api.PropertyException;
065import org.nuxeo.ecm.core.api.RecoverableClientException;
066import org.nuxeo.ecm.core.api.impl.DocumentModelListImpl;
067import org.nuxeo.ecm.core.api.security.SecurityConstants;
068import org.nuxeo.ecm.core.schema.types.Field;
069import org.nuxeo.ecm.core.schema.types.Type;
070import org.nuxeo.ecm.core.utils.SIDGenerator;
071import org.nuxeo.ecm.directory.BaseSession;
072import org.nuxeo.ecm.directory.DirectoryException;
073import org.nuxeo.ecm.directory.DirectoryFieldMapper;
074import org.nuxeo.ecm.directory.EntryAdaptor;
075import org.nuxeo.ecm.directory.EntrySource;
076import org.nuxeo.ecm.directory.PasswordHelper;
077import org.nuxeo.ecm.directory.Reference;
078import org.nuxeo.ecm.directory.BaseDirectoryDescriptor.SubstringMatchType;
079
080/**
081 * This class represents a session against an LDAPDirectory.
082 *
083 * @author Olivier Grisel <ogrisel@nuxeo.com>
084 */
085public class LDAPSession extends BaseSession implements EntrySource {
086
087    protected static final String MISSING_ID_LOWER_CASE = "lower";
088
089    protected static final String MISSING_ID_UPPER_CASE = "upper";
090
091    private static final Log log = LogFactory.getLog(LDAPSession.class);
092
093    protected final String schemaName;
094
095    protected final DirContext dirContext;
096
097    protected final String idAttribute;
098
099    protected final String idCase;
100
101    protected final String searchBaseDn;
102
103    protected final Set<String> emptySet = Collections.emptySet();
104
105    protected final String sid;
106
107    protected final Map<String, Field> schemaFieldMap;
108
109    protected SubstringMatchType substringMatchType;
110
111    protected final String rdnAttribute;
112
113    protected final String rdnField;
114
115    protected final String passwordHashAlgorithm;
116
117    public LDAPSession(LDAPDirectory directory, DirContext dirContext) {
118        super(directory);
119        this.dirContext = LdapRetryHandler.wrap(dirContext, directory.getServer().getRetries());
120        DirectoryFieldMapper fieldMapper = directory.getFieldMapper();
121        idAttribute = fieldMapper.getBackendField(getIdField());
122        LDAPDirectoryDescriptor descriptor = directory.getDescriptor();
123        idCase = descriptor.getIdCase();
124        schemaName = directory.getSchema();
125        schemaFieldMap = directory.getSchemaFieldMap();
126        sid = String.valueOf(SIDGenerator.next());
127        searchBaseDn = descriptor.getSearchBaseDn();
128        substringMatchType = descriptor.getSubstringMatchType();
129        rdnAttribute = descriptor.getRdnAttribute();
130        rdnField = directory.getFieldMapper().getDirectoryField(rdnAttribute);
131        passwordHashAlgorithm = descriptor.passwordHashAlgorithm;
132        permissions = descriptor.permissions;
133    }
134
135    @Override
136    public LDAPDirectory getDirectory() {
137        return (LDAPDirectory) directory;
138    }
139
140    public DirContext getContext() {
141        return dirContext;
142    }
143
144    @Override
145    @SuppressWarnings("unchecked")
146    public DocumentModel createEntry(Map<String, Object> fieldMap) {
147        if (!isCurrentUserAllowed(SecurityConstants.WRITE)) {
148            return null;
149        }
150        if (isReadOnly()) {
151            return null;
152        }
153        LDAPDirectoryDescriptor descriptor = getDirectory().getDescriptor();
154        List<String> referenceFieldList = new LinkedList<String>();
155        try {
156            String dn = String.format("%s=%s,%s", rdnAttribute, fieldMap.get(rdnField), descriptor.getCreationBaseDn());
157            Attributes attrs = new BasicAttributes();
158            Attribute attr;
159
160            List<String> mandatoryAttributes = getMandatoryAttributes();
161            for (String mandatoryAttribute : mandatoryAttributes) {
162                attr = new BasicAttribute(mandatoryAttribute);
163                attr.add(" ");
164                attrs.put(attr);
165            }
166
167            String[] creationClasses = descriptor.getCreationClasses();
168            if (creationClasses.length != 0) {
169                attr = new BasicAttribute("objectclass");
170                for (String creationClasse : creationClasses) {
171                    attr.add(creationClasse);
172                }
173                attrs.put(attr);
174            }
175
176            for (String fieldId : fieldMap.keySet()) {
177                String backendFieldId = getDirectory().getFieldMapper().getBackendField(fieldId);
178                if (backendFieldId.equals(getPasswordField())) {
179                    attr = new BasicAttribute(backendFieldId);
180                    String password = (String) fieldMap.get(fieldId);
181                    password = PasswordHelper.hashPassword(password, passwordHashAlgorithm);
182                    attr.add(password);
183                    attrs.put(attr);
184                } else if (getDirectory().isReference(fieldId)) {
185                    List<Reference> references = directory.getReferences(fieldId);
186                    if (references.size() > 1) {
187                        // not supported
188                    } else {
189                        Reference reference = references.get(0);
190                        if (reference instanceof LDAPReference) {
191                            attr = new BasicAttribute(((LDAPReference) reference).getStaticAttributeId());
192                            attr.add(descriptor.getEmptyRefMarker());
193                            attrs.put(attr);
194                        }
195                    }
196                    referenceFieldList.add(fieldId);
197                } else if (LDAPDirectory.DN_SPECIAL_ATTRIBUTE_KEY.equals(backendFieldId)) {
198                    // ignore special DN field
199                    log.warn(String.format("field %s is mapped to read only DN field: ignored", fieldId));
200                } else {
201                    Object value = fieldMap.get(fieldId);
202                    if ((value != null) && !value.equals("") && !Collections.emptyList().equals(value)) {
203                        attrs.put(getAttributeValue(fieldId, value));
204                    }
205                }
206            }
207
208            if (log.isDebugEnabled()) {
209                String idField = getIdField();
210                log.debug(String.format("LDAPSession.createEntry(%s=%s): LDAP bind dn='%s' attrs='%s' [%s]", idField,
211                        fieldMap.get(idField), dn, attrs, this));
212            }
213            dirContext.bind(dn, null, attrs);
214
215            for (String referenceFieldName : referenceFieldList) {
216                List<Reference> references = directory.getReferences(referenceFieldName);
217                if (references.size() > 1) {
218                    // not supported
219                } else {
220                    Reference reference = references.get(0);
221                    List<String> targetIds = (List<String>) fieldMap.get(referenceFieldName);
222                    reference.addLinks((String) fieldMap.get(getIdField()), targetIds);
223                }
224            }
225            String dnFieldName = getDirectory().getFieldMapper().getDirectoryField(LDAPDirectory.DN_SPECIAL_ATTRIBUTE_KEY);
226            if (getDirectory().getSchemaFieldMap().containsKey(dnFieldName)) {
227                // add the DN special attribute to the fieldmap of the new
228                // entry
229                fieldMap.put(dnFieldName, dn);
230            }
231            getDirectory().invalidateCaches();
232            return fieldMapToDocumentModel(fieldMap);
233        } catch (NamingException e) {
234            handleException(e, "createEntry failed");
235            return null;
236        }
237    }
238
239    @Override
240    public DocumentModel getEntry(String id) throws DirectoryException {
241        return getEntry(id, true);
242    }
243
244    @Override
245    public DocumentModel getEntry(String id, boolean fetchReferences) throws DirectoryException {
246        if (isCurrentUserAllowed(SecurityConstants.READ)) {
247            return directory.getCache().getEntry(id, this, fetchReferences);
248        }
249        return null;
250    }
251
252    @Override
253    public DocumentModel getEntryFromSource(String id, boolean fetchReferences) throws DirectoryException {
254        try {
255            SearchResult result = getLdapEntry(id, true);
256            if (result == null) {
257                return null;
258            }
259            return ldapResultToDocumentModel(result, id, fetchReferences);
260        } catch (NamingException e) {
261            throw new DirectoryException("getEntry failed: " + e.getMessage(), e);
262        }
263    }
264
265    @Override
266    public boolean hasEntry(String id) throws DirectoryException {
267        try {
268            // TODO: check directory cache first
269            return getLdapEntry(id) != null;
270        } catch (NamingException e) {
271            throw new DirectoryException("hasEntry failed: " + e.getMessage(), e);
272        }
273    }
274
275    protected SearchResult getLdapEntry(String id) throws NamingException, DirectoryException {
276        return getLdapEntry(id, false);
277    }
278
279    protected SearchResult getLdapEntry(String id, boolean fetchAllAttributes) throws NamingException {
280        if (StringUtils.isEmpty(id)) {
281            log.warn("The application should not " + "query for entries with an empty id " + "=> return no results");
282            return null;
283        }
284        String filterExpr;
285        String baseFilter = getDirectory().getBaseFilter();
286        if (baseFilter.startsWith("(")) {
287            filterExpr = String.format("(&(%s={0})%s)", idAttribute, baseFilter);
288        } else {
289            filterExpr = String.format("(&(%s={0})(%s))", idAttribute, baseFilter);
290        }
291        String[] filterArgs = { id };
292        SearchControls scts = getDirectory().getSearchControls(fetchAllAttributes);
293
294        if (log.isDebugEnabled()) {
295            log.debug(String.format("LDAPSession.getLdapEntry(%s, %s): LDAP search base='%s' filter='%s' "
296                    + " args='%s' scope='%s' [%s]", id, fetchAllAttributes, searchBaseDn, filterExpr, id,
297                    scts.getSearchScope(), this));
298        }
299        NamingEnumeration<SearchResult> results;
300        try {
301            results = dirContext.search(searchBaseDn, filterExpr, filterArgs, scts);
302        } catch (NameNotFoundException nnfe) {
303            // sometimes ActiveDirectory have some query fail with: LDAP:
304            // error code 32 - 0000208D: NameErr: DSID-031522C9, problem
305            // 2001 (NO_OBJECT).
306            // To keep the application usable return no results instead of
307            // crashing but log the error so that the AD admin
308            // can fix the issue.
309            log.error("Unexpected response from server while performing query: " + nnfe.getMessage(), nnfe);
310            return null;
311        }
312
313        if (!results.hasMore()) {
314            log.debug("Entry not found: " + id);
315            return null;
316        }
317        SearchResult result = results.next();
318        try {
319            String dn = result.getNameInNamespace();
320            if (results.hasMore()) {
321                result = results.next();
322                String dn2 = result.getNameInNamespace();
323                String msg = String.format("Unable to fetch entry for '%s': found more than one match,"
324                        + " for instance: '%s' and '%s'", id, dn, dn2);
325                log.error(msg);
326                // ignore entries that are ambiguous while giving enough info
327                // in the logs to let the LDAP admin be able to fix the issue
328                return null;
329            }
330            if (log.isDebugEnabled()) {
331                log.debug(String.format("LDAPSession.getLdapEntry(%s, %s): LDAP search base='%s' filter='%s' "
332                        + " args='%s' scope='%s' => found: %s [%s]", id, fetchAllAttributes, searchBaseDn, filterExpr,
333                        id, scts.getSearchScope(), dn, this));
334            }
335        } catch (UnsupportedOperationException e) {
336            // ignore unsupported operation thrown by the Apache DS server in
337            // the tests in embedded mode
338        }
339        return result;
340    }
341
342    @Override
343    public DocumentModelList getEntries() throws DirectoryException {
344        try {
345            SearchControls scts = getDirectory().getSearchControls(true);
346            if (log.isDebugEnabled()) {
347                log.debug(String.format("LDAPSession.getEntries(): LDAP search base='%s' filter='%s' "
348                        + " args=* scope=%s [%s]", searchBaseDn, getDirectory().getBaseFilter(), scts.getSearchScope(), this));
349            }
350            NamingEnumeration<SearchResult> results = dirContext.search(searchBaseDn, getDirectory().getBaseFilter(), scts);
351            // skip reference fetching
352            return ldapResultsToDocumentModels(results, false);
353        } catch (SizeLimitExceededException e) {
354            throw new org.nuxeo.ecm.directory.SizeLimitExceededException(e);
355        } catch (NamingException e) {
356            throw new DirectoryException("getEntries failed", e);
357        }
358    }
359
360    @Override
361    @SuppressWarnings("unchecked")
362    public void updateEntry(DocumentModel docModel) {
363        if (!isCurrentUserAllowed(SecurityConstants.WRITE)) {
364            return;
365        }
366        if (isReadOnlyEntry(docModel)) {
367            // do not edit readonly entries
368            return;
369        }
370        List<String> updateList = new ArrayList<String>();
371        List<String> referenceFieldList = new LinkedList<String>();
372
373        try {
374            DataModel dataModel = docModel.getDataModel(schemaName);
375            for (String fieldName : schemaFieldMap.keySet()) {
376                if (!dataModel.isDirty(fieldName)) {
377                    continue;
378                }
379                if (getDirectory().isReference(fieldName)) {
380                    referenceFieldList.add(fieldName);
381                } else {
382                    updateList.add(fieldName);
383                }
384            }
385
386            if (!isReadOnlyEntry(docModel) && !updateList.isEmpty()) {
387                Attributes attrs = new BasicAttributes();
388                SearchResult ldapEntry = getLdapEntry(docModel.getId());
389                if (ldapEntry == null) {
390                    throw new DirectoryException(docModel.getId() + " not found");
391                }
392                Attributes oldattrs = ldapEntry.getAttributes();
393                String dn = ldapEntry.getNameInNamespace();
394                Attributes attrsToDel = new BasicAttributes();
395                for (String f : updateList) {
396                    Object value = docModel.getProperty(schemaName, f);
397                    String backendField = getDirectory().getFieldMapper().getBackendField(f);
398                    if (LDAPDirectory.DN_SPECIAL_ATTRIBUTE_KEY.equals(backendField)) {
399                        // skip special LDAP DN field that is readonly
400                        log.warn(String.format("field %s is mapped to read only DN field: ignored", f));
401                        continue;
402                    }
403                    if (value == null || value.equals("")) {
404                        Attribute objectClasses = oldattrs.get("objectClass");
405                        Attribute attr;
406                        if (getMandatoryAttributes(objectClasses).contains(backendField)) {
407                            attr = new BasicAttribute(backendField);
408                            // XXX: this might fail if the mandatory attribute
409                            // is typed integer for instance
410                            attr.add(" ");
411                            attrs.put(attr);
412                        } else if (oldattrs.get(backendField) != null) {
413                            attr = new BasicAttribute(backendField);
414                            attr.add(oldattrs.get(backendField).get());
415                            attrsToDel.put(attr);
416                        }
417                    } else if (f.equals(getPasswordField())) {
418                        // The password has been updated, it has to be encrypted
419                        Attribute attr = new BasicAttribute(backendField);
420                        attr.add(PasswordHelper.hashPassword((String) value, passwordHashAlgorithm));
421                        attrs.put(attr);
422                    } else {
423                        attrs.put(getAttributeValue(f, value));
424                    }
425                }
426
427                if (log.isDebugEnabled()) {
428                    log.debug(String.format("LDAPSession.updateEntry(%s): LDAP modifyAttributes dn='%s' "
429                            + "mod_op='REMOVE_ATTRIBUTE' attr='%s' [%s]", docModel, dn, attrsToDel, this));
430                }
431                dirContext.modifyAttributes(dn, DirContext.REMOVE_ATTRIBUTE, attrsToDel);
432
433                if (log.isDebugEnabled()) {
434                    log.debug(String.format("LDAPSession.updateEntry(%s): LDAP modifyAttributes dn='%s' "
435                            + "mod_op='REPLACE_ATTRIBUTE' attr='%s' [%s]", docModel, dn, attrs, this));
436                }
437                dirContext.modifyAttributes(dn, DirContext.REPLACE_ATTRIBUTE, attrs);
438            }
439
440            // update reference fields
441            for (String referenceFieldName : referenceFieldList) {
442                List<Reference> references = directory.getReferences(referenceFieldName);
443                if (references.size() > 1) {
444                    // not supported
445                } else {
446                    Reference reference = references.get(0);
447                    List<String> targetIds = (List<String>) docModel.getProperty(schemaName, referenceFieldName);
448                    reference.setTargetIdsForSource(docModel.getId(), targetIds);
449                }
450            }
451        } catch (NamingException e) {
452            handleException(e, "updateEntry failed:");
453        }
454        getDirectory().invalidateCaches();
455    }
456
457    protected void handleException(Exception e, String message) {
458        LdapExceptionProcessor processor = getDirectory().getDescriptor().getExceptionProcessor();
459
460        RecoverableClientException userException = processor.extractRecoverableException(e);
461        if (userException != null) {
462            throw userException;
463        }
464        throw new DirectoryException(message + " " + e.getMessage(), e);
465
466    }
467
468    @Override
469    public void deleteEntry(DocumentModel dm) {
470        deleteEntry(dm.getId());
471    }
472
473    @Override
474    public void deleteEntry(String id) {
475        if (!isCurrentUserAllowed(SecurityConstants.WRITE)) {
476            return;
477        }
478        if (isReadOnly()) {
479            return;
480        }
481        try {
482            for (String fieldName : schemaFieldMap.keySet()) {
483                if (getDirectory().isReference(fieldName)) {
484                    List<Reference> references = directory.getReferences(fieldName);
485                    if (references.size() > 1) {
486                        // not supported
487                    } else {
488                        Reference reference = references.get(0);
489                        reference.removeLinksForSource(id);
490                    }
491                }
492            }
493            SearchResult result = getLdapEntry(id);
494
495            if (log.isDebugEnabled()) {
496                log.debug(String.format("LDAPSession.deleteEntry(%s): LDAP destroySubcontext dn='%s' [%s]", id,
497                        result.getNameInNamespace(), this));
498            }
499            dirContext.destroySubcontext(result.getNameInNamespace());
500        } catch (NamingException e) {
501            handleException(e, "deleteEntry failed for: " + id);
502        }
503        getDirectory().invalidateCaches();
504    }
505
506    @Override
507    public void deleteEntry(String id, Map<String, String> map) {
508        log.warn("Calling deleteEntry extended on LDAP directory");
509        deleteEntry(id);
510    }
511
512    public DocumentModelList query(Map<String, Serializable> filter, Set<String> fulltext, boolean fetchReferences,
513            Map<String, String> orderBy) throws DirectoryException {
514        try {
515            // building the query using filterExpr / filterArgs to
516            // escape special characters and to fulltext search only on
517            // the explicitly specified fields
518            String[] filters = new String[filter.size()];
519            String[] filterArgs = new String[filter.size()];
520
521            if (fulltext == null) {
522                fulltext = Collections.emptySet();
523            }
524
525            int index = 0;
526            for (String fieldName : filter.keySet()) {
527                if (getDirectory().isReference(fieldName)) {
528                    log.warn(fieldName + " is a reference and will be ignored as a query criterion");
529                    continue;
530                }
531
532                String backendFieldName = getDirectory().getFieldMapper().getBackendField(fieldName);
533                Object fieldValue = filter.get(fieldName);
534
535                StringBuilder currentFilter = new StringBuilder();
536                currentFilter.append("(");
537                if (fieldValue == null) {
538                    currentFilter.append("!(" + backendFieldName + "=*)");
539                } else if ("".equals(fieldValue)) {
540                    if (fulltext.contains(fieldName)) {
541                        currentFilter.append(backendFieldName + "=*");
542                    } else {
543                        currentFilter.append("!(" + backendFieldName + "=*)");
544                    }
545                } else {
546                    currentFilter.append(backendFieldName + "=");
547                    if (fulltext.contains(fieldName)) {
548                        switch (substringMatchType) {
549                        case subinitial:
550                            currentFilter.append("{" + index + "}*");
551                            break;
552                        case subfinal:
553                            currentFilter.append("*{" + index + "}");
554                            break;
555                        case subany:
556                            currentFilter.append("*{" + index + "}*");
557                            break;
558                        }
559                    } else {
560                        currentFilter.append("{" + index + "}");
561                    }
562                }
563                currentFilter.append(")");
564                filters[index] = currentFilter.toString();
565                if (fieldValue != null && !"".equals(fieldValue)) {
566                    if (fieldValue instanceof Blob) {
567                        // filter arg could be a sequence of \xx where xx is the
568                        // hexadecimal value of the byte
569                        log.warn("Binary search is not supported");
570                    } else {
571                        // XXX: what kind of Objects can we get here? Is
572                        // toString() enough?
573                        filterArgs[index] = fieldValue.toString();
574                    }
575                }
576                index++;
577            }
578            String filterExpr = "(&" + getDirectory().getBaseFilter() + StringUtils.join(filters) + ')';
579            SearchControls scts = getDirectory().getSearchControls(true);
580
581            if (log.isDebugEnabled()) {
582                log.debug(String.format(
583                        "LDAPSession.query(...): LDAP search base='%s' filter='%s' args='%s' scope='%s' [%s]",
584                        searchBaseDn, filterExpr, StringUtils.join(filterArgs, ","), scts.getSearchScope(), this));
585            }
586            try {
587                NamingEnumeration<SearchResult> results = dirContext.search(searchBaseDn, filterExpr, filterArgs, scts);
588                DocumentModelList entries = ldapResultsToDocumentModels(results, fetchReferences);
589
590                if (orderBy != null && !orderBy.isEmpty()) {
591                    getDirectory().orderEntries(entries, orderBy);
592                }
593                return entries;
594            } catch (NameNotFoundException nnfe) {
595                // sometimes ActiveDirectory have some query fail with: LDAP:
596                // error code 32 - 0000208D: NameErr: DSID-031522C9, problem
597                // 2001 (NO_OBJECT).
598                // To keep the application usable return no results instead of
599                // crashing but log the error so that the AD admin
600                // can fix the issue.
601                log.error("Unexpected response from server while performing query: " + nnfe.getMessage(), nnfe);
602                return new DocumentModelListImpl();
603            }
604        } catch (LimitExceededException e) {
605            throw new org.nuxeo.ecm.directory.SizeLimitExceededException(e);
606        } catch (NamingException e) {
607            throw new DirectoryException("executeQuery failed", e);
608        }
609    }
610
611    @Override
612    public DocumentModelList query(Map<String, Serializable> filter) throws DirectoryException {
613        // by default, do not fetch references of result entries
614        return query(filter, emptySet, new HashMap<String, String>());
615    }
616
617    @Override
618    public DocumentModelList query(Map<String, Serializable> filter, Set<String> fulltext, Map<String, String> orderBy)
619            throws DirectoryException {
620        return query(filter, fulltext, false, orderBy);
621    }
622
623    @Override
624    public DocumentModelList query(Map<String, Serializable> filter, Set<String> fulltext, Map<String, String> orderBy,
625            boolean fetchReferences) throws DirectoryException {
626        return query(filter, fulltext, fetchReferences, orderBy);
627    }
628
629    @Override
630    public DocumentModelList query(Map<String, Serializable> filter, Set<String> fulltext) throws DirectoryException {
631        // by default, do not fetch references of result entries
632        return query(filter, fulltext, new HashMap<String, String>());
633    }
634
635    @Override
636    public void close() throws DirectoryException {
637        try {
638            dirContext.close();
639        } catch (NamingException e) {
640            throw new DirectoryException("close failed", e);
641        } finally {
642            getDirectory().removeSession(this);
643        }
644    }
645
646    @Override
647    public List<String> getProjection(Map<String, Serializable> filter, String columnName) throws DirectoryException {
648        return getProjection(filter, emptySet, columnName);
649    }
650
651    @Override
652    public List<String> getProjection(Map<String, Serializable> filter, Set<String> fulltext, String columnName)
653            throws DirectoryException {
654        // XXX: this suboptimal code should be either optimized for LDAP or
655        // moved to an abstract class
656        List<String> result = new ArrayList<String>();
657        DocumentModelList docList = query(filter, fulltext);
658        String columnNameinDocModel = getDirectory().getFieldMapper().getDirectoryField(columnName);
659        for (DocumentModel docModel : docList) {
660            Object obj;
661            try {
662                obj = docModel.getProperty(schemaName, columnNameinDocModel);
663            } catch (PropertyException e) {
664                throw new DirectoryException(e);
665            }
666            String propValue;
667            if (obj instanceof String) {
668                propValue = (String) obj;
669            } else {
670                propValue = String.valueOf(obj);
671            }
672            result.add(propValue);
673        }
674        return result;
675    }
676
677    protected DocumentModel fieldMapToDocumentModel(Map<String, Object> fieldMap) throws DirectoryException {
678        String id = String.valueOf(fieldMap.get(getIdField()));
679        try {
680            DocumentModel docModel = BaseSession.createEntryModel(sid, schemaName, id, fieldMap, isReadOnly());
681            EntryAdaptor adaptor = getDirectory().getDescriptor().getEntryAdaptor();
682            if (adaptor != null) {
683                docModel = adaptor.adapt(directory, docModel);
684            }
685            return docModel;
686        } catch (PropertyException e) {
687            log.error(e, e);
688            return null;
689        }
690    }
691
692    @SuppressWarnings("unchecked")
693    protected Object getFieldValue(Attribute attribute, String fieldName, String entryId, boolean fetchReferences)
694            throws DirectoryException {
695
696        Field field = schemaFieldMap.get(fieldName);
697        Type type = field.getType();
698        Object defaultValue = field.getDefaultValue();
699        String typeName = type.getName();
700        if (attribute == null) {
701            return defaultValue;
702        }
703        Object value;
704        try {
705            value = attribute.get();
706        } catch (NamingException e) {
707            throw new DirectoryException("Could not fetch value for " + attribute, e);
708        }
709        if (value == null) {
710            return defaultValue;
711        }
712        String trimmedValue = value.toString().trim();
713        if ("string".equals(typeName)) {
714            return trimmedValue;
715        } else if ("integer".equals(typeName) || "long".equals(typeName)) {
716            if ("".equals(trimmedValue)) {
717                return defaultValue;
718            }
719            try {
720                return Long.valueOf(trimmedValue);
721            } catch (NumberFormatException e) {
722                log.error(String.format(
723                        "field %s of type %s has non-numeric value found on server: '%s' (ignoring and using default value instead)",
724                        fieldName, typeName, trimmedValue));
725                return defaultValue;
726            }
727        } else if (type.isListType()) {
728            List<String> parsedItems = new LinkedList<String>();
729            NamingEnumeration<Object> values = null;
730            try {
731                values = (NamingEnumeration<Object>) attribute.getAll();
732                while (values.hasMore()) {
733                    parsedItems.add(values.next().toString().trim());
734                }
735                return parsedItems;
736            } catch (NamingException e) {
737                log.error(String.format(
738                        "field %s of type %s has non list value found on server: '%s' (ignoring and using default value instead)",
739                        fieldName, typeName, values != null ? values.toString() : trimmedValue));
740                return defaultValue;
741            } finally {
742                if (values != null) {
743                    try {
744                        values.close();
745                    } catch (NamingException e) {
746                        log.error(e, e);
747                    }
748                }
749            }
750        } else if ("date".equals(typeName)) {
751            if ("".equals(trimmedValue)) {
752                return defaultValue;
753            }
754            try {
755                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss'Z'");
756                dateFormat.setTimeZone(new SimpleTimeZone(0, "Z"));
757                Date date = dateFormat.parse(trimmedValue);
758                Calendar cal = Calendar.getInstance();
759                cal.setTime(date);
760                return cal;
761            } catch (ParseException e) {
762                log.error(String.format(
763                        "field %s of type %s has invalid value found on server: '%s' (ignoring and using default value instead)",
764                        fieldName, typeName, trimmedValue));
765                return defaultValue;
766            }
767        } else if ("content".equals(typeName)) {
768            return Blobs.createBlob((byte[]) value);
769        } else {
770            throw new DirectoryException("Field type not supported in directories: " + typeName);
771        }
772    }
773
774    @SuppressWarnings("unchecked")
775    protected Attribute getAttributeValue(String fieldName, Object value) throws DirectoryException {
776        Attribute attribute = new BasicAttribute(getDirectory().getFieldMapper().getBackendField(fieldName));
777        Field field = schemaFieldMap.get(fieldName);
778        if (field == null) {
779            String message = String.format("Invalid field name '%s' for directory '%s' with schema '%s'", fieldName,
780                    directory.getName(), directory.getSchema());
781            throw new DirectoryException(message);
782        }
783        Type type = field.getType();
784        String typeName = type.getName();
785
786        if ("string".equals(typeName)) {
787            attribute.add(value);
788        } else if ("integer".equals(typeName) || "long".equals(typeName)) {
789            attribute.add(value.toString());
790        } else if (type.isListType()) {
791            Collection<String> valueItems;
792            if (value instanceof String[]) {
793                valueItems = Arrays.asList((String[]) value);
794            } else if (value instanceof Collection) {
795                valueItems = (Collection<String>) value;
796            } else {
797                throw new DirectoryException(String.format("field %s with value %s does not match type %s", fieldName,
798                        value.toString(), type.getName()));
799            }
800            for (String item : valueItems) {
801                attribute.add(item);
802            }
803        } else if ("date".equals(typeName)) {
804            Calendar cal = (Calendar) value;
805            Date date = cal.getTime();
806            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss'Z'");
807            dateFormat.setTimeZone(new SimpleTimeZone(0, "Z"));
808            attribute.add(dateFormat.format(date));
809        } else if ("content".equals(typeName)) {
810            try {
811                attribute.add(((Blob) value).getByteArray());
812            } catch (IOException e) {
813                throw new DirectoryException("Failed to get ByteArray value", e);
814            }
815        } else {
816            throw new DirectoryException("Field type not supported in directories: " + typeName);
817        }
818
819        return attribute;
820    }
821
822    protected DocumentModelList ldapResultsToDocumentModels(NamingEnumeration<SearchResult> results,
823            boolean fetchReferences) throws DirectoryException, NamingException {
824        DocumentModelListImpl list = new DocumentModelListImpl();
825        if (!isCurrentUserAllowed(SecurityConstants.READ)) {
826            return list;
827        }
828        try {
829            while (results.hasMore()) {
830                SearchResult result = results.next();
831                DocumentModel entry = ldapResultToDocumentModel(result, null, fetchReferences);
832                if (entry != null) {
833                    list.add(entry);
834                }
835            }
836        } catch (SizeLimitExceededException e) {
837            if (list.isEmpty()) {
838                // the server did no send back the truncated results set,
839                // re-throw the exception to that the user interface can display
840                // the error message
841                throw e;
842            }
843            // mark the collect results as a truncated result list
844            log.debug("SizeLimitExceededException caught," + " return truncated results. Original message: "
845                    + e.getMessage() + " explanation: " + e.getExplanation());
846            list.setTotalSize(-2);
847        } finally {
848            results.close();
849        }
850        log.debug("LDAP search returned " + list.size() + " results");
851        return list;
852    }
853
854    protected DocumentModel ldapResultToDocumentModel(SearchResult result, String entryId, boolean fetchReferences)
855            throws DirectoryException, NamingException {
856        Attributes attributes = result.getAttributes();
857        String passwordFieldId = getPasswordField();
858        Map<String, Object> fieldMap = new HashMap<String, Object>();
859
860        Attribute attribute = attributes.get(idAttribute);
861        // NXP-2461: check that id field is filled + NXP-2730: make sure that
862        // entry id is the one returned from LDAP
863        if (attribute != null) {
864            Object entry = attribute.get();
865            if (entry != null) {
866                entryId = entry.toString();
867            }
868        }
869        // NXP-7136 handle id case
870        entryId = changeEntryIdCase(entryId, idCase);
871
872        if (entryId == null) {
873            // don't bother
874            return null;
875        }
876        for (String fieldName : schemaFieldMap.keySet()) {
877            List<Reference> references = directory.getReferences(fieldName);
878            if (references != null && references.size() > 0) {
879                if (fetchReferences) {
880                    Map<String, List<String>> referencedIdsMap = new HashMap<>();
881                    for (Reference reference : references) {
882                        // reference resolution
883                        List<String> referencedIds;
884                        if (reference instanceof LDAPReference) {
885                            // optim: use the current LDAPSession directly to
886                            // provide the LDAP reference with the needed backend entries
887                            LDAPReference ldapReference = (LDAPReference) reference;
888                            referencedIds = ldapReference.getLdapTargetIds(attributes);
889                        } else if (reference instanceof LDAPTreeReference) {
890                            // TODO: optimize using the current LDAPSession
891                            // directly to provide the LDAP reference with the
892                            // needed backend entries (needs to implement getLdapTargetIds)
893                            LDAPTreeReference ldapReference = (LDAPTreeReference) reference;
894                            referencedIds = ldapReference.getTargetIdsForSource(entryId);
895                        } else {
896                            referencedIds = reference.getTargetIdsForSource(entryId);
897                        }
898                        referencedIds = new ArrayList<>(referencedIds);
899                        Collections.sort(referencedIds);
900                        if (referencedIdsMap.containsKey(fieldName)) {
901                            referencedIdsMap.get(fieldName).addAll(referencedIds);
902                        } else {
903                            referencedIdsMap.put(fieldName, referencedIds);
904                        }
905                    }
906                    fieldMap.put(fieldName, referencedIdsMap.get(fieldName));
907                }
908            } else {
909                // manage directly stored fields
910                String attributeId = getDirectory().getFieldMapper().getBackendField(fieldName);
911                if (attributeId.equals(LDAPDirectory.DN_SPECIAL_ATTRIBUTE_KEY)) {
912                    // this is the special DN readonly attribute
913                    try {
914                        fieldMap.put(fieldName, result.getNameInNamespace());
915                    } catch (UnsupportedOperationException e) {
916                        // ignore ApacheDS partial implementation when running
917                        // in embedded mode
918                    }
919                } else {
920                    // this is a regular attribute
921                    attribute = attributes.get(attributeId);
922                    if (fieldName.equals(passwordFieldId)) {
923                        // do not try to fetch the password attribute
924                        continue;
925                    } else {
926                        fieldMap.put(fieldName, getFieldValue(attribute, fieldName, entryId, fetchReferences));
927                    }
928                }
929            }
930        }
931        // check if the idAttribute was returned from the search. If not
932        // set it anyway, maybe changing its case if it's a String instance
933        String fieldId = getDirectory().getFieldMapper().getDirectoryField(idAttribute);
934        Object obj = fieldMap.get(fieldId);
935        if (obj == null) {
936            fieldMap.put(fieldId, changeEntryIdCase(entryId, getDirectory().getDescriptor().getMissingIdFieldCase()));
937        } else if (obj instanceof String) {
938            fieldMap.put(fieldId, changeEntryIdCase((String) obj, idCase));
939        }
940        return fieldMapToDocumentModel(fieldMap);
941    }
942
943    protected String changeEntryIdCase(String id, String idFieldCase) {
944        if (MISSING_ID_LOWER_CASE.equals(idFieldCase)) {
945            return id.toLowerCase();
946        } else if (MISSING_ID_UPPER_CASE.equals(idFieldCase)) {
947            return id.toUpperCase();
948        }
949        // returns the unchanged id
950        return id;
951    }
952
953    @Override
954    public boolean authenticate(String username, String password) throws DirectoryException {
955
956        if (password == null || "".equals(password.trim())) {
957            // never use anonymous bind as a way to authenticate a user in
958            // Nuxeo EP
959            return false;
960        }
961
962        // lookup the user: fetch its dn
963        SearchResult entry;
964        try {
965            entry = getLdapEntry(username);
966        } catch (NamingException e) {
967            throw new DirectoryException("failed to fetch the ldap entry for " + username, e);
968        }
969        if (entry == null) {
970            // no such user => authentication failed
971            return false;
972        }
973        String dn = entry.getNameInNamespace();
974        Properties env = (Properties) getDirectory().getContextProperties().clone();
975        env.put(Context.SECURITY_PRINCIPAL, dn);
976        env.put(Context.SECURITY_CREDENTIALS, password);
977
978        InitialLdapContext authenticationDirContext = null;
979        try {
980            // creating a context does a bind
981            log.debug(String.format("LDAP bind dn='%s'", dn));
982            // noinspection ResultOfObjectAllocationIgnored
983            authenticationDirContext = new InitialLdapContext(env, null);
984            // force reconnection to prevent from using a previous connection
985            // with an obsolete password (after an user has changed his
986            // password)
987            authenticationDirContext.reconnect(null);
988            log.debug("Bind succeeded, authentication ok");
989            return true;
990        } catch (NamingException e) {
991            log.debug("Bind failed: " + e.getMessage());
992            // authentication failed
993            return false;
994        } finally {
995            try {
996                if (authenticationDirContext != null) {
997                    authenticationDirContext.close();
998                }
999            } catch (NamingException e) {
1000                log.error("Error closing authentication context when biding dn " + dn, e);
1001                return false;
1002            }
1003        }
1004    }
1005
1006    @Override
1007    public boolean isAuthenticating() throws DirectoryException {
1008        String password = getPasswordField();
1009        return schemaFieldMap.containsKey(password);
1010    }
1011
1012    public boolean rdnMatchesIdField() {
1013        return getDirectory().getDescriptor().rdnAttribute.equals(idAttribute);
1014    }
1015
1016    @SuppressWarnings("unchecked")
1017    protected List<String> getMandatoryAttributes(Attribute objectClassesAttribute) throws DirectoryException {
1018        try {
1019            List<String> mandatoryAttributes = new ArrayList<String>();
1020
1021            DirContext schema = dirContext.getSchema("");
1022            List<String> objectClasses = new ArrayList<String>();
1023            if (objectClassesAttribute == null) {
1024                // use the creation classes as reference schema for this entry
1025                objectClasses.addAll(Arrays.asList(getDirectory().getDescriptor().getCreationClasses()));
1026            } else {
1027                // introspec the objectClass definitions to find the mandatory
1028                // attributes for this entry
1029                NamingEnumeration<Object> values = null;
1030                try {
1031                    values = (NamingEnumeration<Object>) objectClassesAttribute.getAll();
1032                    while (values.hasMore()) {
1033                        objectClasses.add(values.next().toString().trim());
1034                    }
1035                } catch (NamingException e) {
1036                    throw new DirectoryException(e);
1037                } finally {
1038                    if (values != null) {
1039                        values.close();
1040                    }
1041                }
1042            }
1043            objectClasses.remove("top");
1044            for (String creationClass : objectClasses) {
1045                Attributes attributes = schema.getAttributes("ClassDefinition/" + creationClass);
1046                Attribute attribute = attributes.get("MUST");
1047                if (attribute != null) {
1048                    NamingEnumeration<String> values = (NamingEnumeration<String>) attribute.getAll();
1049                    try {
1050                        while (values.hasMore()) {
1051                            String value = values.next();
1052                            mandatoryAttributes.add(value);
1053                        }
1054                    } finally {
1055                        values.close();
1056                    }
1057                }
1058            }
1059            return mandatoryAttributes;
1060        } catch (NamingException e) {
1061            throw new DirectoryException("getMandatoryAttributes failed", e);
1062        }
1063    }
1064
1065    protected List<String> getMandatoryAttributes() throws DirectoryException {
1066        return getMandatoryAttributes(null);
1067    }
1068
1069    @Override
1070    // useful for the log function
1071    public String toString() {
1072        return String.format("LDAPSession '%s' for directory %s", sid, directory.getName());
1073    }
1074
1075    @Override
1076    public DocumentModel createEntry(DocumentModel entry) {
1077        Map<String, Object> fieldMap = entry.getProperties(directory.getSchema());
1078        Map<String, Object> simpleNameFieldMap = new HashMap<String, Object>();
1079        for (Map.Entry<String, Object> fieldEntry : fieldMap.entrySet()) {
1080            String fieldKey = fieldEntry.getKey();
1081            if (fieldKey.contains(":")) {
1082                fieldKey = fieldKey.split(":")[1];
1083            }
1084            simpleNameFieldMap.put(fieldKey, fieldEntry.getValue());
1085        }
1086        return createEntry(simpleNameFieldMap);
1087    }
1088
1089}