001/*
002 * Copyright 2009-2020 Ping Identity Corporation
003 * All Rights Reserved.
004 */
005/*
006 * Copyright 2009-2020 Ping Identity Corporation
007 *
008 * Licensed under the Apache License, Version 2.0 (the "License");
009 * you may not use this file except in compliance with the License.
010 * You may obtain a copy of the License at
011 *
012 *    http://www.apache.org/licenses/LICENSE-2.0
013 *
014 * Unless required by applicable law or agreed to in writing, software
015 * distributed under the License is distributed on an "AS IS" BASIS,
016 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
017 * See the License for the specific language governing permissions and
018 * limitations under the License.
019 */
020/*
021 * Copyright (C) 2009-2020 Ping Identity Corporation
022 *
023 * This program is free software; you can redistribute it and/or modify
024 * it under the terms of the GNU General Public License (GPLv2 only)
025 * or the terms of the GNU Lesser General Public License (LGPLv2.1 only)
026 * as published by the Free Software Foundation.
027 *
028 * This program is distributed in the hope that it will be useful,
029 * but WITHOUT ANY WARRANTY; without even the implied warranty of
030 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
031 * GNU General Public License for more details.
032 *
033 * You should have received a copy of the GNU General Public License
034 * along with this program; if not, see <http://www.gnu.org/licenses>.
035 */
036package com.unboundid.ldap.protocol;
037
038
039
040import java.util.ArrayList;
041import java.util.Collections;
042import java.util.Iterator;
043import java.util.List;
044
045import com.unboundid.asn1.ASN1Buffer;
046import com.unboundid.asn1.ASN1BufferSequence;
047import com.unboundid.asn1.ASN1Element;
048import com.unboundid.asn1.ASN1Enumerated;
049import com.unboundid.asn1.ASN1OctetString;
050import com.unboundid.asn1.ASN1Sequence;
051import com.unboundid.asn1.ASN1StreamReader;
052import com.unboundid.asn1.ASN1StreamReaderSequence;
053import com.unboundid.ldap.sdk.BindResult;
054import com.unboundid.ldap.sdk.Control;
055import com.unboundid.ldap.sdk.LDAPException;
056import com.unboundid.ldap.sdk.LDAPResult;
057import com.unboundid.ldap.sdk.ResultCode;
058import com.unboundid.util.Debug;
059import com.unboundid.util.InternalUseOnly;
060import com.unboundid.util.NotMutable;
061import com.unboundid.util.StaticUtils;
062import com.unboundid.util.ThreadSafety;
063import com.unboundid.util.ThreadSafetyLevel;
064import com.unboundid.util.Validator;
065
066import static com.unboundid.ldap.protocol.ProtocolMessages.*;
067
068
069
070/**
071 * This class provides an implementation of a bind response protocol op.
072 */
073@InternalUseOnly()
074@NotMutable()
075@ThreadSafety(level=ThreadSafetyLevel.COMPLETELY_THREADSAFE)
076public final class BindResponseProtocolOp
077       implements ProtocolOp
078{
079  /**
080   * The BER type for the server SASL credentials element.
081   */
082  public static final byte TYPE_SERVER_SASL_CREDENTIALS = (byte) 0x87;
083
084
085
086  /**
087   * The serial version UID for this serializable class.
088   */
089  private static final long serialVersionUID = -7757619031268544913L;
090
091
092
093  // The server SASL credentials for this bind response.
094  private final ASN1OctetString serverSASLCredentials;
095
096  // The result code for this bind response.
097  private final int resultCode;
098
099  // The referral URLs for this bind response.
100  private final List<String> referralURLs;
101
102  // The diagnostic message for this bind response.
103  private final String diagnosticMessage;
104
105  // The matched DN for this bind response.
106  private final String matchedDN;
107
108
109
110  /**
111   * Creates a new instance of this bind response protocol op with the provided
112   * information.
113   *
114   * @param  resultCode             The result code for this response.
115   * @param  matchedDN              The matched DN for this response, if
116   *                                available.
117   * @param  diagnosticMessage      The diagnostic message for this response, if
118   *                                any.
119   * @param  referralURLs           The list of referral URLs for this response,
120   *                                if any.
121   * @param  serverSASLCredentials  The server SASL credentials for this
122   *                                response, if available.
123   */
124  public BindResponseProtocolOp(final int resultCode, final String matchedDN,
125                                final String diagnosticMessage,
126                                final List<String> referralURLs,
127                                final ASN1OctetString serverSASLCredentials)
128  {
129    this.resultCode            = resultCode;
130    this.matchedDN             = matchedDN;
131    this.diagnosticMessage     = diagnosticMessage;
132
133    if (referralURLs == null)
134    {
135      this.referralURLs = Collections.emptyList();
136    }
137    else
138    {
139      this.referralURLs = Collections.unmodifiableList(referralURLs);
140    }
141
142    if (serverSASLCredentials == null)
143    {
144      this.serverSASLCredentials = null;
145    }
146    else
147    {
148      this.serverSASLCredentials = new ASN1OctetString(
149           TYPE_SERVER_SASL_CREDENTIALS, serverSASLCredentials.getValue());
150    }
151  }
152
153
154
155  /**
156   * Creates a new bind response protocol op from the provided bind result
157   * object.
158   *
159   * @param  result  The LDAP result object to use to create this protocol op.
160   */
161  public BindResponseProtocolOp(final LDAPResult result)
162  {
163    resultCode            = result.getResultCode().intValue();
164    matchedDN             = result.getMatchedDN();
165    diagnosticMessage     = result.getDiagnosticMessage();
166    referralURLs          = StaticUtils.toList(result.getReferralURLs());
167
168    if (result instanceof BindResult)
169    {
170      final BindResult br = (BindResult) result;
171      serverSASLCredentials = br.getServerSASLCredentials();
172    }
173    else
174    {
175      serverSASLCredentials = null;
176    }
177  }
178
179
180
181  /**
182   * Creates a new bind response protocol op read from the provided ASN.1 stream
183   * reader.
184   *
185   * @param  reader  The ASN.1 stream reader from which to read the bind
186   *                 response.
187   *
188   * @throws  LDAPException  If a problem occurs while reading or parsing the
189   *                         bind response.
190   */
191  BindResponseProtocolOp(final ASN1StreamReader reader)
192       throws LDAPException
193  {
194    try
195    {
196      final ASN1StreamReaderSequence opSequence = reader.beginSequence();
197      resultCode = reader.readEnumerated();
198
199      String s = reader.readString();
200      Validator.ensureNotNull(s);
201      if (s.isEmpty())
202      {
203        matchedDN = null;
204      }
205      else
206      {
207        matchedDN = s;
208      }
209
210      s = reader.readString();
211      Validator.ensureNotNull(s);
212      if (s.isEmpty())
213      {
214        diagnosticMessage = null;
215      }
216      else
217      {
218        diagnosticMessage = s;
219      }
220
221      ASN1OctetString creds = null;
222      final ArrayList<String> refs = new ArrayList<>(1);
223      while (opSequence.hasMoreElements())
224      {
225        final byte type = (byte) reader.peek();
226        if (type == GenericResponseProtocolOp.TYPE_REFERRALS)
227        {
228          final ASN1StreamReaderSequence refSequence = reader.beginSequence();
229          while (refSequence.hasMoreElements())
230          {
231            refs.add(reader.readString());
232          }
233        }
234        else if (type == TYPE_SERVER_SASL_CREDENTIALS)
235        {
236          creds = new ASN1OctetString(type, reader.readBytes());
237        }
238        else
239        {
240          throw new LDAPException(ResultCode.DECODING_ERROR,
241               ERR_BIND_RESPONSE_INVALID_ELEMENT.get(StaticUtils.toHex(type)));
242        }
243      }
244
245      referralURLs = Collections.unmodifiableList(refs);
246      serverSASLCredentials = creds;
247    }
248    catch (final LDAPException le)
249    {
250      Debug.debugException(le);
251      throw le;
252    }
253    catch (final Exception e)
254    {
255      Debug.debugException(e);
256      throw new LDAPException(ResultCode.DECODING_ERROR,
257           ERR_BIND_RESPONSE_CANNOT_DECODE.get(
258                StaticUtils.getExceptionMessage(e)),
259           e);
260    }
261  }
262
263
264
265  /**
266   * Retrieves the result code for this bind response.
267   *
268   * @return  The result code for this bind response.
269   */
270  public int getResultCode()
271  {
272    return resultCode;
273  }
274
275
276
277  /**
278   * Retrieves the matched DN for this bind response, if any.
279   *
280   * @return  The matched DN for this bind response, or {@code null} if there is
281   *          no matched DN.
282   */
283  public String getMatchedDN()
284  {
285    return matchedDN;
286  }
287
288
289
290  /**
291   * Retrieves the diagnostic message for this bind response, if any.
292   *
293   * @return  The diagnostic message for this bind response, or {@code null} if
294   *          there is no diagnostic message.
295   */
296  public String getDiagnosticMessage()
297  {
298    return diagnosticMessage;
299  }
300
301
302
303  /**
304   * Retrieves the list of referral URLs for this bind response.
305   *
306   * @return  The list of referral URLs for this bind response, or an empty list
307   *          if there are no referral URLs.
308   */
309  public List<String> getReferralURLs()
310  {
311    return referralURLs;
312  }
313
314
315
316  /**
317   * Retrieves the server SASL credentials for this bind response, if any.
318   *
319   * @return  The server SASL credentials for this bind response, or
320   *          {@code null} if there are no server SASL credentials.
321   */
322  public ASN1OctetString getServerSASLCredentials()
323  {
324    return serverSASLCredentials;
325  }
326
327
328
329  /**
330   * {@inheritDoc}
331   */
332  @Override()
333  public byte getProtocolOpType()
334  {
335    return LDAPMessage.PROTOCOL_OP_TYPE_BIND_RESPONSE;
336  }
337
338
339
340  /**
341   * {@inheritDoc}
342   */
343  @Override()
344  public ASN1Element encodeProtocolOp()
345  {
346    final ArrayList<ASN1Element> elements = new ArrayList<>(5);
347    elements.add(new ASN1Enumerated(getResultCode()));
348
349    final String mDN = getMatchedDN();
350    if (mDN == null)
351    {
352      elements.add(new ASN1OctetString());
353    }
354    else
355    {
356      elements.add(new ASN1OctetString(mDN));
357    }
358
359    final String dm = getDiagnosticMessage();
360    if (dm == null)
361    {
362      elements.add(new ASN1OctetString());
363    }
364    else
365    {
366      elements.add(new ASN1OctetString(dm));
367    }
368
369    final List<String> refs = getReferralURLs();
370    if (! refs.isEmpty())
371    {
372      final ArrayList<ASN1Element> refElements = new ArrayList<>(refs.size());
373      for (final String r : refs)
374      {
375        refElements.add(new ASN1OctetString(r));
376      }
377      elements.add(new ASN1Sequence(GenericResponseProtocolOp.TYPE_REFERRALS,
378           refElements));
379    }
380
381    if (serverSASLCredentials != null)
382    {
383      elements.add(serverSASLCredentials);
384    }
385
386    return new ASN1Sequence(LDAPMessage.PROTOCOL_OP_TYPE_BIND_RESPONSE,
387         elements);
388  }
389
390
391
392  /**
393   * Decodes the provided ASN.1 element as a bind response protocol op.
394   *
395   * @param  element  The ASN.1 element to be decoded.
396   *
397   * @return  The decoded bind response protocol op.
398   *
399   * @throws  LDAPException  If the provided ASN.1 element cannot be decoded as
400   *                         a bind response protocol op.
401   */
402  public static BindResponseProtocolOp decodeProtocolOp(
403                                            final ASN1Element element)
404         throws LDAPException
405  {
406    try
407    {
408      final ASN1Element[] elements =
409           ASN1Sequence.decodeAsSequence(element).elements();
410      final int resultCode =
411           ASN1Enumerated.decodeAsEnumerated(elements[0]).intValue();
412
413      final String matchedDN;
414      final String md =
415           ASN1OctetString.decodeAsOctetString(elements[1]).stringValue();
416      if (! md.isEmpty())
417      {
418        matchedDN = md;
419      }
420      else
421      {
422        matchedDN = null;
423      }
424
425      final String diagnosticMessage;
426      final String dm =
427           ASN1OctetString.decodeAsOctetString(elements[2]).stringValue();
428      if (! dm.isEmpty())
429      {
430        diagnosticMessage = dm;
431      }
432      else
433      {
434        diagnosticMessage = null;
435      }
436
437      ASN1OctetString serverSASLCredentials = null;
438      List<String> referralURLs = null;
439      if (elements.length > 3)
440      {
441        for (int i=3; i < elements.length; i++)
442        {
443          switch (elements[i].getType())
444          {
445            case GenericResponseProtocolOp.TYPE_REFERRALS:
446              final ASN1Element[] refElements =
447                   ASN1Sequence.decodeAsSequence(elements[3]).elements();
448              referralURLs = new ArrayList<>(refElements.length);
449              for (final ASN1Element e : refElements)
450              {
451                referralURLs.add(
452                     ASN1OctetString.decodeAsOctetString(e).stringValue());
453              }
454              break;
455
456            case TYPE_SERVER_SASL_CREDENTIALS:
457              serverSASLCredentials =
458                   ASN1OctetString.decodeAsOctetString(elements[i]);
459              break;
460
461            default:
462              throw new LDAPException(ResultCode.DECODING_ERROR,
463                   ERR_BIND_RESPONSE_INVALID_ELEMENT.get(
464                        StaticUtils.toHex(elements[i].getType())));
465          }
466        }
467      }
468
469      return new BindResponseProtocolOp(resultCode, matchedDN,
470           diagnosticMessage, referralURLs, serverSASLCredentials);
471    }
472    catch (final LDAPException le)
473    {
474      Debug.debugException(le);
475      throw le;
476    }
477    catch (final Exception e)
478    {
479      Debug.debugException(e);
480      throw new LDAPException(ResultCode.DECODING_ERROR,
481           ERR_BIND_RESPONSE_CANNOT_DECODE.get(
482                StaticUtils.getExceptionMessage(e)),
483           e);
484    }
485  }
486
487
488
489  /**
490   * {@inheritDoc}
491   */
492  @Override()
493  public void writeTo(final ASN1Buffer buffer)
494  {
495    final ASN1BufferSequence opSequence =
496         buffer.beginSequence(LDAPMessage.PROTOCOL_OP_TYPE_BIND_RESPONSE);
497    buffer.addEnumerated(resultCode);
498    buffer.addOctetString(matchedDN);
499    buffer.addOctetString(diagnosticMessage);
500
501    if (! referralURLs.isEmpty())
502    {
503      final ASN1BufferSequence refSequence =
504           buffer.beginSequence(GenericResponseProtocolOp.TYPE_REFERRALS);
505      for (final String s : referralURLs)
506      {
507        buffer.addOctetString(s);
508      }
509      refSequence.end();
510    }
511
512    if (serverSASLCredentials != null)
513    {
514      buffer.addElement(serverSASLCredentials);
515    }
516
517    opSequence.end();
518  }
519
520
521
522  /**
523   * Creates a new LDAP result object from this response protocol op.
524   *
525   * @param  controls  The set of controls to include in the LDAP result.  It
526   *                   may be empty or {@code null} if no controls should be
527   *                   included.
528   *
529   * @return  The LDAP result that was created.
530   */
531  public BindResult toBindResult(final Control... controls)
532  {
533    final String[] refs;
534    if (referralURLs.isEmpty())
535    {
536      refs = StaticUtils.NO_STRINGS;
537    }
538    else
539    {
540      refs = new String[referralURLs.size()];
541      referralURLs.toArray(refs);
542    }
543
544    return new BindResult(-1, ResultCode.valueOf(resultCode), diagnosticMessage,
545         matchedDN, refs, controls, serverSASLCredentials);
546  }
547
548
549
550  /**
551   * Retrieves a string representation of this protocol op.
552   *
553   * @return  A string representation of this protocol op.
554   */
555  @Override()
556  public String toString()
557  {
558    final StringBuilder buffer = new StringBuilder();
559    toString(buffer);
560    return buffer.toString();
561  }
562
563
564
565  /**
566   * {@inheritDoc}
567   */
568  @Override()
569  public void toString(final StringBuilder buffer)
570  {
571    buffer.append("BindResponseProtocolOp(resultCode=");
572    buffer.append(resultCode);
573
574    if (matchedDN != null)
575    {
576      buffer.append(", matchedDN='");
577      buffer.append(matchedDN);
578      buffer.append('\'');
579    }
580
581    if (diagnosticMessage != null)
582    {
583      buffer.append(", diagnosticMessage='");
584      buffer.append(diagnosticMessage);
585      buffer.append('\'');
586    }
587
588    if (! referralURLs.isEmpty())
589    {
590      buffer.append(", referralURLs={");
591
592      final Iterator<String> iterator = referralURLs.iterator();
593      while (iterator.hasNext())
594      {
595        buffer.append('\'');
596        buffer.append(iterator.next());
597        buffer.append('\'');
598        if (iterator.hasNext())
599        {
600          buffer.append(',');
601        }
602      }
603
604      buffer.append('}');
605    }
606    buffer.append(')');
607  }
608}