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

Jean-Noel Rouvignac
25.16.2015 f983fc4bc7a4dc0e9d175e77cfaf8a2127aaeb2d
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
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at legal-notices/CDDLv1_0.txt
 * or http://forgerock.org/license/CDDLv1.0.html.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at legal-notices/CDDLv1_0.txt.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information:
 *      Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 *
 *
 *      Copyright 2008-2010 Sun Microsystems, Inc.
 *      Portions Copyright 2013-2014 ForgeRock AS.
 */
package org.opends.admin.ads.util;
 
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
 
import javax.naming.AuthenticationException;
import javax.naming.NamingException;
import javax.naming.NoPermissionException;
import javax.naming.TimeLimitExceededException;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapName;
 
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.i18n.slf4j.LocalizedLogger;
import org.opends.admin.ads.ADSContext;
import org.opends.admin.ads.ADSContext.ServerProperty;
import org.opends.admin.ads.ServerDescriptor;
import org.opends.admin.ads.TopologyCacheException;
import org.opends.admin.ads.TopologyCacheException.Type;
import org.opends.admin.ads.TopologyCacheFilter;
 
import com.forgerock.opendj.cli.Utils;
 
import static org.opends.server.util.StaticUtils.*;
 
/**
 * Class used to load the configuration of a server.  Basically the code
 * uses some provided properties and authentication information to connect
 * to the server and then generate a ServerDescriptor object based on the
 * read configuration.
 */
public class ServerLoader extends Thread
{
  private Map<ServerProperty,Object> serverProperties;
  private boolean isOver;
  private boolean isInterrupted;
  private String lastLdapUrl;
  private TopologyCacheException lastException;
  private ServerDescriptor serverDescriptor;
  private ApplicationTrustManager trustManager;
  private int timeout;
  private String dn;
  private String pwd;
  private final LinkedHashSet<PreferredConnection> preferredLDAPURLs;
  private TopologyCacheFilter filter;
 
  private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
 
  /**
   * Constructor.
   * @param serverProperties the server properties of the server we want to
   * load.
   * @param dn the DN that we must use to bind to the server.
   * @param pwd the password that we must use to bind to the server.
   * @param trustManager the ApplicationTrustManager to be used when we try
   * to connect to the server.
   * @param timeout the timeout to establish the connection in milliseconds.
   * Use {@code 0} to express no timeout.
   * @param preferredLDAPURLs the list of preferred LDAP URLs that we want
   * to use to connect to the server.  They will be used only if they correspond
   * to the URLs that we found in the the server properties.
   * @param filter the topology cache filter to be used.  This can be used not
   * to retrieve all the information.
   */
  public ServerLoader(Map<ServerProperty,Object> serverProperties,
      String dn, String pwd, ApplicationTrustManager trustManager,
      int timeout,
      Set<PreferredConnection> preferredLDAPURLs,
      TopologyCacheFilter filter)
  {
    this.serverProperties = serverProperties;
    this.dn = dn;
    this.pwd = pwd;
    this.trustManager = trustManager;
    this.timeout = timeout;
    this.preferredLDAPURLs =
      new LinkedHashSet<PreferredConnection>(preferredLDAPURLs);
    this.filter = filter;
  }
 
  /**
   * Returns the ServerDescriptor that could be retrieved.
   * @return the ServerDescriptor that could be retrieved.
   */
  public ServerDescriptor getServerDescriptor()
  {
    if (serverDescriptor == null)
    {
      serverDescriptor = ServerDescriptor.createStandalone(serverProperties);
    }
    serverDescriptor.setLastException(lastException);
    return serverDescriptor;
  }
 
  /**
   * Returns the last exception that occurred while trying to generate
   * the ServerDescriptor object.
   * @return the last exception that occurred while trying to generate
   * the ServerDescriptor object.
   */
  public TopologyCacheException getLastException()
  {
    return lastException;
  }
 
  /** {@inheritDoc} */
  @Override
  public void interrupt()
  {
    if (!isOver)
    {
      isInterrupted = true;
      String ldapUrl = getLastLdapUrl();
      if (ldapUrl == null)
      {
        LinkedHashSet<PreferredConnection> urls = getLDAPURLsByPreference();
        if (!urls.isEmpty())
        {
          ldapUrl = urls.iterator().next().getLDAPURL();
        }
      }
      lastException = new TopologyCacheException(
          TopologyCacheException.Type.TIMEOUT,
          new TimeLimitExceededException("Timeout reading server: "+ldapUrl),
          trustManager, ldapUrl);
      logger.warn(LocalizableMessage.raw("Timeout reading server: "+ldapUrl));
    }
    super.interrupt();
  }
 
  /**
   * The method where we try to generate the ServerDescriptor object.
   */
  @Override
  public void run()
  {
    lastException = null;
    InitialLdapContext ctx = null;
    try
    {
      ctx = createContext();
      serverDescriptor = ServerDescriptor.createStandalone(ctx, filter);
      serverDescriptor.setAdsProperties(serverProperties);
      serverDescriptor.updateAdsPropertiesWithServerProperties();
    }
    catch (NoPermissionException npe)
    {
      logger.warn(LocalizableMessage.raw(
          "Permissions error reading server: "+getLastLdapUrl(), npe));
      if (!isAdministratorDn())
      {
        lastException = new TopologyCacheException(
                TopologyCacheException.Type.NOT_GLOBAL_ADMINISTRATOR, npe,
                trustManager, getLastLdapUrl());
      }
      else
      {
        lastException =
          new TopologyCacheException(
              TopologyCacheException.Type.NO_PERMISSIONS, npe,
              trustManager, getLastLdapUrl());
      }
    }
    catch (AuthenticationException ae)
    {
      logger.warn(LocalizableMessage.raw(
          "Authentication exception: "+getLastLdapUrl(), ae));
      if (!isAdministratorDn())
      {
        lastException = new TopologyCacheException(
                TopologyCacheException.Type.NOT_GLOBAL_ADMINISTRATOR, ae,
                trustManager, getLastLdapUrl());
      }
      else
      {
        lastException =
          new TopologyCacheException(
              TopologyCacheException.Type.GENERIC_READING_SERVER, ae,
              trustManager, getLastLdapUrl());
      }
    }
    catch (NamingException ne)
    {
      logger.warn(LocalizableMessage.raw(
          "NamingException error reading server: "+getLastLdapUrl(), ne));
      Type type = ctx == null
          ? TopologyCacheException.Type.GENERIC_CREATING_CONNECTION
          : TopologyCacheException.Type.GENERIC_READING_SERVER;
      lastException = new TopologyCacheException(
          type, ne, trustManager, getLastLdapUrl());
    }
    catch (Throwable t)
    {
      if (!isInterrupted)
      {
        logger.warn(LocalizableMessage.raw(
            "Generic error reading server: "+getLastLdapUrl(), t));
        logger.warn(LocalizableMessage.raw("server Properties: "+serverProperties));
        lastException =
            new TopologyCacheException(TopologyCacheException.Type.BUG, t);
      }
    }
    finally
    {
      isOver = true;
      close(ctx);
    }
  }
 
  /**
   * Create an InitialLdapContext based in the provide server properties and
   * authentication data provided in the constructor.
   * @return an InitialLdapContext based in the provide server properties and
   * authentication data provided in the constructor.
   * @throws NamingException if an error occurred while creating the
   * InitialLdapContext.
   */
  public InitialLdapContext createContext() throws NamingException
  {
    InitialLdapContext ctx = null;
    if (trustManager != null)
    {
      trustManager.resetLastRefusedItems();
 
      String host = (String)serverProperties.get(ServerProperty.HOST_NAME);
      trustManager.setHost(host);
    }
 
    /* Try to connect to the server in a certain order of preference.  If an
     * URL fails, we will try with the others.
     */
    LinkedHashSet<PreferredConnection> conns = getLDAPURLsByPreference();
 
    for (PreferredConnection connection : conns)
    {
      if (ctx == null)
      {
        lastLdapUrl = connection.getLDAPURL();
        switch (connection.getType())
        {
        case LDAPS:
          ctx = ConnectionUtils.createLdapsContext(lastLdapUrl, dn, pwd,
              timeout, null, trustManager,
              null);
          break;
        case START_TLS:
          ctx = ConnectionUtils.createStartTLSContext(lastLdapUrl, dn, pwd,
              timeout, null, trustManager,
              null, null);
          break;
        default:
          ctx = ConnectionUtils.createLdapContext(lastLdapUrl, dn, pwd,
              timeout, null);
        }
      }
    }
    return ctx;
  }
 
  /**
   * Returns the last LDAP URL to which we tried to connect.
   * @return the last LDAP URL to which we tried to connect.
   */
  private String getLastLdapUrl()
  {
    return lastLdapUrl;
  }
 
  /**
   * Returns the non-secure LDAP URL for the given server properties.  It
   * returns NULL if according to the server properties no non-secure LDAP URL
   * can be generated (LDAP disabled or port not defined).
   * @param serverProperties the server properties to be used to generate
   * the non-secure LDAP URL.
   * @return the non-secure LDAP URL for the given server properties.
   */
  private String getLdapUrl(Map<ServerProperty,Object> serverProperties)
  {
    if (isLdapEnabled(serverProperties))
    {
      return "ldap://" + getHostNameForLdapUrl(serverProperties) + ":"
          + serverProperties.get(ServerProperty.LDAP_PORT);
    }
    return null;
  }
 
  /**
   * Returns the StartTLS LDAP URL for the given server properties.  It
   * returns NULL if according to the server properties no StartTLS LDAP URL
   * can be generated (StartTLS disabled or port not defined).
   * @param serverProperties the server properties to be used to generate
   * the StartTLS LDAP URL.
   * @return the StartTLS LDAP URL for the given server properties.
   */
  private String getStartTlsLdapUrl(Map<ServerProperty,Object> serverProperties)
  {
    if (isLdapEnabled(serverProperties) && isStartTlsEnabled(serverProperties))
    {
      return "ldap://" + getHostNameForLdapUrl(serverProperties) + ":"
          + serverProperties.get(ServerProperty.LDAP_PORT);
    }
    return null;
  }
 
  /**
   * Returns the LDAPs URL for the given server properties.  It
   * returns NULL if according to the server properties no LDAPS URL
   * can be generated (LDAPS disabled or port not defined).
   * @param serverProperties the server properties to be used to generate
   * the LDAPS URL.
   * @return the LDAPS URL for the given server properties.
   */
  private String getLdapsUrl(Map<ServerProperty,Object> serverProperties)
  {
    boolean ldapsEnabled = isLdapsEnabled(serverProperties);
    if (ldapsEnabled)
    {
      return "ldaps://" + getHostNameForLdapUrl(serverProperties) + ":"
          + serverProperties.get(ServerProperty.LDAPS_PORT);
    }
    return null;
  }
 
  /**
   * Returns the administration connector URL for the given server properties.
   * It returns NULL if according to the server properties no administration
   * connector URL can be generated.
   * @param serverProperties the server properties to be used to generate
   * the administration connector URL.
   * @return the administration connector URL for the given server properties.
   */
  private String getAdminConnectorUrl(
    Map<ServerProperty,Object> serverProperties)
  {
    boolean portDefined;
    if (isPropertyEnabled(serverProperties, ServerProperty.ADMIN_ENABLED))
    {
      Object v = serverProperties.get(ServerProperty.ADMIN_PORT);
      portDefined = v != null;
    }
    else
    {
      portDefined = false;
    }
 
    if (portDefined)
    {
      return "ldaps://" + getHostNameForLdapUrl(serverProperties) + ":"
          + serverProperties.get(ServerProperty.ADMIN_PORT);
    }
    return null;
  }
 
  private boolean isLdapEnabled(Map<ServerProperty, Object> serverProperties)
  {
    return isPropertyEnabled(serverProperties, ServerProperty.LDAP_ENABLED);
  }
 
  private boolean isLdapsEnabled(Map<ServerProperty, Object> serverProperties)
  {
    return isPropertyEnabled(serverProperties, ServerProperty.LDAPS_ENABLED);
  }
 
  private boolean isStartTlsEnabled(Map<ServerProperty, Object> serverProperties)
  {
    return isPropertyEnabled(serverProperties, ServerProperty.STARTTLS_ENABLED);
  }
 
  private boolean isPropertyEnabled(Map<ServerProperty, Object> serverProperties, ServerProperty property)
  {
    Object v = serverProperties.get(property);
    return v != null && "true".equalsIgnoreCase(v.toString());
  }
 
  /**
   * Returns the host name to be used to generate an LDAP URL based on the
   * contents of the provided server properties.
   * @param serverProperties the server properties.
   * @return the host name to be used to generate an LDAP URL based on the
   * contents of the provided server properties.
   */
  private String getHostNameForLdapUrl(
      Map<ServerProperty,Object> serverProperties)
  {
    String host = (String)serverProperties.get(ServerProperty.HOST_NAME);
    return Utils.getHostNameForLdapUrl(host);
  }
 
  /**
   * Returns whether the DN provided in the constructor is a Global
   * Administrator DN or not.
   * @return <CODE>true</CODE> if the DN provided in the constructor is a Global
   * Administrator DN and <CODE>false</CODE> otherwise.
   */
  private boolean isAdministratorDn()
  {
    try
    {
      LdapName theDn = new LdapName(dn);
      LdapName containerDn =
        new LdapName(ADSContext.getAdministratorContainerDN());
      return theDn.startsWith(containerDn);
    }
    catch (Throwable t)
    {
      logger.warn(LocalizableMessage.raw("Error parsing authentication DNs.", t));
    }
    return false;
  }
 
  /**
   * Returns the list of LDAP URLs that can be used to connect to the server.
   * They are ordered so that the first URL is the preferred URL to be used.
   * @return the list of LDAP URLs that can be used to connect to the server.
   * They are ordered so that the first URL is the preferred URL to be used.
   */
  private LinkedHashSet<PreferredConnection> getLDAPURLsByPreference()
  {
    LinkedHashSet<PreferredConnection> ldapUrls =
      new LinkedHashSet<PreferredConnection>();
 
    String adminConnectorUrl = getAdminConnectorUrl(serverProperties);
    String ldapsUrl = getLdapsUrl(serverProperties);
    String startTLSUrl = getStartTlsLdapUrl(serverProperties);
    String ldapUrl = getLdapUrl(serverProperties);
 
    /**
     * Check the preferred connections passed in the constructor.
     */
    for (PreferredConnection connection : preferredLDAPURLs)
    {
      String url = connection.getLDAPURL();
      if (url.equalsIgnoreCase(adminConnectorUrl))
      {
        ldapUrls.add(connection);
      }
      else if (url.equalsIgnoreCase(ldapsUrl) &&
          connection.getType() == PreferredConnection.Type.LDAPS)
      {
        ldapUrls.add(connection);
      }
      else if (url.equalsIgnoreCase(startTLSUrl) &&
          connection.getType() == PreferredConnection.Type.START_TLS)
      {
        ldapUrls.add(connection);
      }
      else if (url.equalsIgnoreCase(ldapUrl) &&
          connection.getType() == PreferredConnection.Type.LDAP)
      {
        ldapUrls.add(connection);
      }
    }
 
    if (adminConnectorUrl != null)
    {
      ldapUrls.add(
          new PreferredConnection(adminConnectorUrl,
          PreferredConnection.Type.LDAPS));
    }
    if (ldapsUrl != null)
    {
      ldapUrls.add(
          new PreferredConnection(ldapsUrl, PreferredConnection.Type.LDAPS));
    }
    if (startTLSUrl != null)
    {
      ldapUrls.add(new PreferredConnection(startTLSUrl,
              PreferredConnection.Type.START_TLS));
    }
    if (ldapUrl != null)
    {
      ldapUrls.add(new PreferredConnection(ldapUrl,
          PreferredConnection.Type.LDAP));
    }
    return ldapUrls;
  }
}