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

Yannick Lecaillez
25.07.2016 464f6dd52a1eeeef0f7b38d4dc1840501818a36f
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
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
/*
 * The contents of this file are subject to the terms of the Common Development and
 * Distribution License (the License). You may not use this file except in compliance with the
 * License.
 *
 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
 * specific language governing permission and limitations under the License.
 *
 * When distributing Covered Software, include this CDDL Header Notice in each file and include
 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
 * Header, with the fields enclosed by brackets [] replaced by your own identifying
 * information: "Portions Copyright [year] [name of copyright owner]".
 *
 * Copyright 2006-2010 Sun Microsystems, Inc.
 * Portions Copyright 2010-2016 ForgeRock AS.
 */
package org.forgerock.opendj.reactive;
 
import static com.forgerock.reactive.RxJavaStreams.*;
import static org.opends.messages.CoreMessages.*;
import static org.opends.messages.ProtocolMessages.*;
import static org.opends.server.loggers.AccessLogger.logDisconnect;
import static org.opends.server.protocols.ldap.LDAPConstants.*;
import static org.opends.server.util.ServerConstants.OID_START_TLS_REQUEST;
import static org.opends.server.util.StaticUtils.getExceptionMessage;
 
import java.net.InetAddress;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.security.cert.Certificate;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
 
import org.forgerock.i18n.LocalizableException;
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.i18n.LocalizableMessageBuilder;
import org.forgerock.i18n.slf4j.LocalizedLogger;
import org.forgerock.opendj.adapter.server3x.Converters;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.DN;
import org.forgerock.opendj.ldap.LDAPClientContext;
import org.forgerock.opendj.ldap.LDAPClientContext.DisconnectListener;
import org.forgerock.opendj.ldap.ResultCode;
import org.forgerock.opendj.ldap.requests.UnbindRequest;
import org.forgerock.opendj.ldap.responses.CompareResult;
import org.forgerock.opendj.ldap.responses.Response;
import org.forgerock.opendj.ldap.responses.Responses;
import org.forgerock.opendj.ldap.responses.Result;
import org.forgerock.opendj.ldap.spi.LdapMessages.LdapRawMessage;
import org.opends.server.api.ClientConnection;
import org.opends.server.api.ConnectionHandler;
import org.opends.server.core.AbandonOperationBasis;
import org.opends.server.core.AddOperationBasis;
import org.opends.server.core.BindOperationBasis;
import org.opends.server.core.CompareOperationBasis;
import org.opends.server.core.DeleteOperationBasis;
import org.opends.server.core.DirectoryServer;
import org.opends.server.core.ExtendedOperationBasis;
import org.opends.server.core.ModifyDNOperationBasis;
import org.opends.server.core.ModifyOperationBasis;
import org.opends.server.core.PersistentSearch;
import org.opends.server.core.PluginConfigManager;
import org.opends.server.core.QueueingStrategy;
import org.opends.server.core.SearchOperation;
import org.opends.server.core.SearchOperationBasis;
import org.opends.server.core.UnbindOperationBasis;
import org.opends.server.extensions.TLSCapableConnection;
import org.opends.server.protocols.ldap.AbandonRequestProtocolOp;
import org.opends.server.protocols.ldap.AddRequestProtocolOp;
import org.opends.server.protocols.ldap.BindRequestProtocolOp;
import org.opends.server.protocols.ldap.CompareRequestProtocolOp;
import org.opends.server.protocols.ldap.DeleteRequestProtocolOp;
import org.opends.server.protocols.ldap.ExtendedRequestProtocolOp;
import org.opends.server.protocols.ldap.LDAPMessage;
import org.opends.server.protocols.ldap.LDAPReader;
import org.opends.server.protocols.ldap.LDAPResultCode;
import org.opends.server.protocols.ldap.LDAPStatistics;
import org.opends.server.protocols.ldap.ModifyDNRequestProtocolOp;
import org.opends.server.protocols.ldap.ModifyRequestProtocolOp;
import org.opends.server.protocols.ldap.SearchRequestProtocolOp;
import org.opends.server.types.AuthenticationType;
import org.opends.server.types.CancelRequest;
import org.opends.server.types.CancelResult;
import org.opends.server.types.Control;
import org.opends.server.types.DirectoryException;
import org.opends.server.types.DisconnectReason;
import org.opends.server.types.IntermediateResponse;
import org.opends.server.types.Operation;
import org.opends.server.types.OperationType;
import org.opends.server.types.SearchResultEntry;
import org.opends.server.types.SearchResultReference;
import org.opends.server.util.TimeThread;
 
import com.forgerock.reactive.ReactiveHandler;
import com.forgerock.reactive.Single;
import com.forgerock.reactive.Stream;
 
import io.reactivex.BackpressureOverflowStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableEmitter.BackpressureMode;
import io.reactivex.FlowableOnSubscribe;
 
/**
 * This class defines an LDAP client connection, which is a type of client connection that will be accepted by an
 * instance of the LDAP connection handler and have its requests decoded by an LDAP request handler.
 */
public final class LDAPClientConnection2 extends ClientConnection implements TLSCapableConnection,
        ReactiveHandler<QueueingStrategy, LdapRawMessage, Stream<Response>> {
    private static final String REACTIVE_OUT = "reactive.out";
 
    /** The tracer object for the debug logger. */
    private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
 
    /** The time that the last operation was completed. */
    private final AtomicLong lastCompletionTime;
    /** The next operation ID that should be used for this connection. */
    private final AtomicLong nextOperationID;
 
    /**
     * Indicates whether the Directory Server believes this connection to be valid and available for communication.
     */
    private volatile boolean connectionValid;
 
    /**
     * Indicates whether this connection is about to be closed. This will be used to prevent accepting new requests
     * while a disconnect is in progress.
     */
    private boolean disconnectRequested;
 
    /**
     * Indicates whether the connection should keep statistics regarding the operations that it is performing.
     */
    private final boolean keepStats;
 
    /** The set of all operations currently in progress on this connection. */
    private final ConcurrentHashMap<Integer, Operation> operationsInProgress;
 
    /**
     * The number of operations performed on this connection. Used to compare with the resource limits of the network
     * group.
     */
    private final AtomicLong operationsPerformed;
 
    /** The port on the client from which this connection originated. */
    private final int clientPort;
    /** The LDAP version that the client is using to communicate with the server. */
    private int ldapVersion;
    /** The port on the server to which this client has connected. */
    private final int serverPort;
 
    /** The reference to the connection handler that accepted this connection. */
    private final LDAPConnectionHandler2 connectionHandler;
    /** The statistics tracker associated with this client connection. */
    private final LDAPStatistics statTracker;
    private final boolean useNanoTime;
 
    /** The connection ID assigned to this connection. */
    private final long connectionID;
 
    /** The lock used to provide threadsafe access to the set of operations in progress. */
    private final Object opsInProgressLock;
 
    /** The socket channel with which this client connection is associated. */
    private final LDAPClientContext clientContext;
 
    /** The string representation of the address of the client. */
    private final String clientAddress;
    /** The name of the protocol that the client is using to communicate with the server. */
    private final String protocol;
    /** The string representation of the address of the server to which the client has connected. */
    private final String serverAddress;
 
    /**
     * Creates a new LDAP client connection with the provided information.
     *
     * @param connectionHandler
     *            The connection handler that accepted this connection.
     * @param clientContext
     *            The socket channel that may be used to communicate with the client.
     * @param protocol
     *            String representing the protocol (LDAP or LDAP+SSL).
     * @throws LdapException
     * @throws DirectoryException
     *             If SSL initialisation fails.
     */
    LDAPClientConnection2(LDAPConnectionHandler2 connectionHandler, LDAPClientContext clientContext, String protocol,
            boolean keepStats) {
        this.connectionHandler = connectionHandler;
        this.clientContext = clientContext;
        opsInProgressLock = new Object();
        ldapVersion = 3;
        lastCompletionTime = new AtomicLong(TimeThread.getTime());
        nextOperationID = new AtomicLong(0);
        connectionValid = true;
        disconnectRequested = false;
        operationsInProgress = new ConcurrentHashMap<>();
        operationsPerformed = new AtomicLong(0);
        this.keepStats = keepStats;
        this.protocol = protocol;
 
        clientAddress = clientContext.getPeerAddress().getAddress().getHostAddress();
        clientPort = clientContext.getPeerAddress().getPort();
        serverAddress = clientContext.getLocalAddress().getAddress().getHostAddress();
        serverPort = clientContext.getLocalAddress().getPort();
 
        statTracker = this.connectionHandler.getStatTracker();
        if (keepStats) {
            statTracker.updateConnect();
            this.useNanoTime = DirectoryServer.getUseNanoTime();
        } else {
            this.useNanoTime = false;
        }
 
        connectionID = DirectoryServer.newConnectionAccepted(this);
        clientContext.onDisconnect(new DisconnectListener() {
            @Override
            public void exceptionOccurred(LDAPClientContext context, Throwable error) {
                if (error instanceof LocalizableException) {
                    disconnect(
                            DisconnectReason.PROTOCOL_ERROR, true, ((LocalizableException) error).getMessageObject());
                } else {
                    disconnect(DisconnectReason.PROTOCOL_ERROR, true, null);
                }
            }
 
            @Override
            public void connectionDisconnected(LDAPClientContext context, ResultCode resultCode,
                    String diagnosticMessage) {
                disconnect(DisconnectReason.SERVER_ERROR, false, null);
            }
 
            @Override
            public void connectionClosed(LDAPClientContext context, UnbindRequest unbindRequest) {
                disconnect(DisconnectReason.CLIENT_DISCONNECT, false, null);
            }
        });
    }
 
    /**
     * Retrieves the connection ID assigned to this connection.
     *
     * @return The connection ID assigned to this connection.
     */
    @Override
    public long getConnectionID() {
        return connectionID;
    }
 
    /**
     * Retrieves the connection handler that accepted this client connection.
     *
     * @return The connection handler that accepted this client connection.
     */
    @Override
    public ConnectionHandler<?> getConnectionHandler() {
        return connectionHandler;
    }
 
    /**
     * Retrieves the socket channel that can be used to communicate with the client.
     *
     * @return The socket channel that can be used to communicate with the client.
     */
    @Override
    public SocketChannel getSocketChannel() {
        throw new UnsupportedOperationException();
    }
 
    /**
     * Retrieves the protocol that the client is using to communicate with the Directory Server.
     *
     * @return The protocol that the client is using to communicate with the Directory Server.
     */
    @Override
    public String getProtocol() {
        return protocol;
    }
 
    /**
     * Retrieves a string representation of the address of the client.
     *
     * @return A string representation of the address of the client.
     */
    @Override
    public String getClientAddress() {
        return clientAddress;
    }
 
    /**
     * Retrieves the port number for this connection on the client system.
     *
     * @return The port number for this connection on the client system.
     */
    @Override
    public int getClientPort() {
        return clientPort;
    }
 
    /**
     * Retrieves a string representation of the address on the server to which the client connected.
     *
     * @return A string representation of the address on the server to which the client connected.
     */
    @Override
    public String getServerAddress() {
        return serverAddress;
    }
 
    /**
     * Retrieves the port number for this connection on the server system.
     *
     * @return The port number for this connection on the server system.
     */
    @Override
    public int getServerPort() {
        return serverPort;
    }
 
    /**
     * Retrieves the <CODE>java.net.InetAddress</CODE> associated with the remote client system.
     *
     * @return The <CODE>java.net.InetAddress</CODE> associated with the remote client system. It may be
     *         <CODE>null</CODE> if the client is not connected over an IP-based connection.
     */
    @Override
    public InetAddress getRemoteAddress() {
        return clientContext.getPeerAddress().getAddress();
    }
 
    /**
     * Retrieves the <CODE>java.net.InetAddress</CODE> for the Directory Server system to which the client has
     * established the connection.
     *
     * @return The <CODE>java.net.InetAddress</CODE> for the Directory Server system to which the client has established
     *         the connection. It may be <CODE>null</CODE> if the client is not connected over an IP-based connection.
     */
    @Override
    public InetAddress getLocalAddress() {
        return clientContext.getLocalAddress().getAddress();
    }
 
    @Override
    public boolean isConnectionValid() {
        return this.connectionValid;
    }
 
    /**
     * Indicates whether this client connection is currently using a secure mechanism to communicate with the server.
     * Note that this may change over time based on operations performed by the client or server (e.g., it may go from
     * <CODE>false</CODE> to <CODE>true</CODE> if the client uses the StartTLS extended operation).
     *
     * @return <CODE>true</CODE> if the client connection is currently using a secure mechanism to communicate with the
     *         server, or <CODE>false</CODE> if not.
     */
    @Override
    public boolean isSecure() {
        return false;
    }
 
    /**
     * Sends a response to the client based on the information in the provided operation.
     *
     * @param operation
     *            The operation for which to send the response.
     */
    @Override
    public void sendResponse(Operation operation) {
        // Since this is the final response for this operation, we can go
        // ahead and remove it from the "operations in progress" list. It
        // can't be canceled after this point, and this will avoid potential
        // race conditions in which the client immediately sends another
        // request with the same message ID as was used for this operation.
 
        if (keepStats) {
            long time;
            if (useNanoTime) {
                time = operation.getProcessingNanoTime();
            } else {
                time = operation.getProcessingTime();
            }
            this.statTracker.updateOperationMonitoringData(operation.getOperationType(), time);
        }
 
        // Avoid sending the response if one has already been sent. This may happen
        // if operation processing encounters a run-time exception after sending the
        // response: the worker thread exception handling code will attempt to send
        // an error result to the client indicating that a problem occurred.
        if (removeOperationInProgress(operation.getMessageID())) {
            final Response response = operationToResponse(operation);
            final FlowableEmitter<Response> out = getOut(operation);
            if (response != null) {
                out.onNext(response);
            }
            out.onComplete();
        }
    }
 
    /**
     * Retrieves an LDAPMessage containing a response generated from the provided operation.
     *
     * @param operation
     *            The operation to use to generate the response LDAPMessage.
     * @return An LDAPMessage containing a response generated from the provided operation.
     */
    private Response operationToResponse(Operation operation) {
        ResultCode resultCode = operation.getResultCode();
        if (resultCode == null) {
            // This must mean that the operation has either not yet completed
            // or that it completed without a result for some reason. In any
            // case, log a message and set the response to "operations error".
            logger.error(ERR_LDAP_CLIENT_SEND_RESPONSE_NO_RESULT_CODE, operation.getOperationType(),
                    operation.getConnectionID(), operation.getOperationID());
            resultCode = DirectoryServer.getServerErrorResultCode();
        }
 
        LocalizableMessageBuilder errorMessage = operation.getErrorMessage();
        String matchedDN = operation.getMatchedDN() != null ? operation.getMatchedDN().toString() : null;
 
        // Referrals are not allowed for LDAPv2 clients.
        List<String> referralURLs;
        if (ldapVersion == 2) {
            referralURLs = null;
 
            if (resultCode == ResultCode.REFERRAL) {
                resultCode = ResultCode.CONSTRAINT_VIOLATION;
                errorMessage.append(ERR_LDAPV2_REFERRAL_RESULT_CHANGED.get());
            }
 
            List<String> opReferrals = operation.getReferralURLs();
            if (opReferrals != null && !opReferrals.isEmpty()) {
                StringBuilder referralsStr = new StringBuilder();
                Iterator<String> iterator = opReferrals.iterator();
                referralsStr.append(iterator.next());
 
                while (iterator.hasNext()) {
                    referralsStr.append(", ");
                    referralsStr.append(iterator.next());
                }
 
                errorMessage.append(ERR_LDAPV2_REFERRALS_OMITTED.get(referralsStr));
            }
        } else {
            referralURLs = operation.getReferralURLs();
        }
 
        final Result result;
        switch (operation.getOperationType()) {
        case ADD:
            result = Responses.newResult(resultCode).setDiagnosticMessage(errorMessage.toString())
                    .setMatchedDN(matchedDN);
            break;
        case BIND:
            result = Responses.newBindResult(resultCode).setDiagnosticMessage(errorMessage.toString())
                    .setMatchedDN(matchedDN)
                    .setServerSASLCredentials(((BindOperationBasis) operation).getServerSASLCredentials());
            break;
        case COMPARE:
            result = Responses.newCompareResult(resultCode).setDiagnosticMessage(errorMessage.toString())
                    .setMatchedDN(matchedDN);
            break;
        case DELETE:
            result = Responses.newResult(resultCode).setDiagnosticMessage(errorMessage.toString())
                    .setMatchedDN(matchedDN);
            break;
        case EXTENDED:
            // If this an LDAPv2 client, then we can't send this.
            if (ldapVersion == 2) {
                logger.error(ERR_LDAPV2_SKIPPING_EXTENDED_RESPONSE, getConnectionID(), operation.getOperationID(),
                        operation);
                return null;
            }
 
            ExtendedOperationBasis extOp = (ExtendedOperationBasis) operation;
            result = Responses.newGenericExtendedResult(resultCode).setDiagnosticMessage(errorMessage.toString())
                    .setMatchedDN(matchedDN).setOID(extOp.getResponseOID()).setValue(extOp.getResponseValue());
            break;
        case MODIFY:
            result = Responses.newResult(resultCode).setDiagnosticMessage(errorMessage.toString())
                    .setMatchedDN(matchedDN);
            break;
        case MODIFY_DN:
            result = Responses.newResult(resultCode).setDiagnosticMessage(errorMessage.toString())
                    .setMatchedDN(matchedDN);
            break;
        case SEARCH:
            result = Responses.newResult(resultCode).setDiagnosticMessage(errorMessage.toString())
                    .setMatchedDN(matchedDN);
            break;
        default:
            // This must be a type of operation that doesn't have a response.
            // This shouldn't happen, so log a message and return.
            logger.error(ERR_LDAP_CLIENT_SEND_RESPONSE_INVALID_OP, operation.getOperationType(), getConnectionID(),
                    operation.getOperationID(), operation);
            return null;
        }
        if (referralURLs != null) {
            result.getReferralURIs().addAll(referralURLs);
        }
 
        // Controls are not allowed for LDAPv2 clients.
        if (ldapVersion != 2) {
            for (Control control : operation.getResponseControls()) {
                result.addControl(Converters.from(control));
            }
        }
 
        return result;
    }
 
    /**
     * Sends the provided search result entry to the client.
     *
     * @param searchOperation
     *            The search operation with which the entry is associated
     * @param searchEntry
     *            The search result entry to be sent to the client
     */
    @Override
    public void sendSearchEntry(SearchOperation searchOperation, SearchResultEntry searchEntry) {
        getEmitter(searchOperation).onNext(toResponse(searchEntry));
    }
 
    private FlowableEmitter<Response> getEmitter(SearchOperation searchOperation) {
        return getOut(searchOperation);
    }
 
    private Response toResponse(SearchResultEntry searchEntry) {
        return Responses.newSearchResultEntry(Converters.partiallyWrap(searchEntry));
    }
 
    private FlowableEmitter<Response> getOut(Operation operation) {
        return ((FlowableEmitter<Response>) operation.getAttachment(REACTIVE_OUT));
    }
 
    /**
     * Sends the provided search result reference to the client.
     *
     * @param searchOperation
     *            The search operation with which the reference is associated.
     * @param searchReference
     *            The search result reference to be sent to the client.
     * @return <CODE>true</CODE> if the client is able to accept referrals, or <CODE>false</CODE> if the client cannot
     *         handle referrals and no more attempts should be made to send them for the associated search operation.
     */
    @Override
    public boolean sendSearchReference(SearchOperation searchOperation, SearchResultReference searchReference) {
        // Make sure this is not an LDAPv2 client. If it is, then they can't
        // see referrals so we'll not send anything. Also, throw an
        // exception so that the core server will know not to try sending
        // any more referrals to this client for the rest of the operation.
        if (ldapVersion == 2) {
            logger.error(ERR_LDAPV2_SKIPPING_SEARCH_REFERENCE, getConnectionID(), searchOperation.getOperationID(),
                    searchReference);
            return false;
        }
 
        final FlowableEmitter<Response> out = getOut(searchOperation);
        out.onNext(Converters.from(searchReference));
 
        return true;
    }
 
    /**
     * Sends the provided intermediate response message to the client.
     *
     * @param intermediateResponse
     *            The intermediate response message to be sent.
     * @return <CODE>true</CODE> if processing on the associated operation should continue, or <CODE>false</CODE> if
     *         not.
     */
    @Override
    protected boolean sendIntermediateResponseMessage(IntermediateResponse intermediateResponse) {
        final Operation operation = intermediateResponse.getOperation();
        final FlowableEmitter<Response> out = getOut(operation);
 
        final Response response = Responses.newGenericIntermediateResponse(intermediateResponse.getOID(),
                intermediateResponse.getValue());
        for (Control control : intermediateResponse.getControls()) {
            response.addControl(Converters.from(control));
        }
 
        out.onNext(response);
 
        // The only reason we shouldn't continue processing is if the
        // connection is closed.
        return connectionValid;
    }
 
    /**
     * Closes the connection to the client, optionally sending it a message indicating the reason for the closure. Note
     * that the ability to send a notice of disconnection may not be available for all protocols or under all
     * circumstances.
     *
     * @param disconnectReason
     *            The disconnect reason that provides the generic cause for the disconnect.
     * @param sendNotification
     *            Indicates whether to try to provide notification to the client that the connection will be closed.
     * @param message
     *            The message to include in the disconnect notification response. It may be <CODE>null</CODE> if no
     *            message is to be sent.
     */
    @Override
    public void disconnect(DisconnectReason disconnectReason, boolean sendNotification, LocalizableMessage message) {
        // Set a flag indicating that the connection is being terminated so
        // that no new requests will be accepted. Also cancel all operations
        // in progress.
        synchronized (opsInProgressLock) {
            // If we are already in the middle of a disconnect, then don't
            // do anything.
            if (disconnectRequested) {
                return;
            }
 
            disconnectRequested = true;
        }
 
        if (keepStats) {
            statTracker.updateDisconnect();
        }
 
        if (connectionID >= 0) {
            DirectoryServer.connectionClosed(this);
        }
 
        // Indicate that this connection is no longer valid.
        connectionValid = false;
 
        final LocalizableMessage cancelMessage;
        if (message != null) {
            cancelMessage = new LocalizableMessageBuilder().append(disconnectReason.getClosureMessage()).append(": ")
                    .append(message).toMessage();
        } else {
            cancelMessage = disconnectReason.getClosureMessage();
        }
        cancelAllOperations(new CancelRequest(true, cancelMessage));
        finalizeConnectionInternal();
 
        // See if we should send a notification to the client. If so, then
        // construct and send a notice of disconnection unsolicited
        // response. Note that we cannot send this notification to an LDAPv2 client.
        if (sendNotification && ldapVersion != 2) {
            try {
                LocalizableMessage errMsg = message != null ? message
                        : INFO_LDAP_CLIENT_GENERIC_NOTICE_OF_DISCONNECTION.get();
                clientContext.disconnect(ResultCode.valueOf(toResultCode(disconnectReason)), errMsg.toString());
            } catch (Exception e) {
                // NYI -- Log a message indicating that we couldn't send the
                // notice of disconnection.
                logger.traceException(e);
            }
        } else {
            clientContext.disconnect();
        }
 
        // NYI -- Deregister the client connection from any server components that
        // might know about it.
 
        logDisconnect(this, disconnectReason, message);
 
        try {
            PluginConfigManager pluginManager = DirectoryServer.getPluginConfigManager();
            pluginManager.invokePostDisconnectPlugins(this, disconnectReason, message);
        } catch (Exception e) {
            logger.traceException(e);
        }
    }
 
    private int toResultCode(DisconnectReason disconnectReason) {
        switch (disconnectReason) {
        case PROTOCOL_ERROR:
            return LDAPResultCode.PROTOCOL_ERROR;
        case SERVER_SHUTDOWN:
            return LDAPResultCode.UNAVAILABLE;
        case SERVER_ERROR:
            return DirectoryServer.getServerErrorResultCode().intValue();
        case ADMIN_LIMIT_EXCEEDED:
        case IDLE_TIME_LIMIT_EXCEEDED:
        case MAX_REQUEST_SIZE_EXCEEDED:
        case IO_TIMEOUT:
            return LDAPResultCode.ADMIN_LIMIT_EXCEEDED;
        case CONNECTION_REJECTED:
            return LDAPResultCode.CONSTRAINT_VIOLATION;
        case INVALID_CREDENTIALS:
            return LDAPResultCode.INVALID_CREDENTIALS;
        default:
            return LDAPResultCode.OTHER;
        }
    }
 
    /**
     * Retrieves the set of operations in progress for this client connection. This list must not be altered by any
     * caller.
     *
     * @return The set of operations in progress for this client connection.
     */
    @Override
    public Collection<Operation> getOperationsInProgress() {
        return operationsInProgress.values();
    }
 
    /**
     * Retrieves the operation in progress with the specified message ID.
     *
     * @param messageID
     *            The message ID for the operation to retrieve.
     * @return The operation in progress with the specified message ID, or <CODE>null</CODE> if no such operation could
     *         be found.
     */
    @Override
    public Operation getOperationInProgress(int messageID) {
        return operationsInProgress.get(messageID);
    }
 
    /**
     * Adds the provided operation to the set of operations in progress for this client connection.
     *
     * @param operation
     *            The operation to add to the set of operations in progress for this client connection.
     * @throws DirectoryException
     *             If the operation is not added for some reason (e.g., the client already has reached the maximum
     *             allowed concurrent requests).
     */
    private void addOperationInProgress(final QueueingStrategy queueingStrategy, Operation operation)
            throws DirectoryException {
        int messageID = operation.getMessageID();
 
        // We need to grab a lock to ensure that no one else can add
        // operations to the queue while we are performing some preliminary
        // checks.
        try {
            synchronized (opsInProgressLock) {
                // If we're already in the process of disconnecting the client,
                // then reject the operation.
                if (disconnectRequested) {
                    LocalizableMessage message = WARN_CLIENT_DISCONNECT_IN_PROGRESS.get();
                    throw new DirectoryException(ResultCode.UNWILLING_TO_PERFORM, message);
                }
 
                // Add the operation to the list of operations in progress for
                // this connection.
                Operation op = operationsInProgress.putIfAbsent(messageID, operation);
 
                // See if there is already an operation in progress with the
                // same message ID. If so, then we can't allow it.
                if (op != null) {
                    LocalizableMessage message = WARN_LDAP_CLIENT_DUPLICATE_MESSAGE_ID.get(messageID);
                    throw new DirectoryException(ResultCode.PROTOCOL_ERROR, message);
                }
            }
 
            // Try to add the operation to the work queue,
            // or run it synchronously (typically for the administration
            // connector)
            queueingStrategy.enqueueRequest(operation);
        } catch (DirectoryException de) {
            logger.traceException(de);
 
            operationsInProgress.remove(messageID);
            lastCompletionTime.set(TimeThread.getTime());
 
            throw de;
        } catch (Exception e) {
            logger.traceException(e);
 
            LocalizableMessage message = WARN_LDAP_CLIENT_CANNOT_ENQUEUE.get(getExceptionMessage(e));
            throw new DirectoryException(DirectoryServer.getServerErrorResultCode(), message, e);
        }
    }
 
    /**
     * Removes the provided operation from the set of operations in progress for this client connection. Note that this
     * does not make any attempt to cancel any processing that may already be in progress for the operation.
     *
     * @param messageID
     *            The message ID of the operation to remove from the set of operations in progress.
     * @return <CODE>true</CODE> if the operation was found and removed from the set of operations in progress, or
     *         <CODE>false</CODE> if not.
     */
    @Override
    public boolean removeOperationInProgress(int messageID) {
        Operation operation = operationsInProgress.remove(messageID);
        if (operation == null) {
            return false;
        }
 
        if (operation.getOperationType() == OperationType.ABANDON && keepStats
                && operation.getResultCode() == ResultCode.CANCELLED) {
            statTracker.updateAbandonedOperation();
        }
 
        lastCompletionTime.set(TimeThread.getTime());
        return true;
    }
 
    /**
     * Attempts to cancel the specified operation.
     *
     * @param messageID
     *            The message ID of the operation to cancel.
     * @param cancelRequest
     *            An object providing additional information about how the cancel should be processed.
     * @return A cancel result that either indicates that the cancel was successful or provides a reason that it was
     *         not.
     */
    @Override
    public CancelResult cancelOperation(int messageID, CancelRequest cancelRequest) {
        Operation op = operationsInProgress.get(messageID);
        if (op != null) {
            return op.cancel(cancelRequest);
        }
 
        // See if the operation is in the list of persistent searches.
        for (PersistentSearch ps : getPersistentSearches()) {
            if (ps.getMessageID() == messageID) {
                // We only need to find the first persistent search
                // associated with the provided message ID. The persistent search
                // will ensure that all other related persistent searches are cancelled.
                return ps.cancel();
            }
        }
        return new CancelResult(ResultCode.NO_SUCH_OPERATION, null);
    }
 
    /**
     * Attempts to cancel all operations in progress on this connection.
     *
     * @param cancelRequest
     *            An object providing additional information about how the cancel should be processed.
     */
    @Override
    public void cancelAllOperations(CancelRequest cancelRequest) {
        // Make sure that no one can add any new operations.
        synchronized (opsInProgressLock) {
            try {
                for (Operation o : operationsInProgress.values()) {
                    try {
                        o.abort(cancelRequest);
 
                        // TODO: Assume its cancelled?
                        if (keepStats) {
                            statTracker.updateAbandonedOperation();
                        }
                    } catch (Exception e) {
                        logger.traceException(e);
                    }
                }
 
                if (!operationsInProgress.isEmpty() || !getPersistentSearches().isEmpty()) {
                    lastCompletionTime.set(TimeThread.getTime());
                }
 
                operationsInProgress.clear();
 
                for (PersistentSearch persistentSearch : getPersistentSearches()) {
                    persistentSearch.cancel();
                }
            } catch (Exception e) {
                logger.traceException(e);
            }
        }
    }
 
    /**
     * Attempts to cancel all operations in progress on this connection except the operation with the specified message
     * ID.
     *
     * @param cancelRequest
     *            An object providing additional information about how the cancel should be processed.
     * @param messageID
     *            The message ID of the operation that should not be canceled.
     */
    @Override
    public void cancelAllOperationsExcept(CancelRequest cancelRequest, int messageID) {
        // Make sure that no one can add any new operations.
        synchronized (opsInProgressLock) {
            try {
                for (int msgID : operationsInProgress.keySet()) {
                    if (msgID == messageID) {
                        continue;
                    }
 
                    Operation o = operationsInProgress.get(msgID);
                    if (o != null) {
                        try {
                            o.abort(cancelRequest);
 
                            // TODO: Assume its cancelled?
                            if (keepStats) {
                                statTracker.updateAbandonedOperation();
                            }
                        } catch (Exception e) {
                            logger.traceException(e);
                        }
                    }
 
                    operationsInProgress.remove(msgID);
                    lastCompletionTime.set(TimeThread.getTime());
                }
 
                for (PersistentSearch persistentSearch : getPersistentSearches()) {
                    if (persistentSearch.getMessageID() == messageID) {
                        continue;
                    }
 
                    persistentSearch.cancel();
                    lastCompletionTime.set(TimeThread.getTime());
                }
            } catch (Exception e) {
                logger.traceException(e);
            }
        }
    }
 
    @Override
    public Selector getWriteSelector() {
        throw new UnsupportedOperationException();
    }
 
    @Override
    public long getMaxBlockedWriteTimeLimit() {
        return connectionHandler.getMaxBlockedWriteTimeLimit();
    }
 
    /**
     * Returns the total number of operations initiated on this connection.
     *
     * @return the total number of operations on this connection
     */
    @Override
    public long getNumberOfOperations() {
        return operationsPerformed.get();
    }
 
    /**
     * Processes the provided LDAP message read from the client and takes whatever action is appropriate. For most
     * requests, this will include placing the operation in the work queue. Certain requests (in particular, abandons
     * and unbinds) will be processed directly.
     *
     * @param queueingStrategy
     *            The {@link QueueingStrategy} to use for operation
     * @param message
     *            The LDAP message to process.
     * @return <CODE>true</CODE> if the appropriate action was taken for the request, or <CODE>false</CODE> if there was
     *         a fatal error and the client has been disconnected as a result, or if the client unbound from the server.
     */
    @Override
    public Single<Stream<Response>> handle(final QueueingStrategy queueingStrategy, final LdapRawMessage message) {
        return singleFrom(streamFromPublisher(Flowable.create(new FlowableOnSubscribe<Response>() {
            @Override
            public void subscribe(FlowableEmitter<Response> emitter) throws Exception {
                processLDAPMessage(queueingStrategy, LDAPReader.readMessage(message.getContent()), emitter);
            }
        }, BackpressureMode.NONE).onBackpressureBuffer(64, null, BackpressureOverflowStrategy.ERROR)));
    }
 
    private boolean processLDAPMessage(final QueueingStrategy queueingStrategy, final LDAPMessage message,
            final FlowableEmitter<Response> out) {
        if (keepStats) {
            statTracker.updateMessageRead(message);
        }
        operationsPerformed.getAndIncrement();
 
        List<Control> opControls = message.getControls();
 
        // FIXME -- See if there is a bind in progress. If so, then deny
        // most kinds of operations.
 
        // Figure out what type of operation we're dealing with based on the
        // LDAP message. Abandon and unbind requests will be processed here.
        // All other types of requests will be encapsulated into operations
        // and append into the work queue to be picked up by a worker
        // thread. Any other kinds of LDAP messages (e.g., response
        // messages) are illegal and will result in the connection being
        // terminated.
        try {
            if (bindInProgress.get()) {
                throw new DirectoryException(ResultCode.CONSTRAINT_VIOLATION, ERR_ENQUEUE_BIND_IN_PROGRESS.get());
            } else if (startTLSInProgress.get()) {
                throw new DirectoryException(ResultCode.CONSTRAINT_VIOLATION, ERR_ENQUEUE_STARTTLS_IN_PROGRESS.get());
            } else if (saslBindInProgress.get() && message.getProtocolOpType() != OP_TYPE_BIND_REQUEST) {
                throw new DirectoryException(ResultCode.CONSTRAINT_VIOLATION, ERR_ENQUEUE_SASLBIND_IN_PROGRESS.get());
            }
 
            boolean result;
            switch (message.getProtocolOpType()) {
            case OP_TYPE_ABANDON_REQUEST:
                return processAbandonRequest(queueingStrategy, message, opControls, out);
            case OP_TYPE_ADD_REQUEST:
                return processAddRequest(queueingStrategy, message, opControls, out);
            case OP_TYPE_BIND_REQUEST:
                boolean isSaslBind =
                    message.getBindRequestProtocolOp().getAuthenticationType() == AuthenticationType.SASL;
                bindInProgress.set(true);
                if (isSaslBind) {
                    saslBindInProgress.set(true);
                }
                result = processBindRequest(queueingStrategy, message, opControls, out);
                if (!result) {
                    bindInProgress.set(false);
                    if (isSaslBind) {
                        saslBindInProgress.set(false);
                    }
                }
                return result;
            case OP_TYPE_COMPARE_REQUEST:
                return processCompareRequest(queueingStrategy, message, opControls, out);
            case OP_TYPE_DELETE_REQUEST:
                return processDeleteRequest(queueingStrategy, message, opControls, out);
            case OP_TYPE_EXTENDED_REQUEST:
                boolean isStartTlsRequest = OID_START_TLS_REQUEST.equals(message.getExtendedRequestProtocolOp()
                        .getOID());
                if (isStartTlsRequest) {
                    startTLSInProgress.set(true);
                }
                result = processExtendedRequest(queueingStrategy, message, opControls, out);
                if (!result && isStartTlsRequest) {
                    startTLSInProgress.set(false);
                }
                return result;
            case OP_TYPE_MODIFY_REQUEST:
                return processModifyRequest(queueingStrategy, message, opControls, out);
            case OP_TYPE_MODIFY_DN_REQUEST:
                return processModifyDNRequest(queueingStrategy, message, opControls, out);
            case OP_TYPE_SEARCH_REQUEST:
                return processSearchRequest(queueingStrategy, message, opControls, out);
            case OP_TYPE_UNBIND_REQUEST:
                return processUnbindRequest(message, opControls);
            default:
                LocalizableMessage msg = ERR_LDAP_DISCONNECT_DUE_TO_INVALID_REQUEST_TYPE.get(
                        message.getProtocolOpName(), message.getMessageID());
                disconnect(DisconnectReason.PROTOCOL_ERROR, true, msg);
                return false;
            }
        } catch (Exception e) {
            logger.traceException(e);
 
            LocalizableMessage msg = ERR_LDAP_DISCONNECT_DUE_TO_PROCESSING_FAILURE.get(message.getProtocolOpName(),
                    message.getMessageID(), e);
            disconnect(DisconnectReason.SERVER_ERROR, true, msg);
            return false;
        }
    }
 
    /**
     * Processes the provided LDAP message as an abandon request.
     *
     * @param queueingStrategy
     *            The {@link QueueingStrategy} to use for operation
     * @param message
     *            The LDAP message containing the abandon request to process.
     * @param controls
     *            The set of pre-decoded request controls contained in the message.
     * @return <CODE>true</CODE> if the request was processed successfully, or <CODE>false</CODE> if not and the
     *         connection has been closed as a result (it is the responsibility of this method to close the connection).
     */
    private boolean processAbandonRequest(final QueueingStrategy queueingStrategy, final LDAPMessage message,
            final List<Control> controls, final FlowableEmitter<Response> out) {
        if (ldapVersion == 2 && !controls.isEmpty()) {
            disconnectControlsNotAllowed();
            return false;
        }
 
        // Create the abandon operation and add it into the work queue.
        AbandonRequestProtocolOp protocolOp = message.getAbandonRequestProtocolOp();
        AbandonOperationBasis abandonOp = new AbandonOperationBasis(this, nextOperationID.getAndIncrement(),
                message.getMessageID(), controls, protocolOp.getIDToAbandon());
        abandonOp.setAttachment(REACTIVE_OUT, out);
 
        try {
            addOperationInProgress(queueingStrategy, abandonOp);
        } catch (DirectoryException de) {
            logger.traceException(de);
 
            // Don't send an error response since abandon operations
            // don't have a response.
        }
 
        return connectionValid;
    }
 
    /**
     * Processes the provided LDAP message as an add request.
     *
     * @param queueingStrategy
     *            The {@link QueueingStrategy} to use for operation
     * @param message
     *            The LDAP message containing the add request to process.
     * @param controls
     *            The set of pre-decoded request controls contained in the message.
     * @return <CODE>true</CODE> if the request was processed successfully, or <CODE>false</CODE> if not and the
     *         connection has been closed as a result (it is the responsibility of this method to close the connection).
     */
    private boolean processAddRequest(final QueueingStrategy queueingStrategy, final LDAPMessage message,
            final List<Control> controls, final FlowableEmitter<Response> out) {
        if (ldapVersion == 2 && !controls.isEmpty()) {
            // LDAPv2 clients aren't allowed to send controls.
            out.onNext(Responses.newResult(ResultCode.PROTOCOL_ERROR).setDiagnosticMessage(
                    ERR_LDAPV2_CLIENTS_NOT_ALLOWED.get().toString()));
            out.onComplete();
            disconnectControlsNotAllowed();
            return false;
        }
 
        // Create the add operation and add it into the work queue.
        AddRequestProtocolOp protocolOp = message.getAddRequestProtocolOp();
        AddOperationBasis addOp = new AddOperationBasis(this, nextOperationID.getAndIncrement(),
                message.getMessageID(), controls, protocolOp.getDN(), protocolOp.getAttributes());
        addOp.setAttachment(REACTIVE_OUT, out);
 
        try {
            addOperationInProgress(queueingStrategy, addOp);
        } catch (DirectoryException de) {
            logger.traceException(de);
 
            final Result result = Responses.newResult(de.getResultCode())
                    .setDiagnosticMessage(de.getLocalizedMessage()).setMatchedDN(de.getMatchedDN().toString());
            for (String referral : de.getReferralURLs()) {
                result.addReferralURI(referral);
            }
 
            out.onNext(result);
            out.onComplete();
        }
 
        return connectionValid;
    }
 
    private void disconnectControlsNotAllowed() {
        disconnect(DisconnectReason.PROTOCOL_ERROR, false, ERR_LDAPV2_CONTROLS_NOT_ALLOWED.get());
    }
 
    /**
     * Processes the provided LDAP message as a bind request.
     *
     * @param queueingStrategy
     *            The {@link QueueingStrategy} to use for operation
     * @param message
     *            The LDAP message containing the bind request to process.
     * @param controls
     *            The set of pre-decoded request controls contained in the message.
     * @return <CODE>true</CODE> if the request was processed successfully, or <CODE>false</CODE> if not and the
     *         connection has been closed as a result (it is the responsibility of this method to close the connection).
     */
    private boolean processBindRequest(final QueueingStrategy queueingStrategy, final LDAPMessage message,
            final List<Control> controls, final FlowableEmitter<Response> out) {
        BindRequestProtocolOp protocolOp = message.getBindRequestProtocolOp();
 
        // See if this is an LDAPv2 bind request, and if so whether that
        // should be allowed.
        String versionString;
        switch (ldapVersion = protocolOp.getProtocolVersion()) {
        case 2:
            versionString = "2";
 
            if (!connectionHandler.allowLDAPv2()) {
                out.onNext(Responses.newBindResult(ResultCode.PROTOCOL_ERROR).setDiagnosticMessage(
                        ERR_LDAPV2_CLIENTS_NOT_ALLOWED.get().toString()));
                out.onComplete();
                disconnect(DisconnectReason.PROTOCOL_ERROR, false, ERR_LDAPV2_CLIENTS_NOT_ALLOWED.get());
                return false;
            }
 
            if (!controls.isEmpty()) {
                // LDAPv2 clients aren't allowed to send controls.
                out.onNext(Responses.newBindResult(ResultCode.PROTOCOL_ERROR).setDiagnosticMessage(
                        ERR_LDAPV2_CONTROLS_NOT_ALLOWED.get().toString()));
                out.onComplete();
                disconnectControlsNotAllowed();
                return false;
            }
 
            break;
        case 3:
            versionString = "3";
            break;
        default:
            // Unsupported protocol version. RFC4511 states that we MUST send
            // a protocol error back to the client.
            out.onNext(Responses.newBindResult(ResultCode.PROTOCOL_ERROR).setDiagnosticMessage(
                    ERR_LDAP_UNSUPPORTED_PROTOCOL_VERSION.get(ldapVersion).toString()));
            out.onComplete();
            disconnect(DisconnectReason.PROTOCOL_ERROR, false, ERR_LDAP_UNSUPPORTED_PROTOCOL_VERSION.get(ldapVersion));
            return false;
        }
 
        ByteString bindDN = protocolOp.getDN();
 
        BindOperationBasis bindOp;
        switch (protocolOp.getAuthenticationType()) {
        case SIMPLE:
            bindOp = new BindOperationBasis(this, nextOperationID.getAndIncrement(), message.getMessageID(), controls,
                    versionString, bindDN, protocolOp.getSimplePassword());
            break;
        case SASL:
            bindOp = new BindOperationBasis(this, nextOperationID.getAndIncrement(), message.getMessageID(), controls,
                    versionString, bindDN, protocolOp.getSASLMechanism(), protocolOp.getSASLCredentials());
            break;
        default:
            // This is an invalid authentication type, and therefore a
            // protocol error. As per RFC 2251, a protocol error in a bind
            // request must result in terminating the connection.
            LocalizableMessage msg = ERR_LDAP_INVALID_BIND_AUTH_TYPE.get(message.getMessageID(),
                    protocolOp.getAuthenticationType());
            disconnect(DisconnectReason.PROTOCOL_ERROR, true, msg);
            return false;
        }
 
        // Add the operation into the work queue.
        bindOp.setAttachment(REACTIVE_OUT, out);
        try {
            addOperationInProgress(queueingStrategy, bindOp);
        } catch (DirectoryException de) {
            logger.traceException(de);
 
            final Result result = Responses.newBindResult(de.getResultCode())
                    .setDiagnosticMessage(de.getLocalizedMessage()).setMatchedDN(de.getMatchedDN().toString());
            for (String referral : de.getReferralURLs()) {
                result.addReferralURI(referral);
            }
 
            out.onNext(result);
            out.onComplete();
 
            // If it was a protocol error, then terminate the connection.
            if (de.getResultCode() == ResultCode.PROTOCOL_ERROR) {
                LocalizableMessage msg = ERR_LDAP_DISCONNECT_DUE_TO_BIND_PROTOCOL_ERROR.get(message.getMessageID(),
                        de.getMessageObject());
                disconnect(DisconnectReason.PROTOCOL_ERROR, true, msg);
            }
        }
 
        return connectionValid;
    }
 
    /**
     * Processes the provided LDAP message as a compare request.
     *
     * @param queueingStrategy
     *            The {@link QueueingStrategy} to use for operation
     * @param message
     *            The LDAP message containing the compare request to process.
     * @param controls
     *            The set of pre-decoded request controls contained in the message.
     * @return <CODE>true</CODE> if the request was processed successfully, or <CODE>false</CODE> if not and the
     *         connection has been closed as a result (it is the responsibility of this method to close the connection).
     */
    private boolean processCompareRequest(final QueueingStrategy queueingStrategy, final LDAPMessage message,
            final List<Control> controls, final FlowableEmitter<Response> out) {
        if (ldapVersion == 2 && !controls.isEmpty()) {
            // LDAPv2 clients aren't allowed to send controls.
            out.onNext(Responses.newResult(ResultCode.PROTOCOL_ERROR).setDiagnosticMessage(
                    ERR_LDAPV2_CONTROLS_NOT_ALLOWED.get().toString()));
            out.onComplete();
            disconnectControlsNotAllowed();
            return false;
        }
 
        CompareRequestProtocolOp protocolOp = message.getCompareRequestProtocolOp();
        CompareOperationBasis compareOp = new CompareOperationBasis(this, nextOperationID.getAndIncrement(),
                message.getMessageID(), controls, protocolOp.getDN(), protocolOp.getAttributeType(),
                protocolOp.getAssertionValue());
 
        // Add the operation into the work queue.
        compareOp.setAttachment(REACTIVE_OUT, out);
        try {
            addOperationInProgress(queueingStrategy, compareOp);
        } catch (DirectoryException de) {
            logger.traceException(de);
 
            final CompareResult result = Responses.newCompareResult(de.getResultCode())
                    .setDiagnosticMessage(de.getLocalizedMessage()).setMatchedDN(de.getMatchedDN().toString());
            result.getReferralURIs().addAll(de.getReferralURLs());
            out.onNext(result);
            out.onComplete();
        }
 
        return connectionValid;
    }
 
    /**
     * Processes the provided LDAP message as a delete request.
     *
     * @param queueingStrategy
     *            The {@link QueueingStrategy} to use for operation
     * @param message
     *            The LDAP message containing the delete request to process.
     * @param controls
     *            The set of pre-decoded request controls contained in the message.
     * @return <CODE>true</CODE> if the request was processed successfully, or <CODE>false</CODE> if not and the
     *         connection has been closed as a result (it is the responsibility of this method to close the connection).
     */
    private boolean processDeleteRequest(final QueueingStrategy queueingStrategy, final LDAPMessage message,
            final List<Control> controls, final FlowableEmitter<Response> out) {
        if (ldapVersion == 2 && !controls.isEmpty()) {
            // LDAPv2 clients aren't allowed to send controls.
            out.onNext(Responses.newResult(ResultCode.PROTOCOL_ERROR).setDiagnosticMessage(
                    ERR_LDAPV2_CONTROLS_NOT_ALLOWED.get().toString()));
            out.onComplete();
            disconnectControlsNotAllowed();
            return false;
        }
 
        DeleteRequestProtocolOp protocolOp = message.getDeleteRequestProtocolOp();
        DeleteOperationBasis deleteOp = new DeleteOperationBasis(this, nextOperationID.getAndIncrement(),
                message.getMessageID(), controls, protocolOp.getDN());
 
        // Add the operation into the work queue.
        deleteOp.setAttachment(REACTIVE_OUT, out);
        try {
            addOperationInProgress(queueingStrategy, deleteOp);
        } catch (DirectoryException de) {
            logger.traceException(de);
 
            final Result result = Responses.newResult(de.getResultCode())
                    .setDiagnosticMessage(de.getLocalizedMessage()).setMatchedDN(de.getMatchedDN().toString());
            result.getReferralURIs().addAll(de.getReferralURLs());
 
            out.onNext(result);
            out.onComplete();
        }
 
        return connectionValid;
    }
 
    /**
     * Processes the provided LDAP message as an extended request.
     *
     * @param queueingStrategy
     *            The {@link QueueingStrategy} to use for operation
     * @param message
     *            The LDAP message containing the extended request to process.
     * @param controls
     *            The set of pre-decoded request controls contained in the message.
     * @return <CODE>true</CODE> if the request was processed successfully, or <CODE>false</CODE> if not and the
     *         connection has been closed as a result (it is the responsibility of this method to close the connection).
     */
    private boolean processExtendedRequest(final QueueingStrategy queueingStrategy, final LDAPMessage message,
            final List<Control> controls, final FlowableEmitter<Response> out) {
        // See if this is an LDAPv2 client. If it is, then they should not
        // be issuing extended requests. We can't send a response that we
        // can be sure they can understand, so we have no choice but to
        // close the connection.
        if (ldapVersion == 2) {
            // LDAPv2 clients aren't allowed to send controls.
            LocalizableMessage msg = ERR_LDAPV2_EXTENDED_REQUEST_NOT_ALLOWED.get(getConnectionID(),
                    message.getMessageID());
 
            out.onNext(Responses.newResult(ResultCode.PROTOCOL_ERROR).setDiagnosticMessage(msg.toString()));
            out.onComplete();
 
            logger.error(msg);
            disconnect(DisconnectReason.PROTOCOL_ERROR, false, msg);
            return false;
        }
 
        // FIXME -- Do we need to handle certain types of request here?
        // -- StartTLS requests
        // -- Cancel requests
 
        ExtendedRequestProtocolOp protocolOp = message.getExtendedRequestProtocolOp();
        ExtendedOperationBasis extendedOp = new ExtendedOperationBasis(this, nextOperationID.getAndIncrement(),
                message.getMessageID(), controls, protocolOp.getOID(), protocolOp.getValue());
 
        // Add the operation into the work queue.
        extendedOp.setAttachment(REACTIVE_OUT, out);
        try {
            addOperationInProgress(queueingStrategy, extendedOp);
        } catch (DirectoryException de) {
            logger.traceException(de);
            final Result result = Responses.newResult(de.getResultCode()).setDiagnosticMessage(de.getMessage())
                    .setMatchedDN(de.getMatchedDN().toString());
            result.getReferralURIs().addAll(de.getReferralURLs());
 
            out.onNext(result);
            out.onComplete();
        }
 
        return connectionValid;
    }
 
    /**
     * Processes the provided LDAP message as a modify request.
     *
     * @param queueingStrategy
     *            The {@link QueueingStrategy} to use for operation
     * @param message
     *            The LDAP message containing the modify request to process.
     * @param controls
     *            The set of pre-decoded request controls contained in the message.
     * @return <CODE>true</CODE> if the request was processed successfully, or <CODE>false</CODE> if not and the
     *         connection has been closed as a result (it is the responsibility of this method to close the connection).
     */
    private boolean processModifyRequest(final QueueingStrategy queueingStrategy, final LDAPMessage message,
            final List<Control> controls, final FlowableEmitter<Response> out) {
        if (ldapVersion == 2 && !controls.isEmpty()) {
            // LDAPv2 clients aren't allowed to send controls.
            out.onNext(Responses.newResult(ResultCode.PROTOCOL_ERROR).setDiagnosticMessage(
                    ERR_LDAPV2_CONTROLS_NOT_ALLOWED.get().toString()));
            out.onComplete();
            disconnectControlsNotAllowed();
            return false;
        }
 
        ModifyRequestProtocolOp protocolOp = message.getModifyRequestProtocolOp();
        ModifyOperationBasis modifyOp = new ModifyOperationBasis(this, nextOperationID.getAndIncrement(),
                message.getMessageID(), controls, protocolOp.getDN(), protocolOp.getModifications());
 
        // Add the operation into the work queue.
        modifyOp.setAttachment(REACTIVE_OUT, out);
        try {
            addOperationInProgress(queueingStrategy, modifyOp);
        } catch (DirectoryException de) {
            logger.traceException(de);
            final Result result = Responses.newResult(de.getResultCode()).setDiagnosticMessage(de.getMessage())
                    .setMatchedDN(de.getMatchedDN().toString());
            result.getReferralURIs().addAll(de.getReferralURLs());
 
            out.onNext(result);
            out.onComplete();
        }
 
        return connectionValid;
    }
 
    /**
     * Processes the provided LDAP message as a modify DN request.
     *
     * @param queueingStrategy
     *            The {@link QueueingStrategy} to use for operation
     * @param message
     *            The LDAP message containing the modify DN request to process.
     * @param controls
     *            The set of pre-decoded request controls contained in the message.
     * @return <CODE>true</CODE> if the request was processed successfully, or <CODE>false</CODE> if not and the
     *         connection has been closed as a result (it is the responsibility of this method to close the connection).
     */
    private boolean processModifyDNRequest(final QueueingStrategy queueingStrategy, final LDAPMessage message,
            final List<Control> controls, final FlowableEmitter<Response> out) {
        if (ldapVersion == 2 && !controls.isEmpty()) {
            // LDAPv2 clients aren't allowed to send controls.
            out.onNext(Responses.newResult(ResultCode.PROTOCOL_ERROR).setDiagnosticMessage(
                    ERR_LDAPV2_CONTROLS_NOT_ALLOWED.get().toString()));
            out.onComplete();
            disconnectControlsNotAllowed();
            return false;
        }
 
        ModifyDNRequestProtocolOp protocolOp = message.getModifyDNRequestProtocolOp();
        ModifyDNOperationBasis modifyDNOp = new ModifyDNOperationBasis(this, nextOperationID.getAndIncrement(),
                message.getMessageID(), controls, protocolOp.getEntryDN(), protocolOp.getNewRDN(),
                protocolOp.deleteOldRDN(), protocolOp.getNewSuperior());
 
        // Add the operation into the work queue.
        modifyDNOp.setAttachment(REACTIVE_OUT, out);
        try {
            addOperationInProgress(queueingStrategy, modifyDNOp);
        } catch (DirectoryException de) {
            logger.traceException(de);
 
            final Result result = Responses.newResult(de.getResultCode()).setDiagnosticMessage(de.getMessage())
                    .setMatchedDN(de.getMatchedDN().toString());
            result.getReferralURIs().addAll(de.getReferralURLs());
            for (Control control : modifyDNOp.getResponseControls()) {
                result.addControl(Converters.from(control));
            }
            out.onNext(result);
            out.onComplete();
        }
 
        return connectionValid;
    }
 
    /**
     * Processes the provided LDAP message as a search request.
     *
     * @param queueingStrategy
     *            The {@link QueueingStrategy} to use for operation
     * @param message
     *            The LDAP message containing the search request to process.
     * @param controls
     *            The set of pre-decoded request controls contained in the message.
     * @return <CODE>true</CODE> if the request was processed successfully, or <CODE>false</CODE> if not and the
     *         connection has been closed as a result (it is the responsibility of this method to close the connection).
     */
    private boolean processSearchRequest(final QueueingStrategy queueingStrategy, final LDAPMessage message,
            final List<Control> controls, final FlowableEmitter<Response> out) {
        if (ldapVersion == 2 && !controls.isEmpty()) {
            // LDAPv2 clients aren't allowed to send controls.
            out.onNext(Responses.newResult(ResultCode.PROTOCOL_ERROR).setDiagnosticMessage(
                    ERR_LDAPV2_CONTROLS_NOT_ALLOWED.get().toString()));
            out.onComplete();
            disconnectControlsNotAllowed();
            return false;
        }
 
        SearchRequestProtocolOp protocolOp = message.getSearchRequestProtocolOp();
        SearchOperationBasis searchOp = new SearchOperationBasis(this, nextOperationID.getAndIncrement(),
                message.getMessageID(), controls, protocolOp.getBaseDN(), protocolOp.getScope(),
                protocolOp.getDereferencePolicy(), protocolOp.getSizeLimit(), protocolOp.getTimeLimit(),
                protocolOp.getTypesOnly(), protocolOp.getFilter(), protocolOp.getAttributes());
 
        // Add the operation into the work queue.
        searchOp.setAttachment(REACTIVE_OUT, out);
        try {
            addOperationInProgress(queueingStrategy, searchOp);
        } catch (DirectoryException de) {
            logger.traceException(de);
 
            final Result result = Responses.newResult(de.getResultCode());
            if (de.getMessage() != null) {
                result.setDiagnosticMessage(de.getMessage());
            }
            if (de.getMatchedDN() != null) {
                result.setMatchedDN(de.getMatchedDN().toString());
            }
            if (de.getReferralURLs() != null) {
                result.getReferralURIs().addAll(de.getReferralURLs());
            }
            if (searchOp.getResponseControls() != null) {
                for (Control control : searchOp.getResponseControls()) {
                    result.addControl(Converters.from(control));
                }
            }
            out.onNext(result);
            out.onComplete();
        }
 
        return connectionValid;
    }
 
    /**
     * Processes the provided LDAP message as an unbind request.
     *
     * @param message
     *            The LDAP message containing the unbind request to process.
     * @param controls
     *            The set of pre-decoded request controls contained in the message.
     * @return <CODE>true</CODE> if the request was processed successfully, or <CODE>false</CODE> if not and the
     *         connection has been closed as a result (it is the responsibility of this method to close the connection).
     */
    private boolean processUnbindRequest(final LDAPMessage message, final List<Control> controls) {
        UnbindOperationBasis unbindOp = new UnbindOperationBasis(this, nextOperationID.getAndIncrement(),
                message.getMessageID(), controls);
 
        unbindOp.run();
 
        // The client connection will never be valid after an unbind.
        return false;
    }
 
    @Override
    public String getMonitorSummary() {
        StringBuilder buffer = new StringBuilder();
        buffer.append("connID=\"");
        buffer.append(connectionID);
        buffer.append("\" connectTime=\"");
        buffer.append(getConnectTimeString());
        buffer.append("\" source=\"");
        buffer.append(clientAddress);
        buffer.append(":");
        buffer.append(clientPort);
        buffer.append("\" destination=\"");
        buffer.append(serverAddress);
        buffer.append(":");
        buffer.append(connectionHandler.getListeners().iterator().next().getPort());
        buffer.append("\" ldapVersion=\"");
        buffer.append(ldapVersion);
        buffer.append("\" authDN=\"");
 
        DN authDN = getAuthenticationInfo().getAuthenticationDN();
        if (authDN != null) {
            buffer.append(authDN);
        }
 
        buffer.append("\" security=\"");
        buffer.append("none");
 
        buffer.append("\" opsInProgress=\"");
        buffer.append(operationsInProgress.size());
        buffer.append("\"");
 
        int countPSearch = getPersistentSearches().size();
        if (countPSearch > 0) {
            buffer.append(" persistentSearches=\"");
            buffer.append(countPSearch);
            buffer.append("\"");
        }
        return buffer.toString();
    }
 
    /**
     * Appends a string representation of this client connection to the provided buffer.
     *
     * @param buffer
     *            The buffer to which the information should be appended.
     */
    @Override
    public void toString(StringBuilder buffer) {
        buffer.append("LDAP client connection from ");
        buffer.append(clientAddress);
        buffer.append(":");
        buffer.append(clientPort);
        buffer.append(" to ");
        buffer.append(serverAddress);
        buffer.append(":");
        buffer.append(serverPort);
    }
 
    @Override
    public boolean prepareTLS(LocalizableMessageBuilder unavailableReason) {
        throw new UnsupportedOperationException();
    }
 
    /**
     * Retrieves the length of time in milliseconds that this client connection has been idle. <BR>
     * <BR>
     * Note that the default implementation will always return zero. Subclasses associated with connection handlers
     * should override this method if they wish to provided idle time limit functionality.
     *
     * @return The length of time in milliseconds that this client connection has been idle.
     */
    @Override
    public long getIdleTime() {
        if (operationsInProgress.isEmpty() && getPersistentSearches().isEmpty()) {
            return TimeThread.getTime() - lastCompletionTime.get();
        } else {
            // There's at least one operation in progress, so it's not idle.
            return 0L;
        }
    }
 
    /**
     * Return the certificate chain array associated with a connection.
     *
     * @return The array of certificates associated with a connection.
     */
    public Certificate[] getClientCertificateChain() {
        return new Certificate[0];
    }
 
    @Override
    public int getSSF() {
        return 0;
    }
}