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

Jean-Noel Rouvignac
01.51.2014 02bbeacbfb05101989dac510cbef7815fdf28a2e
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
/*
 * 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 2006-2010 Sun Microsystems, Inc.
 *      Portions Copyright 2011-2014 ForgeRock AS
 */
package org.opends.server.core;
 
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
 
import org.opends.messages.Message;
import org.opends.server.api.AccessControlHandler;
import org.opends.server.api.AuthenticationPolicyState;
import org.opends.server.api.ClientConnection;
import org.opends.server.api.plugin.PluginResult;
import org.opends.server.controls.AccountUsableResponseControl;
import org.opends.server.controls.MatchedValuesControl;
import org.opends.server.core.networkgroups.NetworkGroup;
import org.opends.server.loggers.debug.DebugLogger;
import org.opends.server.loggers.debug.DebugTracer;
import org.opends.server.protocols.ldap.LDAPFilter;
import org.opends.server.types.*;
import org.opends.server.types.operation.PostResponseSearchOperation;
import org.opends.server.types.operation.PreParseSearchOperation;
import org.opends.server.types.operation.SearchEntrySearchOperation;
import org.opends.server.types.operation.SearchReferenceSearchOperation;
import org.opends.server.util.TimeThread;
 
import static org.opends.messages.CoreMessages.*;
import static org.opends.server.loggers.AccessLogger.*;
import static org.opends.server.loggers.debug.DebugLogger.*;
import static org.opends.server.util.ServerConstants.*;
import static org.opends.server.util.StaticUtils.*;
 
/**
 * This class defines an operation that may be used to locate entries in the
 * Directory Server based on a given set of criteria.
 */
public class SearchOperationBasis
       extends AbstractOperation
       implements PreParseSearchOperation,
                  PostResponseSearchOperation,
                  SearchEntrySearchOperation,
                  SearchReferenceSearchOperation,
                  SearchOperation
{
  /**
   * The tracer object for the debug logger.
   */
  private static final DebugTracer TRACER = DebugLogger.getTracer();
 
  /**
   * Indicates whether a search result done response has been sent to the
   * client.
   */
  private final AtomicBoolean responseSent = new AtomicBoolean(false);
 
  /** Indicates whether the client is able to handle referrals. */
  private boolean clientAcceptsReferrals = true;
 
  /**
   * Indicates whether to include the account usable control with search result
   * entries.
   */
  private boolean includeUsableControl;
 
  /** Indicates whether to only real attributes should be returned. */
  private boolean realAttributesOnly;
 
  /** Indicates whether only LDAP subentries should be returned. */
  private boolean returnSubentriesOnly;
 
  /**
   * Indicates whether the filter references subentry or ldapSubentry object
   * class.
   */
  private boolean filterIncludesSubentries;
  private boolean filterNeedsCheckingForSubentries = true;
 
  /**
   * Indicates whether to include attribute types only or both types and values.
   */
  private boolean typesOnly;
 
  /** Indicates whether to only virtual attributes should be returned. */
  private boolean virtualAttributesOnly;
 
  /**
   * The raw, unprocessed base DN as included in the request from the client.
   */
  private ByteString rawBaseDN;
 
  /** The dereferencing policy for the search operation. */
  private DereferencePolicy derefPolicy;
 
  /** The base DN for the search operation. */
  private DN baseDN;
 
  /** The proxied authorization target DN for this operation. */
  private DN proxiedAuthorizationDN;
 
  /** The number of entries that have been sent to the client. */
  private final AtomicInteger entriesSent = new AtomicInteger();
 
  /**
   * The number of search result references that have been sent to the client.
   */
  private final AtomicInteger referencesSent = new AtomicInteger();
 
  /** The size limit for the search operation. */
  private int sizeLimit;
 
  /** The time limit for the search operation. */
  private int timeLimit;
 
  /** The raw, unprocessed filter as included in the request from the client. */
  private RawFilter rawFilter;
 
  /** The set of attributes that should be returned in matching entries. */
  private Set<String> attributes;
 
  /** The set of response controls for this search operation. */
  private final List<Control> responseControls = new ArrayList<Control>();
 
  /** The time that the search time limit has expired. */
  private long timeLimitExpiration;
 
  /** The matched values control associated with this search operation. */
  private MatchedValuesControl matchedValuesControl;
 
  /** The search filter for the search operation. */
  private SearchFilter filter;
 
  /** The search scope for the search operation. */
  private SearchScope scope;
 
  /** Indicates whether to send the search result done to the client or not. */
  private boolean sendResponse = true;
 
  /**
   * Creates a new search operation with the provided information.
   *
   * @param  clientConnection  The client connection with which this operation
   *                           is associated.
   * @param  operationID       The operation ID for this operation.
   * @param  messageID         The message ID of the request with which this
   *                           operation is associated.
   * @param  requestControls   The set of controls included in the request.
   * @param  rawBaseDN         The raw, unprocessed base DN as included in the
   *                           request from the client.
   * @param  scope             The scope for this search operation.
   * @param  derefPolicy       The alias dereferencing policy for this search
   *                           operation.
   * @param  sizeLimit         The size limit for this search operation.
   * @param  timeLimit         The time limit for this search operation.
   * @param  typesOnly         The typesOnly flag for this search operation.
   * @param  rawFilter         the raw, unprocessed filter as included in the
   *                           request from the client.
   * @param  attributes        The requested attributes for this search
   *                           operation.
   */
  public SearchOperationBasis(ClientConnection clientConnection,
                         long operationID,
                         int messageID, List<Control> requestControls,
                         ByteString rawBaseDN, SearchScope scope,
                         DereferencePolicy derefPolicy, int sizeLimit,
                         int timeLimit, boolean typesOnly, RawFilter rawFilter,
                         Set<String> attributes)
  {
    super(clientConnection, operationID, messageID, requestControls);
 
    this.rawBaseDN   = rawBaseDN;
    this.scope       = scope;
    this.derefPolicy = derefPolicy;
    this.sizeLimit   = sizeLimit;
    this.timeLimit   = timeLimit;
    this.typesOnly   = typesOnly;
    this.rawFilter   = rawFilter;
    this.attributes  = attributes != null ? attributes : new LinkedHashSet<String>(0);
 
    this.sizeLimit = getSizeLimit(sizeLimit, clientConnection);
    this.timeLimit = getTimeLimit(timeLimit, clientConnection);
  }
 
  /**
   * Creates a new search operation with the provided information.
   *
   * @param  clientConnection  The client connection with which this operation
   *                           is associated.
   * @param  operationID       The operation ID for this operation.
   * @param  messageID         The message ID of the request with which this
   *                           operation is associated.
   * @param  requestControls   The set of controls included in the request.
   * @param  baseDN            The base DN for this search operation.
   * @param  scope             The scope for this search operation.
   * @param  derefPolicy       The alias dereferencing policy for this search
   *                           operation.
   * @param  sizeLimit         The size limit for this search operation.
   * @param  timeLimit         The time limit for this search operation.
   * @param  typesOnly         The typesOnly flag for this search operation.
   * @param  filter            The filter for this search operation.
   * @param  attributes        The attributes for this search operation.
   */
  public SearchOperationBasis(ClientConnection clientConnection,
                         long operationID,
                         int messageID, List<Control> requestControls,
                         DN baseDN, SearchScope scope,
                         DereferencePolicy derefPolicy, int sizeLimit,
                         int timeLimit, boolean typesOnly, SearchFilter filter,
                         Set<String> attributes)
  {
    super(clientConnection, operationID, messageID, requestControls);
 
    this.baseDN      = baseDN;
    this.scope       = scope;
    this.derefPolicy = derefPolicy;
    this.sizeLimit   = sizeLimit;
    this.timeLimit   = timeLimit;
    this.typesOnly   = typesOnly;
    this.filter      = filter;
    this.attributes  = attributes != null ? attributes : new LinkedHashSet<String>(0);
 
    rawBaseDN = ByteString.valueOf(baseDN.toString());
    rawFilter = new LDAPFilter(filter);
 
    this.sizeLimit = getSizeLimit(sizeLimit, clientConnection);
    this.timeLimit = getTimeLimit(timeLimit, clientConnection);
  }
 
 
  private int getSizeLimit(int sizeLimit, ClientConnection clientConnection)
  {
    if (clientConnection.getSizeLimit() <= 0)
    {
      return sizeLimit;
    }
    else if (sizeLimit <= 0)
    {
      return clientConnection.getSizeLimit();
    }
    return Math.min(sizeLimit, clientConnection.getSizeLimit());
  }
 
  private int getTimeLimit(int timeLimit, ClientConnection clientConnection)
  {
    if (clientConnection.getTimeLimit() <= 0)
    {
      return timeLimit;
    }
    else if (timeLimit <= 0)
    {
      return clientConnection.getTimeLimit();
    }
    return Math.min(timeLimit, clientConnection.getTimeLimit());
  }
 
  /** {@inheritDoc} */
  @Override
  public final ByteString getRawBaseDN()
  {
    return rawBaseDN;
  }
 
  /** {@inheritDoc} */
  @Override
  public final void setRawBaseDN(ByteString rawBaseDN)
  {
    this.rawBaseDN = rawBaseDN;
 
    baseDN = null;
  }
 
  /** {@inheritDoc} */
  @Override
  public final DN getBaseDN()
  {
    try
    {
      if (baseDN == null)
      {
        baseDN = DN.decode(rawBaseDN);
      }
    }
    catch (DirectoryException de)
    {
      if (debugEnabled())
      {
        TRACER.debugCaught(DebugLogLevel.ERROR, de);
      }
 
      setResultCode(de.getResultCode());
      appendErrorMessage(de.getMessageObject());
      setMatchedDN(de.getMatchedDN());
      setReferralURLs(de.getReferralURLs());
    }
    return baseDN;
  }
 
  /** {@inheritDoc} */
  @Override
  public final void setBaseDN(DN baseDN)
  {
    this.baseDN = baseDN;
  }
 
  /** {@inheritDoc} */
  @Override
  public final SearchScope getScope()
  {
    return scope;
  }
 
  /** {@inheritDoc} */
  @Override
  public final void setScope(SearchScope scope)
  {
    this.scope = scope;
  }
 
  /** {@inheritDoc} */
  @Override
  public final DereferencePolicy getDerefPolicy()
  {
    return derefPolicy;
  }
 
  /** {@inheritDoc} */
  @Override
  public final void setDerefPolicy(DereferencePolicy derefPolicy)
  {
    this.derefPolicy = derefPolicy;
  }
 
  /** {@inheritDoc} */
  @Override
  public final int getSizeLimit()
  {
    return sizeLimit;
  }
 
  /** {@inheritDoc} */
  @Override
  public final void setSizeLimit(int sizeLimit)
  {
    this.sizeLimit = sizeLimit;
  }
 
  /** {@inheritDoc} */
  @Override
  public final int getTimeLimit()
  {
    return timeLimit;
  }
 
  /** {@inheritDoc} */
  @Override
  public final void setTimeLimit(int timeLimit)
  {
    this.timeLimit = timeLimit;
  }
 
  /** {@inheritDoc} */
  @Override
  public final boolean getTypesOnly()
  {
    return typesOnly;
  }
 
  /** {@inheritDoc} */
  @Override
  public final void setTypesOnly(boolean typesOnly)
  {
    this.typesOnly = typesOnly;
  }
 
  /** {@inheritDoc} */
  @Override
  public final RawFilter getRawFilter()
  {
    return rawFilter;
  }
 
  /** {@inheritDoc} */
  @Override
  public final void setRawFilter(RawFilter rawFilter)
  {
    this.rawFilter = rawFilter;
 
    filter = null;
  }
 
  /** {@inheritDoc} */
  @Override
  public final SearchFilter getFilter()
  {
    try
    {
      if (filter == null)
      {
        filter = rawFilter.toSearchFilter();
      }
    }
    catch (DirectoryException de)
    {
      if (debugEnabled())
      {
        TRACER.debugCaught(DebugLogLevel.ERROR, de);
      }
 
      setResultCode(de.getResultCode());
      appendErrorMessage(de.getMessageObject());
      setMatchedDN(de.getMatchedDN());
      setReferralURLs(de.getReferralURLs());
    }
    return filter;
  }
 
  /** {@inheritDoc} */
  @Override
  public final Set<String> getAttributes()
  {
    return attributes;
  }
 
  /** {@inheritDoc} */
  @Override
  public final void setAttributes(Set<String> attributes)
  {
    if (attributes == null)
    {
      this.attributes.clear();
    }
    else
    {
      this.attributes = attributes;
    }
  }
 
  /** {@inheritDoc} */
  @Override
  public final int getEntriesSent()
  {
    return entriesSent.get();
  }
 
  /** {@inheritDoc} */
  @Override
  public final int getReferencesSent()
  {
    return referencesSent.get();
  }
 
  /** {@inheritDoc} */
  @Override
  public final boolean returnEntry(Entry entry, List<Control> controls)
  {
    return returnEntry(entry, controls, true);
  }
 
  /** {@inheritDoc} */
  @Override
  public final boolean returnEntry(Entry entry, List<Control> controls,
                                   boolean evaluateAci)
  {
    boolean typesOnly = getTypesOnly();
 
    // See if the size limit has been exceeded.  If so, then don't send the
    // entry and indicate that the search should end.
    if (getSizeLimit() > 0 && getEntriesSent() >= getSizeLimit())
    {
      setResultCode(ResultCode.SIZE_LIMIT_EXCEEDED);
      appendErrorMessage(ERR_SEARCH_SIZE_LIMIT_EXCEEDED.get(getSizeLimit()));
      return false;
    }
 
    // See if the time limit has expired.  If so, then don't send the entry and
    // indicate that the search should end.
    if (getTimeLimit() > 0
        && TimeThread.getTime() >= getTimeLimitExpiration())
    {
      setResultCode(ResultCode.TIME_LIMIT_EXCEEDED);
      appendErrorMessage(ERR_SEARCH_TIME_LIMIT_EXCEEDED.get(getTimeLimit()));
      return false;
    }
 
    // Determine whether the provided entry is a subentry and if so whether it
    // should be returned.
    if (entry.isSubentry() || entry.isLDAPSubentry())
    {
      if (filterNeedsCheckingForSubentries)
      {
        filterIncludesSubentries = checkFilterForLDAPSubEntry(filter, 0);
        filterNeedsCheckingForSubentries = false;
      }
 
      if (getScope() != SearchScope.BASE_OBJECT
          && !filterIncludesSubentries
          && !isReturnSubentriesOnly())
      {
        return true;
      }
    }
    else if (isReturnSubentriesOnly())
    {
      // Subentries are visible and normal entries are not.
      return true;
    }
 
    // Determine whether to include the account usable control. If so, then
    // create it now.
    if (isIncludeUsableControl())
    {
      if (controls == null)
      {
        controls = new ArrayList<Control>(1);
      }
 
      try
      {
        // FIXME -- Need a way to enable PWP debugging.
        AuthenticationPolicyState state = AuthenticationPolicyState.forUser(
            entry, false);
        if (state.isPasswordPolicy())
        {
          PasswordPolicyState pwpState = (PasswordPolicyState) state;
 
          boolean isInactive = pwpState.isDisabled()
              || pwpState.isAccountExpired();
          boolean isLocked = pwpState.lockedDueToFailures()
              || pwpState.lockedDueToMaximumResetAge()
              || pwpState.lockedDueToIdleInterval();
          boolean isReset = pwpState.mustChangePassword();
          boolean isExpired = pwpState.isPasswordExpired();
 
          if (isInactive || isLocked || isReset || isExpired)
          {
            int secondsBeforeUnlock = pwpState.getSecondsUntilUnlock();
            int remainingGraceLogins = pwpState.getGraceLoginsRemaining();
            controls
                .add(new AccountUsableResponseControl(isInactive, isReset,
                    isExpired, remainingGraceLogins, isLocked,
                    secondsBeforeUnlock));
          }
          else
          {
            int secondsBeforeExpiration = pwpState.getSecondsUntilExpiration();
            controls.add(new AccountUsableResponseControl(
                secondsBeforeExpiration));
          }
        }
        // Another type of authentication policy (e.g. PTA).
        else if (state.isDisabled())
        {
          controls.add(new AccountUsableResponseControl(false, false, false,
              -1, true, -1));
        }
        else
        {
          controls.add(new AccountUsableResponseControl(-1));
        }
      }
      catch (Exception e)
      {
        if (debugEnabled())
        {
          TRACER.debugCaught(DebugLogLevel.ERROR, e);
        }
      }
    }
 
    // Check to see if the entry can be read by the client.
    SearchResultEntry unfilteredSearchEntry = new SearchResultEntry(entry, controls);
    if (evaluateAci && !getACIHandler().maySend(this, unfilteredSearchEntry))
    {
      return true;
    }
 
    // Make a copy of the entry and pare it down to only include the set
    // of requested attributes.
 
    // NOTE: that this copy will include the objectClass attribute.
    Entry filteredEntry =
        entry.filterEntry(getAttributes(), typesOnly,
            isVirtualAttributesOnly(), isRealAttributesOnly());
 
 
    // If there is a matched values control, then further pare down the entry
    // based on the filters that it contains.
    MatchedValuesControl matchedValuesControl = getMatchedValuesControl();
    if (matchedValuesControl != null && !typesOnly)
    {
      // First, look at the set of objectclasses.
 
      // NOTE: the objectClass attribute is also present and must be
      // dealt with later.
      AttributeType attrType = DirectoryServer.getObjectClassAttributeType();
      Iterator<String> ocIterator =
           filteredEntry.getObjectClasses().values().iterator();
      while (ocIterator.hasNext())
      {
        String ocName = ocIterator.next();
        AttributeValue v = AttributeValues.create(attrType,ocName);
        if (! matchedValuesControl.valueMatches(attrType, v))
        {
          ocIterator.remove();
        }
      }
 
 
      // Next, the set of user attributes (incl. objectClass attribute).
      for (Map.Entry<AttributeType, List<Attribute>> e : filteredEntry
          .getUserAttributes().entrySet())
      {
        AttributeType t = e.getKey();
        List<Attribute> oldAttributes = e.getValue();
        List<Attribute> newAttributes =
            new ArrayList<Attribute>(oldAttributes.size());
 
        for (Attribute a : oldAttributes)
        {
          // Assume that the attribute will be either empty or contain
          // very few values.
          AttributeBuilder builder = new AttributeBuilder(a, true);
          for (AttributeValue v : a)
          {
            if (matchedValuesControl.valueMatches(t, v))
            {
              builder.add(v);
            }
          }
          newAttributes.add(builder.toAttribute());
        }
        e.setValue(newAttributes);
      }
 
 
      // Then the set of operational attributes.
      for (Map.Entry<AttributeType, List<Attribute>> e : filteredEntry
          .getOperationalAttributes().entrySet())
      {
        AttributeType t = e.getKey();
        List<Attribute> oldAttributes = e.getValue();
        List<Attribute> newAttributes =
            new ArrayList<Attribute>(oldAttributes.size());
 
        for (Attribute a : oldAttributes)
        {
          // Assume that the attribute will be either empty or contain
          // very few values.
          AttributeBuilder builder = new AttributeBuilder(a, true);
          for (AttributeValue v : a)
          {
            if (matchedValuesControl.valueMatches(t, v))
            {
              builder.add(v);
            }
          }
          newAttributes.add(builder.toAttribute());
        }
        e.setValue(newAttributes);
      }
    }
 
 
    // Convert the provided entry to a search result entry.
    SearchResultEntry filteredSearchEntry = new SearchResultEntry(
        filteredEntry, controls);
 
    // Strip out any attributes that the client does not have access to.
 
    // FIXME: need some way to prevent plugins from adding attributes or
    // values that the client is not permitted to see.
    if (evaluateAci)
    {
      getACIHandler().filterEntry(this, unfilteredSearchEntry, filteredSearchEntry);
    }
 
    // Invoke any search entry plugins that may be registered with the server.
    PluginResult.IntermediateResponse pluginResult =
         DirectoryServer.getPluginConfigManager().
              invokeSearchResultEntryPlugins(this, filteredSearchEntry);
 
    // Send the entry to the client.
    if (pluginResult.sendResponse())
    {
      // Log the entry sent to the client.
      logSearchResultEntry(this, filteredSearchEntry);
 
      try
      {
        sendSearchEntry(filteredSearchEntry);
 
        entriesSent.incrementAndGet();
      }
      catch (DirectoryException de)
      {
        if (debugEnabled())
        {
          TRACER.debugCaught(DebugLogLevel.ERROR, de);
        }
 
        setResponseData(de);
        return false;
      }
    }
 
    return pluginResult.continueProcessing();
  }
 
  private AccessControlHandler<?> getACIHandler()
  {
    return AccessControlConfigManager.getInstance().getAccessControlHandler();
  }
 
  /** {@inheritDoc} */
  @Override
  public final boolean returnReference(DN dn, SearchResultReference reference)
  {
    return returnReference(dn, reference, true);
  }
 
  /** {@inheritDoc} */
  @Override
  public final boolean returnReference(DN dn, SearchResultReference reference,
                                       boolean evaluateAci)
  {
    // See if the time limit has expired.  If so, then don't send the entry and
    // indicate that the search should end.
    if (getTimeLimit() > 0
        && TimeThread.getTime() >= getTimeLimitExpiration())
    {
      setResultCode(ResultCode.TIME_LIMIT_EXCEEDED);
      appendErrorMessage(ERR_SEARCH_TIME_LIMIT_EXCEEDED.get(getTimeLimit()));
      return false;
    }
 
 
    // See if we know that this client can't handle referrals.  If so, then
    // don't even try to send it.
    if (!isClientAcceptsReferrals()
        // See if the client has permission to read this reference.
        || (evaluateAci && !getACIHandler().maySend(dn, this, reference)))
    {
      return true;
    }
 
 
    // Invoke any search reference plugins that may be registered with the
    // server.
    PluginResult.IntermediateResponse pluginResult =
         DirectoryServer.getPluginConfigManager().
              invokeSearchResultReferencePlugins(this, reference);
 
    // Send the reference to the client.  Note that this could throw an
    // exception, which would indicate that the associated client can't handle
    // referrals.  If that't the case, then set a flag so we'll know not to try
    // to send any more.
    if (pluginResult.sendResponse())
    {
      // Log the entry sent to the client.
      logSearchResultReference(this, reference);
 
      try
      {
        if (sendSearchReference(reference))
        {
          referencesSent.incrementAndGet();
 
          // FIXME -- Should the size limit apply here?
        }
        else
        {
          // We know that the client can't handle referrals, so we won't try to
          // send it any more.
          setClientAcceptsReferrals(false);
        }
      }
      catch (DirectoryException de)
      {
        if (debugEnabled())
        {
          TRACER.debugCaught(DebugLogLevel.ERROR, de);
        }
 
        setResponseData(de);
        return false;
      }
    }
 
    return pluginResult.continueProcessing();
  }
 
  /** {@inheritDoc} */
  @Override
  public final void sendSearchResultDone()
  {
    // Send the search result done message to the client.  We want to make sure
    // that this only gets sent once, and it's possible that this could be
    // multithreaded in the event of a persistent search, so do it safely.
    if (responseSent.compareAndSet(false, true))
    {
      logSearchResultDone(this);
 
      clientConnection.sendResponse(this);
 
      invokePostResponsePlugins();
    }
  }
 
  /** {@inheritDoc} */
  @Override
  public final OperationType getOperationType()
  {
    // Note that no debugging will be done in this method because it is a likely
    // candidate for being called by the logging subsystem.
    return OperationType.SEARCH;
  }
 
  /** {@inheritDoc} */
  @Override
  public DN getProxiedAuthorizationDN()
  {
    return proxiedAuthorizationDN;
  }
 
  /** {@inheritDoc} */
  @Override
  public final List<Control> getResponseControls()
  {
    return responseControls;
  }
 
  /** {@inheritDoc} */
  @Override
  public final void addResponseControl(Control control)
  {
    responseControls.add(control);
  }
 
  /** {@inheritDoc} */
  @Override
  public final void removeResponseControl(Control control)
  {
    responseControls.remove(control);
  }
 
  /** {@inheritDoc} */
  @Override
  public void abort(CancelRequest cancelRequest)
  {
    if(cancelResult == null && this.cancelRequest == null)
    {
      this.cancelRequest = cancelRequest;
    }
  }
 
  /** {@inheritDoc} */
  @Override
  public final void toString(StringBuilder buffer)
  {
    buffer.append("SearchOperation(connID=");
    buffer.append(clientConnection.getConnectionID());
    buffer.append(", opID=");
    buffer.append(operationID);
    buffer.append(", baseDN=");
    buffer.append(rawBaseDN);
    buffer.append(", scope=");
    buffer.append(scope.toString());
    buffer.append(", filter=");
    buffer.append(rawFilter.toString());
    buffer.append(")");
  }
 
  /** {@inheritDoc} */
  @Override
  public void setTimeLimitExpiration(long timeLimitExpiration)
  {
    this.timeLimitExpiration = timeLimitExpiration;
  }
 
  /** {@inheritDoc} */
  @Override
  public boolean isReturnSubentriesOnly()
  {
    return returnSubentriesOnly;
  }
 
  /** {@inheritDoc} */
  @Override
  public void setReturnSubentriesOnly(boolean returnLDAPSubentries)
  {
    this.returnSubentriesOnly = returnLDAPSubentries;
  }
 
  /** {@inheritDoc} */
  @Override
  public MatchedValuesControl getMatchedValuesControl()
  {
    return matchedValuesControl;
  }
 
  /** {@inheritDoc} */
  @Override
  public void setMatchedValuesControl(MatchedValuesControl controls)
  {
    this.matchedValuesControl = controls;
  }
 
  /** {@inheritDoc} */
  @Override
  public boolean isIncludeUsableControl()
  {
    return includeUsableControl;
  }
 
  /** {@inheritDoc} */
  @Override
  public void setIncludeUsableControl(boolean includeUsableControl)
  {
    this.includeUsableControl = includeUsableControl;
  }
 
  /** {@inheritDoc} */
  @Override
  public long getTimeLimitExpiration()
  {
    return timeLimitExpiration;
  }
 
  /** {@inheritDoc} */
  @Override
  public boolean isClientAcceptsReferrals()
  {
    return clientAcceptsReferrals;
  }
 
  /** {@inheritDoc} */
  @Override
  public void setClientAcceptsReferrals(boolean clientAcceptReferrals)
  {
    this.clientAcceptsReferrals = clientAcceptReferrals;
  }
 
  /** {@inheritDoc} */
  @Override
  public boolean isSendResponse()
  {
    return sendResponse;
  }
 
  /** {@inheritDoc} */
  @Override
  public void setSendResponse(boolean sendResponse)
  {
    this.sendResponse = sendResponse;
  }
 
  /** {@inheritDoc} */
  @Override
  public boolean isRealAttributesOnly()
  {
    return this.realAttributesOnly;
  }
 
  /** {@inheritDoc} */
  @Override
  public boolean isVirtualAttributesOnly()
  {
    return this.virtualAttributesOnly;
  }
 
  /** {@inheritDoc} */
  @Override
  public void setRealAttributesOnly(boolean realAttributesOnly)
  {
    this.realAttributesOnly = realAttributesOnly;
  }
 
  /** {@inheritDoc} */
  @Override
  public void setVirtualAttributesOnly(boolean virtualAttributesOnly)
  {
    this.virtualAttributesOnly = virtualAttributesOnly;
  }
 
  /** {@inheritDoc} */
  @Override
  public void sendSearchEntry(SearchResultEntry searchEntry)
      throws DirectoryException
  {
    getClientConnection().sendSearchEntry(this, searchEntry);
  }
 
  /** {@inheritDoc} */
  @Override
  public boolean sendSearchReference(SearchResultReference searchReference)
      throws DirectoryException
  {
    return getClientConnection().sendSearchReference(this, searchReference);
  }
 
  /** {@inheritDoc} */
  @Override
  public void setProxiedAuthorizationDN(DN proxiedAuthorizationDN)
  {
    this.proxiedAuthorizationDN = proxiedAuthorizationDN;
  }
 
  /** {@inheritDoc} */
  @Override
  public final void run()
  {
    setResultCode(ResultCode.UNDEFINED);
 
    // Start the processing timer.
    setProcessingStartTime();
 
    // Log the search request message.
    logSearchRequest(this);
 
    setSendResponse(true);
 
    // Get the plugin config manager that will be used for invoking plugins.
    PluginConfigManager pluginConfigManager =
        DirectoryServer.getPluginConfigManager();
 
    int timeLimit = getTimeLimit();
    long timeLimitExpiration;
    if (timeLimit <= 0)
    {
      timeLimitExpiration = Long.MAX_VALUE;
    }
    else
    {
      // FIXME -- Factor in the user's effective time limit.
      timeLimitExpiration = getProcessingStartTime() + (1000L * timeLimit);
    }
    setTimeLimitExpiration(timeLimitExpiration);
 
    try
    {
      // Check for and handle a request to cancel this operation.
      checkIfCanceled(false);
 
      PluginResult.PreParse preParseResult =
          pluginConfigManager.invokePreParseSearchPlugins(this);
 
      if(!preParseResult.continueProcessing())
      {
        setResultCode(preParseResult.getResultCode());
        appendErrorMessage(preParseResult.getErrorMessage());
        setMatchedDN(preParseResult.getMatchedDN());
        setReferralURLs(preParseResult.getReferralURLs());
        return;
      }
 
      // Check for and handle a request to cancel this operation.
      checkIfCanceled(false);
 
      // Process the search base and filter to convert them from their raw forms
      // as provided by the client to the forms required for the rest of the
      // search processing.
      DN baseDN = getBaseDN();
      if (baseDN == null){
        return;
      }
 
 
      // Retrieve the network group attached to the client connection
      // and get a workflow to process the operation.
      NetworkGroup ng = getClientConnection().getNetworkGroup();
      Workflow workflow = ng.getWorkflowCandidate(baseDN);
      if (workflow == null)
      {
        // We have found no workflow for the requested base DN, just return
        // a no such entry result code and stop the processing.
        updateOperationErrMsgAndResCode();
        return;
      }
      workflow.execute(this);
    }
    catch(CanceledOperationException coe)
    {
      if (debugEnabled())
      {
        TRACER.debugCaught(DebugLogLevel.ERROR, coe);
      }
 
      setResultCode(ResultCode.CANCELED);
      cancelResult = new CancelResult(ResultCode.CANCELED, null);
 
      appendErrorMessage(coe.getCancelRequest().getCancelReason());
    }
    finally
    {
      // Stop the processing timer.
      setProcessingStopTime();
 
      if(cancelRequest == null || cancelResult == null ||
          cancelResult.getResultCode() != ResultCode.CANCELED)
      {
        // If everything is successful to this point and it is not a persistent
        // search, then send the search result done message to the client.
        // Otherwise, we'll want to make the size and time limit values
        // unlimited to ensure that the remainder of the persistent search
        // isn't subject to those restrictions.
        if (isSendResponse())
        {
          sendSearchResultDone();
        }
        else
        {
          setSizeLimit(0);
          setTimeLimit(0);
        }
      }
      else if(cancelRequest.notifyOriginalRequestor() ||
          DirectoryServer.notifyAbandonedOperations())
      {
        sendSearchResultDone();
      }
 
      // If no cancel result, set it
      if(cancelResult == null)
      {
        cancelResult = new CancelResult(ResultCode.TOO_LATE, null);
      }
    }
  }
 
 
  /**
   * Invokes the post response plugins.
   */
  private void invokePostResponsePlugins()
  {
    // Get the plugin config manager that will be used for invoking plugins.
    PluginConfigManager pluginConfigManager =
      DirectoryServer.getPluginConfigManager();
 
    // Invoke the post response plugins that have been registered with
    // the current operation
    pluginConfigManager.invokePostResponseSearchPlugins(this);
  }
 
 
  /**
   * Updates the error message and the result code of the operation.
   *
   * This method is called because no workflows were found to process
   * the operation.
   */
  private void updateOperationErrMsgAndResCode()
  {
    setResultCode(ResultCode.NO_SUCH_OBJECT);
    Message message =
            ERR_SEARCH_BASE_DOESNT_EXIST.get(String.valueOf(getBaseDN()));
    appendErrorMessage(message);
  }
 
 
 
  /**
   * Checks if the filter contains an equality element with the objectclass
   * attribute type and a value of "ldapSubentry" and if so sets
   * returnSubentriesOnly to <code>true</code>.
   *
   * @param filter
   *          The complete filter being checked, of which this filter may be a
   *          subset.
   * @param depth
   *          The current depth of the evaluation, which is used to prevent
   *          infinite recursion due to highly nested filters and eventually
   *          running out of stack space.
   * @return {@code true} if the filter references the sub-entry object class.
   */
  private boolean checkFilterForLDAPSubEntry(SearchFilter filter, int depth)
  {
    // Paranoid check to avoid recursion deep enough to provoke
    // the stack overflow. This should never happen because if
    // a given filter is too nested SearchFilter exception gets
    // raised long before this method is invoked.
    if (depth >= MAX_NESTED_FILTER_DEPTH)
    {
      if (debugEnabled())
      {
        TRACER.debugError("Exceeded maximum filter depth");
      }
      return false;
    }
 
    switch (filter.getFilterType())
    {
    case EQUALITY:
      if (filter.getAttributeType().isObjectClassType())
      {
        AttributeValue v = filter.getAssertionValue();
        // FIXME : technically this is not correct since the presence
        // of draft oc would trigger rfc oc visibility and visa versa.
        String stringValueLC = toLowerCase(v.getValue().toString());
        if (OC_LDAP_SUBENTRY_LC.equals(stringValueLC) ||
            OC_SUBENTRY.equals(stringValueLC))
        {
          return true;
        }
      }
      break;
    case AND:
    case OR:
      for (SearchFilter f : filter.getFilterComponents())
      {
        if (checkFilterForLDAPSubEntry(f, depth + 1))
        {
          return true;
        }
      }
      break;
    }
 
    return false;
  }
}