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

Valera V.Harseko
19.01.2020 8d4a14b55a8f1b68a4a13c6b4920e3c267b130a8
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
/*
 * 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 2014-2016 ForgeRock AS.
 */
package org.opends.server.backends;
 
import static org.opends.messages.ConfigMessages.*;
import static org.opends.server.config.ConfigConstants.ATTR_DEFAULT_ROOT_PRIVILEGE_NAME;
import static org.opends.server.config.ConfigConstants.CONFIG_ARCHIVE_DIR_NAME;
import static org.opends.server.util.StaticUtils.getExceptionMessage;
 
import java.io.File;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
 
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.i18n.slf4j.LocalizedLogger;
import org.forgerock.opendj.adapter.server3x.Converters;
import org.forgerock.opendj.config.server.ConfigException;
import org.forgerock.opendj.config.server.ConfigurationChangeListener;
import org.forgerock.opendj.ldap.ConditionResult;
import org.forgerock.opendj.ldap.DN;
import org.forgerock.opendj.ldap.ResultCode;
import org.forgerock.opendj.ldap.schema.AttributeType;
import org.forgerock.opendj.server.config.meta.LocalBackendCfgDefn.WritabilityMode;
import org.forgerock.opendj.server.config.server.BackendCfg;
import org.forgerock.opendj.server.config.server.LocalBackendCfg;
import org.opends.server.api.Backupable;
import org.opends.server.api.ClientConnection;
import org.opends.server.api.LocalBackend;
import org.opends.server.backends.ConfigurationBackend.ConfigurationBackendCfg;
import org.opends.server.config.ConfigurationHandler;
import org.opends.server.core.AddOperation;
import org.opends.server.core.DeleteOperation;
import org.opends.server.core.ModifyDNOperation;
import org.opends.server.core.ModifyOperation;
import org.opends.server.core.SearchOperation;
import org.opends.server.core.ServerContext;
import org.opends.server.types.BackupConfig;
import org.opends.server.types.BackupDirectory;
import org.opends.server.types.DirectoryException;
import org.opends.server.types.Entry;
import org.opends.server.types.IndexType;
import org.opends.server.types.InitializationException;
import org.opends.server.types.LDIFExportConfig;
import org.opends.server.types.LDIFImportConfig;
import org.opends.server.types.LDIFImportResult;
import org.opends.server.types.Modification;
import org.opends.server.types.Privilege;
import org.opends.server.types.RestoreConfig;
import org.opends.server.util.BackupManager;
import org.opends.server.util.StaticUtils;
 
/** Back-end responsible for management of configuration entries. */
public class ConfigurationBackend extends LocalBackend<ConfigurationBackendCfg> implements Backupable
{
  /**
   * Dummy {@link BackendCfg} implementation for the {@link ConfigurationBackend}. No config is
   * needed for this specific backend, but this class is required to behave like other backends
   * during initialization.
   */
  public final class ConfigurationBackendCfg implements LocalBackendCfg
  {
    private ConfigurationBackendCfg()
    {
      // let nobody instantiate it
    }
 
    @Override
    public DN dn()
    {
      return getBaseDNs().iterator().next();
    }
 
    @Override
    public String name()
    {
      return dn().rdn().getFirstAVA().getAttributeValue().toString();
    }
 
    @Override
    public Class<? extends LocalBackendCfg> configurationClass()
    {
      return this.getClass();
    }
 
    @Override
    public String getBackendId()
    {
      return CONFIG_BACKEND_ID;
    }
 
    @Override
    public SortedSet<DN> getBaseDN()
    {
      return Collections.unmodifiableSortedSet(new TreeSet<DN>(getBaseDNs()));
    }
 
    @Override
    public boolean isEnabled()
    {
      return true;
    }
 
    @Override
    public String getJavaClass()
    {
      return ConfigurationBackend.class.getName();
    }
 
    @Override
    public WritabilityMode getWritabilityMode()
    {
      return WritabilityMode.ENABLED;
    }
 
    @Override
    public void addChangeListener(ConfigurationChangeListener<BackendCfg> arg0)
    {
      // no-op
 
    }
 
    @Override
    public void removeChangeListener(ConfigurationChangeListener<BackendCfg> arg0)
    {
      // no-op
 
    }
 
    @Override
    public void addLocalChangeListener(ConfigurationChangeListener<LocalBackendCfg> arg0)
    {
      // no-op
 
    }
 
    @Override
    public void removeLocalChangeListener(ConfigurationChangeListener<LocalBackendCfg> arg0)
    {
      // no-op
 
    }
  }
 
  /**
   * The backend ID for the configuration backend.
   * <p>
   * Try to avoid potential conflict with user backend identifiers.
   */
  public static final String CONFIG_BACKEND_ID = "__config.ldif__";
 
  private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
 
  /** The set of supported control OIDs for this backend. */
  private static final Set<String> SUPPORTED_CONTROLS = new HashSet<>(0);
  /** The set of supported feature OIDs for this backend. */
  private static final Set<String> SUPPORTED_FEATURES = new HashSet<>(0);
 
  /** The privilege array containing both the CONFIG_READ and CONFIG_WRITE privileges. */
  private static final Privilege[] CONFIG_READ_AND_WRITE =
  {
    Privilege.CONFIG_READ,
    Privilege.CONFIG_WRITE
  };
 
  /** Handles the configuration entries and their storage in files. */
  private final ConfigurationHandler configurationHandler;
 
  /** The reference to the configuration root entry. */
  private final Entry configRootEntry;
 
  /** The set of base DNs for this config handler backend. */
  private Set<DN> baseDNs;
 
  /**
   * The write lock used to ensure that only one thread can apply a
   * configuration update at any given time.
   */
  private final Object configLock = new Object();
 
  /** The server context. */
  private final ServerContext serverContext;
 
  /**
   * Creates and initializes a new instance of this backend.
   *
   * @param serverContext
   *            The server context.
   * @throws InitializationException
   *            If an errors occurs.
   */
  public ConfigurationBackend(ServerContext serverContext)
      throws InitializationException
  {
    this.serverContext = serverContext;
    this.configurationHandler = serverContext.getConfigurationHandler();
    this.configRootEntry = Converters.to(configurationHandler.getRootEntry());
    baseDNs = Collections.singleton(configRootEntry.getName());
 
    setBackendID(CONFIG_BACKEND_ID);
  }
 
  /**
   * Returns a new {@link ConfigurationBackendCfg} for this {@link ConfigurationBackend}.
   *
   * @return a new {@link ConfigurationBackendCfg} for this {@link ConfigurationBackend}
   */
  public ConfigurationBackendCfg getBackendCfg()
  {
    return new ConfigurationBackendCfg();
  }
 
  @Override
  public void closeBackend()
  {
    try
    {
      serverContext.getBackendConfigManager().deregisterBaseDN(configRootEntry.getName());
    }
    catch (Exception e)
    {
      logger.traceException(e, "Error when deregistering base DN: " + configRootEntry.getName());
    }
  }
 
  @Override
  public void configureBackend(ConfigurationBackendCfg cfg, ServerContext serverContext) throws ConfigException
  {
    // No action is required.
  }
 
  @Override
  public void openBackend() throws InitializationException
  {
    DN baseDN = configRootEntry.getName();
    try
    {
      serverContext.getBackendConfigManager().registerBaseDN(baseDN, this, true);
    }
    catch (DirectoryException e)
    {
      logger.traceException(e);
      throw new InitializationException(
          ERR_CONFIG_CANNOT_REGISTER_AS_PRIVATE_SUFFIX.get(baseDN, getExceptionMessage(e)), e);
    }
  }
 
  @Override
  public Set<DN> getBaseDNs()
  {
    return baseDNs;
  }
 
  @Override
  public Entry getEntry(DN entryDN)
  {
    try
    {
      org.forgerock.opendj.ldap.Entry entry = configurationHandler.getEntry(entryDN);
      if (entry != null)
      {
        Entry serverEntry = Converters.to(entry);
        serverEntry.processVirtualAttributes();
        return serverEntry;
      }
    }
    catch (ConfigException e)
    {
      // should never happen
    }
    return null;
  }
 
  @Override
  public long getEntryCount()
  {
    try
    {
      return getNumberOfEntriesInBaseDN(configRootEntry.getName());
    }
    catch (DirectoryException e)
    {
      logger.traceException(e, "Unable to count entries of configuration backend");
      return -1;
    }
  }
 
  @Override
  public File getDirectory()
  {
    return configurationHandler.getConfigurationFile().getParentFile();
  }
 
  @Override
  public long getNumberOfChildren(DN parentDN) throws DirectoryException
  {
    try {
      return configurationHandler.numSubordinates(parentDN, false);
    }
    catch (ConfigException e)
    {
      throw new DirectoryException(ResultCode.UNDEFINED, e.getMessageObject());
    }
  }
 
  @Override
  public long getNumberOfEntriesInBaseDN(DN baseDN) throws DirectoryException
  {
    try
    {
      return configurationHandler.numSubordinates(baseDN, true) + 1;
    }
    catch (ConfigException e)
    {
      throw new DirectoryException(ResultCode.UNDEFINED, e.getMessageObject());
    }
  }
 
  @Override
  public Set<String> getSupportedControls()
  {
    return SUPPORTED_CONTROLS;
  }
 
  @Override
  public Set<String> getSupportedFeatures()
  {
    return SUPPORTED_FEATURES;
  }
 
  @Override
  public ConditionResult hasSubordinates(DN entryDN) throws DirectoryException
  {
    long ret = getNumberOfChildren(entryDN);
    if(ret < 0)
    {
      return ConditionResult.UNDEFINED;
    }
    return ConditionResult.valueOf(ret != 0);
  }
 
  @Override
  public boolean isIndexed(AttributeType attributeType, IndexType indexType)
  {
    // All searches in this backend will always be considered indexed.
    return true;
  }
 
  @Override
  public boolean entryExists(DN entryDN) throws DirectoryException
  {
    try
    {
      return configurationHandler.hasEntry(entryDN);
    }
    catch (ConfigException e)
    {
      throw new DirectoryException(ResultCode.UNDEFINED, e.getMessageObject(), e);
    }
  }
 
  @Override
  public boolean supports(BackendOperation backendOperation)
  {
    switch (backendOperation)
    {
    case BACKUP:
    case RESTORE:
    case LDIF_EXPORT:
      return true;
    default:
      return false;
    }
  }
 
  @Override
  public void search(SearchOperation searchOperation) throws DirectoryException
  {
    // Make sure that the associated user has the CONFIG_READ privilege.
    ClientConnection clientConnection = searchOperation.getClientConnection();
    if (! clientConnection.hasPrivilege(Privilege.CONFIG_READ, searchOperation))
    {
      LocalizableMessage message = ERR_CONFIG_FILE_SEARCH_INSUFFICIENT_PRIVILEGES.get();
      throw new DirectoryException(ResultCode.INSUFFICIENT_ACCESS_RIGHTS, message);
    }
 
    configurationHandler.search(searchOperation);
  }
 
  @Override
  public void addEntry(Entry entry, AddOperation addOperation)
         throws DirectoryException
  {
    // Make sure that the associated user has
    // both the CONFIG_READ and CONFIG_WRITE privileges.
    if (addOperation != null)
    {
      ClientConnection clientConnection = addOperation.getClientConnection();
      if (!clientConnection.hasAllPrivileges(CONFIG_READ_AND_WRITE, addOperation))
      {
        LocalizableMessage message = ERR_CONFIG_FILE_ADD_INSUFFICIENT_PRIVILEGES.get();
        throw new DirectoryException(ResultCode.INSUFFICIENT_ACCESS_RIGHTS, message);
      }
    }
 
    // Only one configuration update may be in progress at any given time.
    synchronized (configLock)
    {
      configurationHandler.addEntry(Converters.from(copyWithoutVirtualAttributes(entry)));
    }
  }
 
  private Entry copyWithoutVirtualAttributes(Entry entry) {
    return entry.duplicate(false);
  }
 
  @Override
  public void deleteEntry(DN entryDN, DeleteOperation deleteOperation)
         throws DirectoryException
  {
    // Make sure that the associated user
    // has both the CONFIG_READ and CONFIG_WRITE privileges.
    if (deleteOperation != null)
    {
      ClientConnection clientConnection = deleteOperation.getClientConnection();
      if (!clientConnection.hasAllPrivileges(CONFIG_READ_AND_WRITE, deleteOperation))
      {
        LocalizableMessage message = ERR_CONFIG_FILE_DELETE_INSUFFICIENT_PRIVILEGES.get();
        throw new DirectoryException(ResultCode.INSUFFICIENT_ACCESS_RIGHTS, message);
      }
    }
 
    // Only one configuration update may be in progress at any given time.
    synchronized (configLock)
    {
      if (configRootEntry.getName().equals(entryDN))
      {
        LocalizableMessage message = ERR_CONFIG_FILE_DELETE_NO_PARENT.get(entryDN);
        throw new DirectoryException(ResultCode.UNWILLING_TO_PERFORM, message);
      }
      configurationHandler.deleteEntry(entryDN);
    }
  }
 
  @Override
  public void replaceEntry(Entry oldEntry, Entry newEntry, ModifyOperation modifyOperation) throws DirectoryException
  {
    // Make sure that the associated user has both the CONFIG_READ and CONFIG_WRITE privileges.
    // Also, if the operation targets the set of root privileges
    // then make sure the user has the PRIVILEGE_CHANGE privilege.
    if (modifyOperation != null)
    {
      ClientConnection clientConnection = modifyOperation.getClientConnection();
      if (!clientConnection.hasAllPrivileges(CONFIG_READ_AND_WRITE, modifyOperation))
      {
        LocalizableMessage message = ERR_CONFIG_FILE_MODIFY_INSUFFICIENT_PRIVILEGES.get();
        throw new DirectoryException(ResultCode.INSUFFICIENT_ACCESS_RIGHTS, message);
      }
 
      for (Modification m : modifyOperation.getModifications())
      {
        if (m.getAttribute().getAttributeDescription().getAttributeType().hasName(ATTR_DEFAULT_ROOT_PRIVILEGE_NAME))
        {
          if (!clientConnection.hasPrivilege(Privilege.PRIVILEGE_CHANGE, modifyOperation))
          {
            LocalizableMessage message = ERR_CONFIG_FILE_MODIFY_PRIVS_INSUFFICIENT_PRIVILEGES.get();
            throw new DirectoryException(ResultCode.INSUFFICIENT_ACCESS_RIGHTS, message);
          }
 
          break;
        }
      }
    }
 
    // Only one configuration update may be in progress at any given time.
    synchronized (configLock)
    {
      configurationHandler.replaceEntry(
          Converters.from(copyWithoutVirtualAttributes(oldEntry)),
          Converters.from(copyWithoutVirtualAttributes(newEntry)));
    }
  }
 
  @Override
  public void renameEntry(DN currentDN, Entry entry, ModifyDNOperation modifyDNOperation) throws DirectoryException
  {
    // Make sure that the associated
    // user has both the CONFIG_READ and CONFIG_WRITE privileges.
    if (modifyDNOperation != null)
    {
      ClientConnection clientConnection = modifyDNOperation.getClientConnection();
      if (!clientConnection.hasAllPrivileges(CONFIG_READ_AND_WRITE, modifyDNOperation))
      {
        LocalizableMessage message = ERR_CONFIG_FILE_MODDN_INSUFFICIENT_PRIVILEGES.get();
        throw new DirectoryException(ResultCode.INSUFFICIENT_ACCESS_RIGHTS, message);
      }
    }
 
    // Modify DN operations will not be allowed in the configuration, so this
    // will always throw an exception.
    LocalizableMessage message = ERR_CONFIG_FILE_MODDN_NOT_ALLOWED.get();
    throw new DirectoryException(ResultCode.UNWILLING_TO_PERFORM, message);
  }
 
  @Override
  public void exportLDIF(LDIFExportConfig exportConfig) throws DirectoryException
  {
    configurationHandler.writeLDIF(exportConfig);
  }
 
  @Override
  public LDIFImportResult importLDIF(LDIFImportConfig importConfig, ServerContext serverContext)
         throws DirectoryException
  {
    throw new DirectoryException(ResultCode.UNWILLING_TO_PERFORM, ERR_CONFIG_FILE_UNWILLING_TO_IMPORT.get());
  }
 
  @Override
  public void createBackup(BackupConfig backupConfig) throws DirectoryException
  {
    new BackupManager(getBackendID()).createBackup(this, backupConfig);
  }
 
  @Override
  public void removeBackup(BackupDirectory backupDirectory, String backupID) throws DirectoryException
  {
    new BackupManager(getBackendID()).removeBackup(backupDirectory, backupID);
  }
 
  @Override
  public void restoreBackup(RestoreConfig restoreConfig) throws DirectoryException
  {
    new BackupManager(getBackendID()).restoreBackup(this, restoreConfig);
  }
 
  @Override
  public ListIterator<Path> getFilesToBackup()
  {
    final List<Path> files = new ArrayList<>();
 
    File configFile = configurationHandler.getConfigurationFile();
    files.add(configFile.toPath());
 
    // the files in archive directory
    File archiveDirectory = new File(getDirectory(), CONFIG_ARCHIVE_DIR_NAME);
    if (archiveDirectory.exists())
    {
      for (File archiveFile : archiveDirectory.listFiles())
      {
        files.add(archiveFile.toPath());
      }
    }
 
    return files.listIterator();
  }
 
  @Override
  public boolean isDirectRestore()
  {
    return true;
  }
 
  @Override
  public Path beforeRestore() throws DirectoryException
  {
    // save current config files to a save directory
    return BackupManager.saveCurrentFilesToDirectory(this, getBackendID());
  }
 
  @Override
  public void afterRestore(Path restoreDirectory, Path saveDirectory) throws DirectoryException
  {
    // restore was successful, delete the save directory
    StaticUtils.recursiveDelete(saveDirectory.toFile());
  }
}