commit_id
string
repo
string
commit_message
string
diff
string
label
int64
db6423ba0afb99615c265112ef4075ef75164faa
1up-lab/OneupUploaderBundle
Merge pull request #192 from u-voelkel/fix-iterator fix iterator access. fixes #190.
commit db6423ba0afb99615c265112ef4075ef75164faa (from f28f251a6c8c5501db38af2a2b6e1a8337e079f5) Merge: f28f251 1ffd96c Author: David Greminger <[email protected]> Date: Tue Sep 29 16:41:35 2015 +0200 Merge pull request #192 from u-voelkel/fix-iterator fix iterator access. fixes #190. diff --git a/Uploader/Chunk/Storage/FilesystemStorage.php b/Uploader/Chunk/Storage/FilesystemStorage.php index 8855188..acc98d7 100644 --- a/Uploader/Chunk/Storage/FilesystemStorage.php +++ b/Uploader/Chunk/Storage/FilesystemStorage.php @@ -56,7 +56,7 @@ class FilesystemStorage implements ChunkStorageInterface throw new \InvalidArgumentException('The first argument must implement \IteratorAggregate interface.'); } - $iterator = $chunks->getIterator()->getInnerIterator(); + $iterator = $chunks->getIterator(); $base = $iterator->current(); $iterator->next();
0
23c7e30640305ab40ed789f45fd308514c140fad
1up-lab/OneupUploaderBundle
Interface and first version of a Orphanage-implementation.
commit 23c7e30640305ab40ed789f45fd308514c140fad Author: Jim Schmid <[email protected]> Date: Wed Mar 13 11:35:56 2013 +0100 Interface and first version of a Orphanage-implementation. diff --git a/Uploader/Orphanage/Orphanage.php b/Uploader/Orphanage/Orphanage.php new file mode 100644 index 0000000..8731c09 --- /dev/null +++ b/Uploader/Orphanage/Orphanage.php @@ -0,0 +1,40 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\Orphanage; + + +use Symfony\Component\HttpFoundation\File\File; +use Symfony\Component\HttpFoundation\Session\SessionInterface; +use Oneup\UploaderBundle\Uploader\Orphanage\OrphanageInterface; + +class Orphanage implements OrphanageInterface +{ + protected $session; + protected $config; + + public function __construct(SessionInterface $session, $config) + { + $this->session = $session; + $this->config = $config; + } + + public function addFile(File $file) + { + // prefix directory with session id + $id = $session->getId(); + $path = sprintf('%s/%s/%s', $this->config['directory'], $id, $file->getRealPath()); + + var_dump($path); + die(); + } + + public function removeFile(File $file) + { + + } + + public function getFiles() + { + + } +} \ No newline at end of file diff --git a/Uploader/Orphanage/OrphanageInterface.php b/Uploader/Orphanage/OrphanageInterface.php new file mode 100644 index 0000000..d585a9a --- /dev/null +++ b/Uploader/Orphanage/OrphanageInterface.php @@ -0,0 +1,8 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\Orphanage; + +interface OrphanageInterface +{ + +}
0
f6804b958cc4d283cec0992943502df61e5f7e89
1up-lab/OneupUploaderBundle
Use the correct typehint for Iterators.
commit f6804b958cc4d283cec0992943502df61e5f7e89 Author: Jim Schmid <[email protected]> Date: Mon Jun 24 14:13:15 2013 +0200 Use the correct typehint for Iterators. diff --git a/Uploader/Chunk/ChunkManager.php b/Uploader/Chunk/ChunkManager.php index f5bc733..18760b0 100644 --- a/Uploader/Chunk/ChunkManager.php +++ b/Uploader/Chunk/ChunkManager.php @@ -47,7 +47,7 @@ class ChunkManager implements ChunkManagerInterface return $chunk->move($path, $name); } - public function assembleChunks(\Traversable $chunks) + public function assembleChunks(\IteratorAggregate $chunks) { $iterator = $chunks->getIterator()->getInnerIterator(); diff --git a/Uploader/Chunk/ChunkManagerInterface.php b/Uploader/Chunk/ChunkManagerInterface.php index 009bfed..3fad75a 100644 --- a/Uploader/Chunk/ChunkManagerInterface.php +++ b/Uploader/Chunk/ChunkManagerInterface.php @@ -8,7 +8,7 @@ interface ChunkManagerInterface { public function clear(); public function addChunk($uuid, $index, UploadedFile $chunk, $original); - public function assembleChunks(\Traversable $chunks); + public function assembleChunks(\IteratorAggregate $chunks); public function cleanup($path); public function getChunks($uuid); }
0
3fc5ff3646613d964397b0ffb34db3bdcf83a3aa
1up-lab/OneupUploaderBundle
Fixed double dispatching of post upload events.
commit 3fc5ff3646613d964397b0ffb34db3bdcf83a3aa Author: Jim Schmid <[email protected]> Date: Thu Jun 20 20:18:36 2013 +0200 Fixed double dispatching of post upload events. diff --git a/Controller/FancyUploadController.php b/Controller/FancyUploadController.php index 30a58a8..b9244fe 100644 --- a/Controller/FancyUploadController.php +++ b/Controller/FancyUploadController.php @@ -21,9 +21,6 @@ class FancyUploadController extends AbstractController try { $uploaded = $this->handleUpload($file, $response, $request); - - // dispatch POST_PERSIST AND POST_UPLOAD events - $this->dispatchEvents($uploaded, $response, $request); } catch(UploadException $e) { diff --git a/Controller/UploadifyController.php b/Controller/UploadifyController.php index 88038a2..cc42c74 100644 --- a/Controller/UploadifyController.php +++ b/Controller/UploadifyController.php @@ -21,9 +21,6 @@ class UploadifyController extends AbstractController try { $uploaded = $this->handleUpload($file, $response, $request); - - // dispatch POST_PERSIST AND POST_UPLOAD events - $this->dispatchEvents($uploaded, $response, $request); } catch(UploadException $e) { diff --git a/Controller/YUI3Controller.php b/Controller/YUI3Controller.php index 4475947..d5c87de 100644 --- a/Controller/YUI3Controller.php +++ b/Controller/YUI3Controller.php @@ -21,9 +21,6 @@ class YUI3Controller extends AbstractController try { $uploaded = $this->handleUpload($file, $response, $request); - - // dispatch POST_PERSIST AND POST_UPLOAD events - $this->dispatchEvents($uploaded, $response, $request); } catch(UploadException $e) {
0
14cbd2ae9d3178a683ac13caaa3844d57e8865e6
1up-lab/OneupUploaderBundle
Comments and CS fixes in AbstractController.
commit 14cbd2ae9d3178a683ac13caaa3844d57e8865e6 Author: Jim Schmid <[email protected]> Date: Thu Jun 20 21:17:40 2013 +0200 Comments and CS fixes in AbstractController. diff --git a/Controller/AbstractChunkedController.php b/Controller/AbstractChunkedController.php index e343807..b167aa6 100644 --- a/Controller/AbstractChunkedController.php +++ b/Controller/AbstractChunkedController.php @@ -26,6 +26,7 @@ abstract class AbstractChunkedController extends AbstractController * - orig: The original file name. * * @param request The request object + * @return array */ abstract protected function parseChunkedRequest(Request $request); @@ -38,6 +39,8 @@ abstract class AbstractChunkedController extends AbstractController * returned array to reassemble the uploaded chunks. * * @param file The uploaded chunk. + * @param response A response object. + * @param request The request object. */ protected function handleChunkedUpload(UploadedFile $file, ResponseInterface $response, Request $request) { @@ -79,6 +82,11 @@ abstract class AbstractChunkedController extends AbstractController /** * This function is a helper function which dispatches post chunk upload event. + * + * @param uploaded The uploaded chunk. + * @param response A response object. + * @param request The request object. + * @param isLast True if this is the last chunk, false otherwise. */ protected function dispatchChunkEvents($uploaded, ResponseInterface $response, Request $request, $isLast) { diff --git a/Controller/AbstractController.php b/Controller/AbstractController.php index bcbe763..b5c91a1 100644 --- a/Controller/AbstractController.php +++ b/Controller/AbstractController.php @@ -42,6 +42,9 @@ abstract class AbstractController * Note: The return value differs when * * @param UploadedFile The file to upload + * @param response A response object. + * @param request The request object. + * * @return File the actual file */ protected function handleUpload(UploadedFile $file, ResponseInterface $response, Request $request) @@ -61,6 +64,10 @@ abstract class AbstractController /** * This function is a helper function which dispatches post upload * and post persist events. + * + * @param uploaded The uploaded file. + * @param response A response object. + * @param request The request object. */ protected function dispatchEvents($uploaded, ResponseInterface $response, Request $request) { @@ -84,12 +91,9 @@ abstract class AbstractController $dispatcher = $this->container->get('event_dispatcher'); $event = new ValidationEvent($file, $this->config, $this->type); - try - { + try { $dispatcher->dispatch(UploadEvents::VALIDATION, $event); - } - catch(ValidationException $exception) - { + } catch(ValidationException $exception) { // pass the exception one level up throw new UploadException($exception->getMessage()); }
0
db9177712e989569bbfab1f33189425d6116e272
1up-lab/OneupUploaderBundle
Update configuration_reference.md
commit db9177712e989569bbfab1f33189425d6116e272 Author: mitom <[email protected]> Date: Fri Oct 11 09:57:36 2013 +0200 Update configuration_reference.md diff --git a/Resources/doc/configuration_reference.md b/Resources/doc/configuration_reference.md index b75fee4..0a712c9 100644 --- a/Resources/doc/configuration_reference.md +++ b/Resources/doc/configuration_reference.md @@ -7,7 +7,13 @@ All available configuration options along with their default values are listed b oneup_uploader: chunks: maxage: 604800 - directory: ~ + storage: + type: filesystem + directory: ~ + filesystem: ~ + sync_buffer_size: 100K + stream_wrapper: ~ + prefix: 'chunks' load_distribution: true orphanage: maxage: 604800 @@ -26,6 +32,7 @@ oneup_uploader: type: filesystem filesystem: ~ directory: ~ + stream_wrapper: ~ sync_buffer_size: 100K allowed_extensions: [] disallowed_extensions: []
0
5d7b5b155782f157cdaf7cd1473bf5c4e72a9837
1up-lab/OneupUploaderBundle
Meh, last commit wasn't the rest. But no, I won't amend. :)
commit 5d7b5b155782f157cdaf7cd1473bf5c4e72a9837 Author: Jim Schmid <[email protected]> Date: Wed Mar 27 18:21:31 2013 +0100 Meh, last commit wasn't the rest. But no, I won't amend. :) diff --git a/Controller/UploaderController.php b/Controller/UploaderController.php index c4b8570..10ffce6 100644 --- a/Controller/UploaderController.php +++ b/Controller/UploaderController.php @@ -82,8 +82,7 @@ class UploaderController implements UploadControllerInterface $postUploadEvent = new PostUploadEvent($file, $this->request, $this->type, array( 'use_orphanage' => $this->config['use_orphanage'], - 'file_name' => $name, - 'deletable' => $this->config['deletable'], + 'file_name' => $name )); $this->dispatcher->dispatch(UploadEvents::POST_UPLOAD, $postUploadEvent); diff --git a/Routing/RouteLoader.php b/Routing/RouteLoader.php index 726e84d..3ccc0a0 100644 --- a/Routing/RouteLoader.php +++ b/Routing/RouteLoader.php @@ -38,21 +38,7 @@ class RouteLoader extends Loader array('_method' => 'POST') ); - $delete = new Route( - sprintf('/_uploader/%s/delete/{uuid}', $type), - array('_controller' => $service . ':delete', '_format' => 'json'), - array('_method' => 'DELETE', 'uuid' => '[A-z0-9-]*') - ); - - $base = new Route( - sprintf('/_uploader/%s/delete', $type), - array('_controller' => $service . ':delete', '_format' => 'json'), - array('_method' => 'DELETE') - ); - $routes->add(sprintf('_uploader_%s_upload', $type), $upload); - $routes->add(sprintf('_uploader_%s_delete', $type), $delete); - $routes->add(sprintf('_uploader_%s_delete_base', $type), $base); } return $routes; diff --git a/UploadEvents.php b/UploadEvents.php index f272c9d..6a9967b 100644 --- a/UploadEvents.php +++ b/UploadEvents.php @@ -6,5 +6,4 @@ final class UploadEvents { const POST_PERSIST = 'oneup.uploader.post.persist'; const POST_UPLOAD = 'oneup.uploader.post.upload'; - const POST_DELETE = 'oneup.uploader.post.delete'; } \ No newline at end of file diff --git a/Uploader/Storage/StorageInterface.php b/Uploader/Storage/StorageInterface.php index 38eb9c8..74a63df 100644 --- a/Uploader/Storage/StorageInterface.php +++ b/Uploader/Storage/StorageInterface.php @@ -7,5 +7,4 @@ use Symfony\Component\HttpFoundation\File\File; interface StorageInterface { public function upload(File $file, $name); - public function remove($type, $uuid); } \ No newline at end of file
0
ab115fc37d8fabb1347a3d476482c1bbeee33e55
1up-lab/OneupUploaderBundle
Renamed (dis)allowed_types to (dis)allowed_extensions.
commit ab115fc37d8fabb1347a3d476482c1bbeee33e55 Author: Jim Schmid <[email protected]> Date: Sat Apr 6 14:43:41 2013 +0200 Renamed (dis)allowed_types to (dis)allowed_extensions. diff --git a/Controller/UploaderController.php b/Controller/UploaderController.php index 3e63f8b..21cf3d9 100644 --- a/Controller/UploaderController.php +++ b/Controller/UploaderController.php @@ -130,12 +130,12 @@ class UploaderController implements UploadControllerInterface // if this mapping defines at least one type of an allowed extension, // test if the current is in this array - if(count($this->config['allowed_types']) > 0 && !in_array($extension, $this->config['allowed_types'])) + if(count($this->config['allowed_extensions']) > 0 && !in_array($extension, $this->config['allowed_extensions'])) throw new UploadException('This extension is not allowed.'); // check if the current extension is mentioned in the disallowed types // and if so, throw an exception - if(count($this->config['disallowed_types']) > 0 && in_array($extension, $this->config['disallowed_types'])) + if(count($this->config['disallowed_extensions']) > 0 && in_array($extension, $this->config['disallowed_extensions'])) throw new UploadException('This extension is not allowed.'); } diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 4deb776..5f061b0 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -46,10 +46,10 @@ class Configuration implements ConfigurationInterface ->scalarNode('directory')->defaultNull()->end() ->end() ->end() - ->arrayNode('allowed_types') + ->arrayNode('allowed_extensions') ->prototype('scalar')->end() ->end() - ->arrayNode('disallowed_types') + ->arrayNode('disallowed_extensions') ->prototype('scalar')->end() ->end() ->scalarNode('max_size')->defaultValue(\PHP_INT_MAX)->end()
0
5364f980335109d5ae946d5ae540c327eeea8376
1up-lab/OneupUploaderBundle
Remove the prefix after assembling the last chunk. Until now, the reassembled file shared the name with the very first chunk uploaded. It had the form {prefix}_{filename}. This commit fixes this issue and addresses #21 with it.
commit 5364f980335109d5ae946d5ae540c327eeea8376 Author: Jim Schmid <[email protected]> Date: Mon Jun 24 14:45:42 2013 +0200 Remove the prefix after assembling the last chunk. Until now, the reassembled file shared the name with the very first chunk uploaded. It had the form {prefix}_{filename}. This commit fixes this issue and addresses #21 with it. diff --git a/Tests/Controller/AbstractChunkedUploadTest.php b/Tests/Controller/AbstractChunkedUploadTest.php index 29c8a90..bbc4bc9 100644 --- a/Tests/Controller/AbstractChunkedUploadTest.php +++ b/Tests/Controller/AbstractChunkedUploadTest.php @@ -4,8 +4,9 @@ namespace Oneup\UploaderBundle\Tests\Controller; use Symfony\Component\EventDispatcher\Event; use Oneup\UploaderBundle\Tests\Controller\AbstractUploadTest; -use Oneup\UploaderBundle\UploadEvents; use Oneup\UploaderBundle\Event\PostChunkUploadEvent; +use Oneup\UploaderBundle\Event\PreUploadEvent; +use Oneup\UploaderBundle\UploadEvents; abstract class AbstractChunkedUploadTest extends AbstractUploadTest { @@ -17,11 +18,27 @@ abstract class AbstractChunkedUploadTest extends AbstractUploadTest public function testChunkedUpload() { // assemble a request - $client = $this->client; + $me = $this; $endpoint = $this->helper->endpoint($this->getConfigKey()); + $basename = ''; for ($i = 0; $i < $this->total; $i ++) { - $client->request('POST', $endpoint, $this->getNextRequestParameters($i), array($this->getNextFile($i))); + $file = $this->getNextFile($i); + + if ($basename === '') { + $basename = $file->getClientOriginalName(); + } + + $client = static::createClient(); + $dispatcher = $client->getContainer()->get('event_dispatcher'); + + $dispatcher->addListener(UploadEvents::PRE_UPLOAD, function(PreUploadEvent $event) use (&$me, $basename) { + $file = $event->getFile(); + + $me->assertEquals($file->getBasename(), $basename); + }); + + $client->request('POST', $endpoint, $this->getNextRequestParameters($i), array($file)); $response = $client->getResponse(); $this->assertTrue($response->isSuccessful()); diff --git a/Uploader/Chunk/ChunkManager.php b/Uploader/Chunk/ChunkManager.php index 18760b0..5bfa4b5 100644 --- a/Uploader/Chunk/ChunkManager.php +++ b/Uploader/Chunk/ChunkManager.php @@ -2,6 +2,7 @@ namespace Oneup\UploaderBundle\Uploader\Chunk; +use Symfony\Component\HttpFoundation\File\File; use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\Finder\Finder; use Symfony\Component\Filesystem\Filesystem; @@ -65,7 +66,11 @@ class ChunkManager implements ChunkManagerInterface $iterator->next(); } - return $base; + // remove the prefix added by self::addChunk + $assembled = new File($base->getRealPath()); + $assembled = $assembled->move($base->getPath(), preg_replace('/^(.+?)_/', '', $base->getBasename())); + + return $assembled; } public function cleanup($path)
0
6af40c4fc610dd774417bf2326d76f3e79099ac2
1up-lab/OneupUploaderBundle
Documented moouploader.
commit 6af40c4fc610dd774417bf2326d76f3e79099ac2 Author: Jim Schmid <[email protected]> Date: Fri Apr 12 14:25:05 2013 +0200 Documented moouploader. diff --git a/README.md b/README.md index dea7969..558ff06 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ The OneupUploaderBundle adds support for handling file uploads using one of the * [YUI3 Uploader](http://yuilibrary.com/yui/docs/uploader/) * [Uploadify](http://www.uploadify.com/) * [FancyUpload](http://digitarald.de/project/fancyupload/) +* [MooUpload](https://github.com/juanparati/MooUpload) Features included: diff --git a/Resources/doc/frontend_mooupload.md b/Resources/doc/frontend_mooupload.md new file mode 100644 index 0000000..5dfa4cb --- /dev/null +++ b/Resources/doc/frontend_mooupload.md @@ -0,0 +1,35 @@ +Use MooUpload in your Symfony2 application +========================================== + +Download [MooUpload](https://github.com/juanparati/MooUpload) and include it in your template. Connect the `action` property to the dynamic route `_uploader_{mapping_name}`. + +```html +<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/mootools/1.4.0/mootools-yui-compressed.js"></script> +<script type="text/javascript" src="http://www.livespanske.com/labs/MooUpload/MooUpload.js"></script> +<script type="text/javascript"> + +window.addEvent("domready", function() +{ + var myUpload = new MooUpload("fileupload", + { + action: "{{ path('_uploader_gallery') }}", + method: "auto" + }); +}); +</script> + +<div id="fileupload"></div> +``` + +Configure the OneupUploaderBundle to use the correct controller: + +```yaml +# app/config/config.yml + +oneup_uploader: + mappings: + gallery: + frontend: mooupload +``` + +Be sure to check out the [official manual](https://github.com/juanparati/MooUpload) for details on the configuration. \ No newline at end of file diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 663f91e..357df8f 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -95,6 +95,7 @@ So if you take the mapping described before, the generated route name would be ` * [Use YUI3 Uploader](frontend_yui3.md) * [Use Uploadify](frontend_uploadify.md) * [Use FancyUpload](frontend_fancyupload.md) +* [Use MooUpload](frontend_mooupload.md) This is of course a very minimal setup. Be sure to include stylesheets for Fine Uploader if you want to use them.
0
6594095e71e484f4afcdac55639fe614a7c7bebc
1up-lab/OneupUploaderBundle
Merge pull request #162 from jbouzekri/max_size process max size when string
commit 6594095e71e484f4afcdac55639fe614a7c7bebc (from 593e54e58981f4bb0796364760ddd34ecca3b23d) Merge: 593e54e 70b5f5e Author: Jim Schmid <[email protected]> Date: Wed Mar 11 08:11:21 2015 +0100 Merge pull request #162 from jbouzekri/max_size process max size when string diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index 34e707d..aec580d 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -69,7 +69,7 @@ class OneupUploaderExtension extends Extension protected function processMapping($key, &$mapping) { - $mapping['max_size'] = $mapping['max_size'] < 0 ? + $mapping['max_size'] = $mapping['max_size'] < 0 || is_string($mapping['max_size']) ? $this->getMaxUploadSize($mapping['max_size']) : $mapping['max_size'] ; commit 6594095e71e484f4afcdac55639fe614a7c7bebc (from 70b5f5e04f1834e547fafdebb5ce35dba2c796d7) Merge: 593e54e 70b5f5e Author: Jim Schmid <[email protected]> Date: Wed Mar 11 08:11:21 2015 +0100 Merge pull request #162 from jbouzekri/max_size process max size when string diff --git a/Controller/DropzoneController.php b/Controller/DropzoneController.php index 0c8a5b0..2121f32 100644 --- a/Controller/DropzoneController.php +++ b/Controller/DropzoneController.php @@ -20,6 +20,11 @@ class DropzoneController extends AbstractController $this->handleUpload($file, $response, $request); } catch (UploadException $e) { $this->errorHandler->addException($response, $e); + $translator = $this->container->get('translator'); + $message = $translator->trans($e->getMessage(), array(), 'OneupUploaderBundle'); + $response = $this->createSupportedJsonResponse(array('error'=>$message )); + $response->setStatusCode(400); + return $response; } } diff --git a/Resources/doc/orphanage.md b/Resources/doc/orphanage.md index 6848615..9e4db06 100644 --- a/Resources/doc/orphanage.md +++ b/Resources/doc/orphanage.md @@ -53,6 +53,18 @@ class AcmeController extends Controller You will get an array containing the moved files. +Note that you can move only one or a set of defined files out of the orphanage by passing an array to $manager->getFiles(). +For instance, you can use this to move a specific file: +```php + // get files + $files = $manager->getFiles(); + + // reduce the scope of the Finder object to what you want + $files->files()->name($filename); + $manager->uploadFiles(iterator_to_array($files)); +``` +In this example, $filename is the name of the file you want to move out of the orphanage. + > If you are using Gaufrette, these files are instances of `Gaufrette\File`, otherwise `SplFileInfo`. ## Configure the Orphanage diff --git a/Routing/RouteLoader.php b/Routing/RouteLoader.php index fad6c0f..cd8c070 100644 --- a/Routing/RouteLoader.php +++ b/Routing/RouteLoader.php @@ -32,14 +32,22 @@ class RouteLoader extends Loader $upload = new Route( sprintf('%s/_uploader/%s/upload', $options['route_prefix'], $type), array('_controller' => $service . ':upload', '_format' => 'json'), - array('_method' => 'POST') + array(), + array(), + '', + array(), + array('POST', 'PUT', 'PATCH') ); if ($options['enable_progress'] === true) { $progress = new Route( sprintf('%s/_uploader/%s/progress', $options['route_prefix'], $type), array('_controller' => $service . ':progress', '_format' => 'json'), - array('_method' => 'POST') + array(), + array(), + '', + array(), + array('POST') ); $routes->add(sprintf('_uploader_progress_%s', $type), $progress); @@ -49,7 +57,11 @@ class RouteLoader extends Loader $progress = new Route( sprintf('%s/_uploader/%s/cancel', $options['route_prefix'], $type), array('_controller' => $service . ':cancel', '_format' => 'json'), - array('_method' => 'POST') + array(), + array(), + '', + array(), + array('POST') ); $routes->add(sprintf('_uploader_cancel_%s', $type), $progress); diff --git a/Tests/Controller/AbstractControllerTest.php b/Tests/Controller/AbstractControllerTest.php index 9e6d26a..2b0abf7 100644 --- a/Tests/Controller/AbstractControllerTest.php +++ b/Tests/Controller/AbstractControllerTest.php @@ -40,8 +40,7 @@ abstract class AbstractControllerTest extends WebTestCase */ public function testCallByGet() { - $endpoint = $this->helper->endpoint($this->getConfigKey()); - $this->client->request('GET', $endpoint); + $this->implTestCallBy('GET'); } /** @@ -49,25 +48,30 @@ abstract class AbstractControllerTest extends WebTestCase */ public function testCallByDelete() { - $endpoint = $this->helper->endpoint($this->getConfigKey()); - $this->client->request('DELETE', $endpoint); + $this->implTestCallBy('DELETE'); } - /** - * @expectedException Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException - */ - public function testCallByPut() + public function testCallByPatch() { - $endpoint = $this->helper->endpoint($this->getConfigKey()); - $this->client->request('PUT', $endpoint); + $this->implTestCallBy('PATCH'); } public function testCallByPost() + { + $this->implTestCallBy('POST'); + } + + public function testCallByPut() + { + $this->implTestCallBy('PUT'); + } + + protected function implTestCallBy($method) { $client = $this->client; $endpoint = $this->helper->endpoint($this->getConfigKey()); - $client->request('POST', $endpoint, array(), array(), $this->requestHeaders); + $client->request($method, $endpoint, array(), array(), $this->requestHeaders); $response = $client->getResponse(); $this->assertTrue($response->isSuccessful()); diff --git a/Tests/Routing/RouteLoaderTest.php b/Tests/Routing/RouteLoaderTest.php index 4058039..95b35ab 100644 --- a/Tests/Routing/RouteLoaderTest.php +++ b/Tests/Routing/RouteLoaderTest.php @@ -33,8 +33,8 @@ class RouteLoaderTest extends \PHPUnit_Framework_TestCase foreach ($routes as $route) { $this->assertInstanceOf('Symfony\Component\Routing\Route', $route); - $this->assertEquals($route->getDefault('_format'), 'json'); - $this->assertEquals($route->getRequirement('_method'), 'POST'); + $this->assertEquals('json', $route->getDefault('_format')); + $this->assertContains('POST', $route->getMethods()); } } @@ -55,8 +55,8 @@ class RouteLoaderTest extends \PHPUnit_Framework_TestCase foreach ($routes as $route) { $this->assertInstanceOf('Symfony\Component\Routing\Route', $route); - $this->assertEquals($route->getDefault('_format'), 'json'); - $this->assertEquals($route->getRequirement('_method'), 'POST'); + $this->assertEquals('json', $route->getDefault('_format')); + $this->assertContains('POST', $route->getMethods()); $this->assertEquals(0, strpos($route->getPath(), $prefix)); }
0
35aa95b0e3a0f0bcc044de7374a110f61ddb0d9d
1up-lab/OneupUploaderBundle
Documented custom_uploaders
commit 35aa95b0e3a0f0bcc044de7374a110f61ddb0d9d Author: Jim Schmid <[email protected]> Date: Fri Apr 12 17:13:18 2013 +0200 Documented custom_uploaders diff --git a/Resources/doc/custom_uploader.md b/Resources/doc/custom_uploader.md index 43dbd6f..786e7a6 100644 --- a/Resources/doc/custom_uploader.md +++ b/Resources/doc/custom_uploader.md @@ -3,4 +3,126 @@ Support a custom Uploader If you have written your own Uploader or you want to use an implementation that is currently not supported by the OneupUploaderBundle follow these steps to integrate it to your Symfony2 application. -## \ No newline at end of file +## Configuration + +Configure your custom uploader according to the following example. + +```yml +oneup_uploader: + mappings: + gallery: + frontend: custom + custom_frontend: + class: Acme\DemoBundle\Controller\CustomController + name: MyFancyCustomUploader +``` + +This will automatically create everything you need later. +The next step is to include the logic of your custom Uploader to your provided Controller. For having a consistent interface consider extending one of the following classes: + +* `Oneup\UploaderBundle\Controller\AbstractController`: For any implementation that don't support chunked uploads. +* `Oneup\UploaderBundle\Controller\AbstractChunkedController`: For any implementation that should support chunked uploads. + +## The Controller part + +If you decided to extend the AbstractController, do the following + +```php +namespace Acme\DemoBundle\Controller; + +use Symfony\Component\HttpFoundation\File\Exception\UploadException; +use Symfony\Component\HttpFoundation\JsonResponse; +use Oneup\UploaderBundle\Controller\UploaderController; +use Oneup\UploaderBundle\Uploader\Response\EmptyResponse; + +class CustomUploader extends UploaderController +{ + public function upload() + { + // get some basic stuff together + $request = $this->container->get('request'); + $response = new EmptyResponse(); + + // get file from request (your own logic) + $file = ...; + + try + { + $uploaded = $this->handleUpload($file); + + // dispatch POST_PERSIST AND POST_UPLOAD events + $this->dispatchEvents($uploaded, $response, $request); + } + catch(UploadException $e) + { + // return nothing + return new JsonResponse(array()); + } + + // return assembled response + return new JsonResponse($response->assemble()); + } +} +``` + +## Implement chunked upload +If you want to additionaly support chunked upload, you have to overwrite the `AbstractChunkedController` and implement the `parseChunkedRequest` method. This method should return an array containing the following values: + +* `$last`: Is this the last chunk of a file (`true`/`false`) +* `$uuid`: A truly unique id which will become the directory name for the `ChunkManager` to use. +* `$index`: Which part (chunk) is it? Its not important that you provide exact numbers, but they must be higher for a subsequent chunk! +* `$orig`: The original filename. + +Take any chunked upload implementation in `Oneup\UploaderBundle\Controller` as an example. + +After that, you manually have to check if you have to do a chunked upload or not. This differs from implementation to implementation, so heres an example of the jQuery File Uploader: + +```php +$chunked = !is_null($request->headers->get('content-range')); +$uploaded = $chunked ? $this->handleChunkedUpload($file) : $this->handleUpload($file); +``` + +## Using a custom Response class +If your frontend implementation relies on specific data returned, it is highly recommended to create your own `Response` class. Here is an example for FineUploader, I guess you'll get the point: + +```php +namespace Oneup\UploaderBundle\Uploader\Response; + +use Oneup\UploaderBundle\Uploader\Response\AbstractResponse; + +class FineUploaderResponse extends AbstractResponse +{ + protected $success; + protected $error; + + public function __construct() + { + $this->success = true; + $this->error = null; + + parent::__construct(); + } + + public function assemble() + { + // explicitly overwrite success and error key + // as these keys are used internaly by the + // frontend uploader + $data = $this->data; + $data['success'] = $this->success; + + if($this->success) + unset($data['error']); + + if(!$this->success) + $data['error'] = $this->error; + + return $data; + } + + // ... snip, setters/getters +} + +## Notes + +It is highly recommended to use the internal and inherited methods `handleUpload` and `handleChunkedUpload` as these will mind your configuration file. Nonetheless; it is possible to overwrite the behaviour completely in your Controller class. \ No newline at end of file
0
8bd74b2d5f07f9ee6280f0b90ed8199471f57f52
1up-lab/OneupUploaderBundle
2020
commit 8bd74b2d5f07f9ee6280f0b90ed8199471f57f52 Author: David Greminger <[email protected]> Date: Thu Feb 6 10:12:03 2020 +0100 2020 diff --git a/LICENSE b/LICENSE index d4f24ca..1ecc6ec 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2018 1up GmbH +Copyright (c) 2020 1up GmbH Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal
0
1819ca7236b823cd03fe55b383313b1aef5f37b8
1up-lab/OneupUploaderBundle
Added warning to upgrade section of readme. Ping #21
commit 1819ca7236b823cd03fe55b383313b1aef5f37b8 Author: Jim Schmid <[email protected]> Date: Thu Jul 25 20:55:44 2013 +0200 Added warning to upgrade section of readme. Ping #21 diff --git a/README.md b/README.md index 0df2f93..d7ed3fd 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,7 @@ The entry point of the documentation can be found in the file `Resources/docs/in Upgrade Notes ------------- +* If you're using chunked uploads consider upgrading from **v0.9.6** to **v0.9.7**. A critical issue was reported regarding the assembly of chunks. More information in ticket [#21](https://github.com/1up-lab/OneupUploaderBundle/issues/21#issuecomment-21560320). * Error management [changed](https://github.com/1up-lab/OneupUploaderBundle/pull/25) in Version **0.9.6**. You can now register an `ErrorHandler` per configured frontend. This comes bundled with some adjustments to the `blueimp` controller. More information is available in [the documentation](https://github.com/1up-lab/OneupUploaderBundle/blob/master/Resources/doc/custom_error_handler.md). * Event dispatching [changed](https://github.com/1up-lab/OneupUploaderBundle/commit/a408548b241f47af3539b2137c1817a21a51fde9) in Version **0.9.5**. The dispatching is now handled in the `upload*` functions. So if you have created your own implementation, be sure to remove the call to the `dispatchEvents` function, otherwise it will be called twice. Furthermore no `POST_UPLOAD` event will be fired anymore after uploading a chunk. You can get more information on this topic in the [documentation](https://github.com/1up-lab/OneupUploaderBundle/blob/master/Resources/doc/custom_logic.md#using-chunked-uploads). * Event names [changed](https://github.com/1up-lab/OneupUploaderBundle/commit/f5d5fe4b6f7b9a04ce633acbc9c94a2dd0e0d6be) in Version **0.9.3**, update your EventListener accordingly.
0
80ae7658ced98fa70b47da454173ccf400a2114f
1up-lab/OneupUploaderBundle
Update README.md
commit 80ae7658ced98fa70b47da454173ccf400a2114f Author: David Greminger <[email protected]> Date: Mon Mar 18 14:35:25 2024 +0100 Update README.md diff --git a/LICENSE b/LICENSE index 1ecc6ec..8e9cdab 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2020 1up GmbH +Copyright (c) 2024 1up AG Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index a71ab81..e3c78cc 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,7 @@ The entry point of the documentation can be found in the file `docs/index.md` Upgrade Notes ------------- +* Version **5.0.0** supports now Symfony 7 (kudos to @[evertharmeling](https://github.com/evertharmeling) and @[joesenova](https://github.com/joesenova)), see [#436](https://github.com/1up-lab/OneupUploaderBundle/pull/436)! Symfony 4 and PHP 7 support was dropped. * Version **4.0.0** supports now [Flysystem 2 & 3](https://github.com/1up-lab/OneupFlysystemBundle) (kudos to @[m2mtech](https://github.com/m2mtech)), see [#412](https://github.com/1up-lab/OneupUploaderBundle/pull/412)! Flysystem 1 and OneupFlysystemBundle < 4.0 support was dropped. * Version **3.2.0** supports now Symfony 6 (kudos to @[pich](https://github.com/pich)), see [#421](https://github.com/1up-lab/OneupUploaderBundle/pull/421)! PHP 7.2/7.3 support was dropped. * Version **3.0.0** supports now Symfony 5 (kudos to @[steveWinter](https://github.com/steveWinter), @[gubler](https://github.com/gubler), @[patrickbussmann](https://github.com/patrickbussmann), @[ErnadoO](https://github.com/ErnadoO) and @[enumag](https://github.com/enumag), see [#373](https://github.com/1up-lab/OneupUploaderBundle/pull/373)! Symfony 3.x support was dropped.
0
f60ff27889f1889c4908cd043beca1291d8a3f89
1up-lab/OneupUploaderBundle
Added a BlueimpController skeleton.
commit f60ff27889f1889c4908cd043beca1291d8a3f89 Author: Jim Schmid <[email protected]> Date: Tue Apr 9 21:07:07 2013 +0200 Added a BlueimpController skeleton. diff --git a/Controller/BlueimpController.php b/Controller/BlueimpController.php new file mode 100644 index 0000000..064b95f --- /dev/null +++ b/Controller/BlueimpController.php @@ -0,0 +1,36 @@ +<?php + +namespace Oneup\UploaderBundle\Controller; + +use Symfony\Component\DependencyInjection\ContainerInterface; +use Symfony\Component\HttpFoundation\File\Exception\UploadException; +use Symfony\Component\HttpFoundation\File\UploadedFile; +use Symfony\Component\HttpFoundation\JsonResponse; + +use Oneup\UploaderBundle\UploadEvents; +use Oneup\UploaderBundle\Event\PostPersistEvent; +use Oneup\UploaderBundle\Event\PostUploadEvent; +use Oneup\UploaderBundle\Controller\UploadControllerInterface; +use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; +use Oneup\UploaderBundle\Uploader\Response\UploaderResponse; + +class FineUploaderController implements UploadControllerInterface +{ + protected $container; + protected $storage; + protected $config; + protected $type; + + public function __construct(ContainerInterface $container, StorageInterface $storage, array $config, $type) + { + $this->container = $container; + $this->storage = $storage; + $this->config = $config; + $this->type = $type; + } + + public function upload() + { + + } +} \ No newline at end of file
0
e5a1fc3b8ff68fdb9853effb2c3d3f548913a963
1up-lab/OneupUploaderBundle
Readded FineUploaderResponse
commit e5a1fc3b8ff68fdb9853effb2c3d3f548913a963 Author: Jim Schmid <[email protected]> Date: Tue Apr 9 21:45:08 2013 +0200 Readded FineUploaderResponse diff --git a/Uploader/Response/FineUploaderResponse.php b/Uploader/Response/FineUploaderResponse.php new file mode 100644 index 0000000..489ae56 --- /dev/null +++ b/Uploader/Response/FineUploaderResponse.php @@ -0,0 +1,78 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\Response; + +use Oneup\UploaderBundle\Uploader\Response\ResponseInterface; + +class FineUploaderResponse implements ResponseInterface +{ + protected $success; + protected $error; + protected $data; + + public function __construct() + { + $this->success = true; + $this->error = null; + $this->data = array(); + } + + public function assemble() + { + // explicitly overwrite success and error key + // as these keys are used internaly by the + // frontend uploader + $data = $this->data; + $data['success'] = $this->success; + + if($this->success) + unset($data['error']); + + if(!$this->success) + $data['error'] = $this->error; + + return $data; + } + + public function offsetSet($offset, $value) + { + is_null($offset) ? $this->data[] = $value : $this->data[$offset] = $value; + } + public function offsetExists($offset) + { + return isset($this->data[$offset]); + } + public function offsetUnset($offset) + { + unset($this->data[$offset]); + } + + public function offsetGet($offset) + { + return isset($this->data[$offset]) ? $this->data[$offset] : null; + } + + public function setSuccess($success) + { + $this->success = (bool) $success; + + return $this; + } + + public function getSuccess() + { + return $this->success; + } + + public function setError($msg) + { + $this->error = $msg; + + return $this; + } + + public function getError() + { + return $this->error; + } +} \ No newline at end of file
0
93a7ab825adb0adcb311ec479c9b56fb213fddd8
1up-lab/OneupUploaderBundle
CS fix
commit 93a7ab825adb0adcb311ec479c9b56fb213fddd8 Author: David Greminger <[email protected]> Date: Mon Dec 4 09:52:37 2017 +0100 CS fix diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 58c295c..c98172f 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -103,7 +103,9 @@ class Configuration implements ConfigurationInterface ->prototype('scalar') ->beforeNormalization() ->ifString() - ->then(function ($v) { return strtolower($v); }) + ->then(function ($v) { + return strtolower($v); + }) ->end() ->end() ->end() diff --git a/Event/ValidationEvent.php b/Event/ValidationEvent.php index cff3c99..baf917f 100644 --- a/Event/ValidationEvent.php +++ b/Event/ValidationEvent.php @@ -48,5 +48,4 @@ class ValidationEvent extends Event { return $this->response; } - } diff --git a/Uploader/ErrorHandler/PluploadErrorHandler.php b/Uploader/ErrorHandler/PluploadErrorHandler.php index 6716c87..81580ac 100644 --- a/Uploader/ErrorHandler/PluploadErrorHandler.php +++ b/Uploader/ErrorHandler/PluploadErrorHandler.php @@ -10,10 +10,8 @@ class PluploadErrorHandler implements ErrorHandlerInterface { public function addException(AbstractResponse $response, Exception $exception) { - /* Plupload only needs an error message so it can be handled client side */ + /* Plupload only needs an error message so it can be handled client side */ $message = $exception->getMessage(); $response['error'] = $message; } } - -?>
0
9b816f128e6eae9b64d13c2355ff2bcc1abdb8ec
1up-lab/OneupUploaderBundle
The assembling of the JsonResponse is not the buisness of the actual upload* methods.
commit 9b816f128e6eae9b64d13c2355ff2bcc1abdb8ec Author: Jim Schmid <[email protected]> Date: Thu Mar 14 17:13:24 2013 +0100 The assembling of the JsonResponse is not the buisness of the actual upload* methods. diff --git a/Controller/UploaderController.php b/Controller/UploaderController.php index ebd2c39..0047a7d 100644 --- a/Controller/UploaderController.php +++ b/Controller/UploaderController.php @@ -47,7 +47,7 @@ class UploaderController implements UploadControllerInterface { try { - $ret = $totalParts > 1 ? $this->handleChunkedUpload($file) : $this->handleUpload($file); + $status = $totalParts > 1 ? $this->handleChunkedUpload($file) : $this->handleUpload($file); } catch(UploadException $e) { @@ -56,7 +56,10 @@ class UploaderController implements UploadControllerInterface } } - return $ret; + return $status ? + new JsonResponse(array('success' => true)): + new JsonResponse(array('error' => 'An unknown error occured.')) + ; } protected function handleUpload(UploadedFile $file) @@ -94,7 +97,7 @@ class UploaderController implements UploadControllerInterface $this->dispatcher->dispatch(UploadEvents::POST_PERSIST, $postPersistEvent); } - return new JsonResponse(array('success' => true)); + return true; } protected function handleChunkedUpload(UploadedFile $file) @@ -126,6 +129,6 @@ class UploaderController implements UploadControllerInterface $this->chunkManager->cleanup($path); } - return new JsonResponse(array('success' => true)); + return true; } } \ No newline at end of file
0
19ba4bf48b3a80581f242eda313149508599c2a5
1up-lab/OneupUploaderBundle
Add Symfony 6.0 support (#421) Co-authored-by: David Greminger <[email protected]>
commit 19ba4bf48b3a80581f242eda313149508599c2a5 Author: Michał Piszczek <[email protected]> Date: Mon Mar 21 14:26:11 2022 +0100 Add Symfony 6.0 support (#421) Co-authored-by: David Greminger <[email protected]> diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6002249..b04960f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -36,8 +36,12 @@ jobs: strategy: fail-fast: false matrix: - php: [7.2, 7.3, 7.4, 8.0] - symfony: [4.4, 5.0] + php: [7.4, 8.0] + symfony: [4.4, 5.4, 6.0] + exclude: + # Symfony 6.0 does not supports php <8.0 + - php: 7.4 + symfony: 6.0 steps: - name: Setup PHP uses: shivammathur/[email protected] @@ -63,7 +67,7 @@ jobs: - name: Setup PHP uses: shivammathur/[email protected] with: - php-version: 7.2 + php-version: 7.4 extensions: dom, fileinfo, filter, gd, hash, intl, json, mbstring, pcre, pdo_mysql, zlib coverage: none diff --git a/composer.json b/composer.json index ef6d10f..000d258 100644 --- a/composer.json +++ b/composer.json @@ -32,16 +32,16 @@ } ], "require": { - "php": "^7.2.5 || ^8.0", - "symfony/asset": "^4.4 || ^5.0", - "symfony/event-dispatcher-contracts": "^1.0 || ^2.0", - "symfony/finder": "^4.4 || ^5.0", - "symfony/framework-bundle": "^4.4 || ^5.0", - "symfony/mime": "^4.4 || ^5.0", - "symfony/templating": "^4.4 || ^5.0", - "symfony/translation": "^4.4 || ^5.0", - "symfony/translation-contracts": "^1.0 || ^2.0", - "symfony/yaml": "^4.4 || ^5.0", + "php": "^7.4 || ^8.0", + "symfony/asset": "^4.4 || ^5.4 || ^6.0", + "symfony/event-dispatcher-contracts": "^1.0 || ^2.0 || ^3.0", + "symfony/finder": "^4.4 || ^5.4 || ^6.0", + "symfony/framework-bundle": "^4.4 || ^5.4 || ^6.0", + "symfony/mime": "^4.4 || ^5.4 || ^6.0", + "symfony/templating": "^4.4 || ^5.4 || ^6.0", + "symfony/translation": "^4.4 || ^5.4 || ^6.0", + "symfony/translation-contracts": "^1.0 || ^2.0 || ^3.0", + "symfony/yaml": "^4.4 || ^5.4 || ^6.0", "twig/twig": "^2.4 || ^3.0" }, "require-dev": { @@ -52,12 +52,12 @@ "knplabs/gaufrette": "^0.9", "oneup/flysystem-bundle": "^1.2 || ^2.0 || ^3.0", "phpstan/phpstan": "^0.12.10", - "phpunit/phpunit": "^8.5", + "phpunit/phpunit": "^9.5", "sensio/framework-extra-bundle": "^5.0 || ^6.0", - "symfony/browser-kit": "^4.4 || ^5.0", - "symfony/phpunit-bridge": "^5.0", - "symfony/security-bundle": "^4.4 || ^5.0", - "symfony/var-dumper": "^4.4 || ^5.0", + "symfony/browser-kit": "^4.4 || ^5.4 || ^6.0", + "symfony/phpunit-bridge": "^5.4", + "symfony/security-bundle": "^4.4 || ^5.4 || ^6.0", + "symfony/var-dumper": "^4.4 || ^5.4 || ^6.0", "twistor/flysystem-stream-wrapper": "^1.0" }, "suggest": { diff --git a/tests/App/Kernel.php b/tests/App/Kernel.php index 3b72826..1a15234 100644 --- a/tests/App/Kernel.php +++ b/tests/App/Kernel.php @@ -11,7 +11,7 @@ use Symfony\Component\HttpKernel\Kernel as BaseKernel; class Kernel extends BaseKernel { - public function registerBundles() + public function registerBundles(): iterable { $bundles = [ new FrameworkBundle(), @@ -30,7 +30,7 @@ class Kernel extends BaseKernel $loader->load($this->getProjectDir() . '/config/config.yml'); } - public function getProjectDir() + public function getProjectDir(): string { return __DIR__; } diff --git a/tests/App/config/config.yml b/tests/App/config/config.yml index ac4945d..3eda25a 100644 --- a/tests/App/config/config.yml +++ b/tests/App/config/config.yml @@ -10,7 +10,6 @@ framework: # engines: ['php'] default_locale: en session: - storage_id: session.storage.native handler_id: ~ test: true @@ -21,8 +20,6 @@ security: dev: pattern: ^/(_(profiler|wdt)|css|images|js)/ security: false - main: - anonymous: ~ oneup_uploader: mappings: diff --git a/tests/Controller/AbstractControllerTest.php b/tests/Controller/AbstractControllerTest.php index 0748c6b..6a56de1 100644 --- a/tests/Controller/AbstractControllerTest.php +++ b/tests/Controller/AbstractControllerTest.php @@ -41,6 +41,8 @@ abstract class AbstractControllerTest extends WebTestCase protected function setUp(): void { + self::ensureKernelShutdown(); + $this->client = static::createClient(['debug' => false]); $this->client->catchExceptions(false); $this->client->disableReboot(); @@ -49,12 +51,13 @@ abstract class AbstractControllerTest extends WebTestCase $container = $this->client->getContainer(); /** @var UploaderHelper $helper */ - $helper = self::$container->get('oneup_uploader.templating.uploader_helper'); + $helper = $container->get('oneup_uploader.templating.uploader_helper'); /** @var RouterInterface $router */ - $router = self::$container->get('router'); + $router = $container->get('router'); self::$container = $container; + $this->helper = $helper; $this->createdFiles = []; $this->requestHeaders = [ diff --git a/tests/Templating/TemplateHelperTest.php b/tests/Templating/TemplateHelperTest.php index 72d2ffb..a0abf71 100644 --- a/tests/Templating/TemplateHelperTest.php +++ b/tests/Templating/TemplateHelperTest.php @@ -12,6 +12,8 @@ class TemplateHelperTest extends WebTestCase { public function testName(): void { + self::ensureKernelShutdown(); + /** @var KernelBrowser $client */ $client = static::createClient(); @@ -28,6 +30,8 @@ class TemplateHelperTest extends WebTestCase { $this->expectException('\InvalidArgumentException'); + self::ensureKernelShutdown(); + /** @var KernelBrowser $client */ $client = static::createClient(); diff --git a/tests/Uploader/Naming/UniqidNamerTest.php b/tests/Uploader/Naming/UniqidNamerTest.php index 2b027a4..047b812 100644 --- a/tests/Uploader/Naming/UniqidNamerTest.php +++ b/tests/Uploader/Naming/UniqidNamerTest.php @@ -13,7 +13,6 @@ class UniqidNamerTest extends TestCase { public function testNamerReturnsName(): void { - /** @var FilesystemFile&MockObject $file */ $file = $this->createMock(FilesystemFile::class); $file @@ -22,7 +21,7 @@ class UniqidNamerTest extends TestCase ; $namer = new UniqidNamer(); - $this->assertRegExp('/[a-z0-9]{13}.jpeg/', $namer->name($file)); + $this->assertMatchesRegularExpression('/[a-z0-9]{13}.jpeg/', $namer->name($file)); } public function testNamerReturnsUniqueName(): void diff --git a/tests/Uploader/Orphanage/OrphanageManagerTest.php b/tests/Uploader/Orphanage/OrphanageManagerTest.php index e75977a..c2685d9 100644 --- a/tests/Uploader/Orphanage/OrphanageManagerTest.php +++ b/tests/Uploader/Orphanage/OrphanageManagerTest.php @@ -65,7 +65,7 @@ class OrphanageManagerTest extends TestCase $manager = new OrphanageManager($this->mockContainer, $this->mockConfig); $service = $manager->get('grumpycat'); - $this->assertTrue($service); + $this->assertInstanceOf(\stdClass::class, $service); } public function testClearAllInPast(): void @@ -119,12 +119,12 @@ class OrphanageManagerTest extends TestCase protected function getContainerMock() { /** @var MockObject&ContainerInterface $mock */ - $mock = $this->createMock('Symfony\Component\DependencyInjection\ContainerInterface'); + $mock = $this->createMock(ContainerInterface::class); $mock ->expects($this->any()) ->method('get') ->with('oneup_uploader.orphanage.grumpycat') - ->willReturn(true) + ->willReturn(new \stdClass()) ; return $mock;
0
f67931620e4c93876f55d892b211a53d7c0e7bfd
1up-lab/OneupUploaderBundle
Added example code for response return
commit f67931620e4c93876f55d892b211a53d7c0e7bfd Author: clément larrieu <[email protected]> Date: Thu Feb 2 11:59:17 2017 +0100 Added example code for response return diff --git a/Resources/doc/custom_logic.md b/Resources/doc/custom_logic.md index 1aa1cfd..3471492 100644 --- a/Resources/doc/custom_logic.md +++ b/Resources/doc/custom_logic.md @@ -31,6 +31,11 @@ class UploadListener public function onUpload(PostPersistEvent $event) { //... + + //if everything went fine + $response = $event->getResponse(); + $response['success'] = true; + return $response; } } ```
0
052148a91278b16bc592ce65ed9b1dddb5105ad6
1up-lab/OneupUploaderBundle
gaufette chunk storage test
commit 052148a91278b16bc592ce65ed9b1dddb5105ad6 Author: mitom <[email protected]> Date: Fri Oct 11 16:01:43 2013 +0200 gaufette chunk storage test diff --git a/Tests/Uploader/Chunk/Storage/ChunkStorageTest.php b/Tests/Uploader/Chunk/Storage/ChunkStorageTest.php new file mode 100644 index 0000000..af1f32f --- /dev/null +++ b/Tests/Uploader/Chunk/Storage/ChunkStorageTest.php @@ -0,0 +1,73 @@ +<?php + +namespace Oneup\UploaderBundle\Tests\Uploader\Chunk\Storage; + +use Symfony\Component\Filesystem\Filesystem; +use Symfony\Component\Finder\Finder; + +abstract class ChunkStorageTest extends \PHPUnit_Framework_TestCase +{ + protected $tmpDir; + protected $storage; + + public function testExistanceOfTmpDir() + { + $this->assertTrue(is_dir($this->tmpDir)); + $this->assertTrue(is_writeable($this->tmpDir)); + } + + public function testFillOfTmpDir() + { + $finder = new Finder(); + $finder->in($this->tmpDir); + + $numberOfFiles = 10; + + $this->fillDirectory($numberOfFiles); + $this->assertCount($numberOfFiles, $finder); + } + + public function testChunkCleanup() + { + // get a manager configured with a max-age of 5 minutes + $maxage = 5 * 60; + $numberOfFiles = 10; + + $finder = new Finder(); + $finder->in($this->tmpDir); + + $this->fillDirectory($numberOfFiles); + $this->assertCount($numberOfFiles, $finder); + + $this->storage->clear($maxage); + + $this->assertTrue(is_dir($this->tmpDir)); + $this->assertTrue(is_writeable($this->tmpDir)); + + $this->assertCount(5, $finder); + + foreach ($finder as $file) { + $this->assertGreaterThanOrEqual(time() - $maxage, filemtime($file)); + } + } + + public function testClearIfDirectoryDoesNotExist() + { + $filesystem = new Filesystem(); + $filesystem->remove($this->tmpDir); + + $this->storage->clear(10); + + // yey, no exception + $this->assertTrue(true); + } + + protected function fillDirectory($number) + { + $system = new Filesystem(); + + for ($i = 0; $i < $number; $i ++) { + $system->touch(sprintf('%s/%s', $this->tmpDir, uniqid()), time() - $i * 60); + } + } +} diff --git a/Tests/Uploader/Chunk/Storage/FilesystemStorageTest.php b/Tests/Uploader/Chunk/Storage/FilesystemStorageTest.php index 1df65ea..8e54cc4 100644 --- a/Tests/Uploader/Chunk/Storage/FilesystemStorageTest.php +++ b/Tests/Uploader/Chunk/Storage/FilesystemStorageTest.php @@ -2,11 +2,10 @@ namespace Oneup\UploaderBundle\Tests\Uploader\Chunk\Storage; -use Symfony\Component\Finder\Finder; use Symfony\Component\Filesystem\Filesystem; use Oneup\UploaderBundle\Uploader\Chunk\Storage\FilesystemStorage; -class FilesystemStorageTest extends \PHPUnit_Framework_TestCase +class FilesystemStorageTest extends ChunkStorageTest { protected $tmpDir; @@ -19,81 +18,14 @@ class FilesystemStorageTest extends \PHPUnit_Framework_TestCase $system->mkdir($tmpDir); $this->tmpDir = $tmpDir; - } - - public function tearDown() - { - $system = new Filesystem(); - $system->remove($this->tmpDir); - } - - public function testExistanceOfTmpDir() - { - $this->assertTrue(is_dir($this->tmpDir)); - $this->assertTrue(is_writeable($this->tmpDir)); - } - - public function testFillOfTmpDir() - { - $finder = new Finder(); - $finder->in($this->tmpDir); - - $numberOfFiles = 10; - - $this->fillDirectory($numberOfFiles); - $this->assertCount($numberOfFiles, $finder); - } - - public function testChunkCleanup() - { - // get a manager configured with a max-age of 5 minutes - $maxage = 5 * 60; - $manager = $this->getStorage(); - $numberOfFiles = 10; - - $finder = new Finder(); - $finder->in($this->tmpDir); - - $this->fillDirectory($numberOfFiles); - $this->assertCount(10, $finder); - - $manager->clear($maxage); - - $this->assertTrue(is_dir($this->tmpDir)); - $this->assertTrue(is_writeable($this->tmpDir)); - - $this->assertCount(5, $finder); - - foreach ($finder as $file) { - $this->assertGreaterThanOrEqual(time() - $maxage, filemtime($file)); - } - } - - public function testClearIfDirectoryDoesNotExist() - { - $filesystem = new Filesystem(); - $filesystem->remove($this->tmpDir); - - $manager = $this->getStorage(); - $manager->clear(10); - - // yey, no exception - $this->assertTrue(true); - } - - protected function getStorage() - { - return new FilesystemStorage(array( + $this->storage = new FilesystemStorage(array( 'directory' => $this->tmpDir )); } - protected function fillDirectory($number) + public function tearDown() { $system = new Filesystem(); - - for ($i = 0; $i < $number; $i ++) { - $system->touch(sprintf('%s/%s', $this->tmpDir, uniqid()), time() - $i * 60); - } + $system->remove($this->tmpDir); } } diff --git a/Tests/Uploader/Chunk/Storage/GaufretteStorageTest.php b/Tests/Uploader/Chunk/Storage/GaufretteStorageTest.php new file mode 100644 index 0000000..375d450 --- /dev/null +++ b/Tests/Uploader/Chunk/Storage/GaufretteStorageTest.php @@ -0,0 +1,43 @@ +<?php + +namespace Oneup\UploaderBundle\Tests\Uploader\Chunk\Storage; + +use Oneup\UploaderBundle\Uploader\Chunk\Storage\GaufretteStorage; +use Symfony\Component\Filesystem\Filesystem; +use Gaufrette\Adapter\Local as Adapter; +use Gaufrette\Filesystem as GaufretteFilesystem; + +class GaufretteStorageTest extends ChunkStorageTest +{ + protected $parentDir; + protected $chunkKey = 'chunks'; + protected $chunkDir; + + public function setUp() + { + // create a cache dir + $parentDir = sprintf('/tmp/%s', uniqid()); + + $system = new Filesystem(); + $system->mkdir($parentDir); + + $this->parentDir = $parentDir; + + $adapter = new Adapter($this->parentDir, true); + + $filesystem = new GaufretteFilesystem($adapter); + + $this->storage = new GaufretteStorage($filesystem, 100000, null, $this->chunkKey); + $this->tmpDir = $this->parentDir.'/'.$this->chunkKey; + + $system->mkdir($this->tmpDir); + + } + + public function tearDown() + { + $system = new Filesystem(); + $system->remove($this->parentDir); + } + +} diff --git a/Uploader/Chunk/Storage/GaufretteStorage.php b/Uploader/Chunk/Storage/GaufretteStorage.php index 6c4cd04..5c641d0 100644 --- a/Uploader/Chunk/Storage/GaufretteStorage.php +++ b/Uploader/Chunk/Storage/GaufretteStorage.php @@ -40,7 +40,7 @@ class GaufretteStorage extends StreamManager implements ChunkStorageInterface $prefix = $prefix ? :$this->prefix; $matches = $this->filesystem->listKeys($prefix); - $limit = time()+$maxAge; + $now = time(); $toDelete = array(); // Collect the directories that are old, @@ -48,14 +48,14 @@ class GaufretteStorage extends StreamManager implements ChunkStorageInterface // but after the files are deleted the dirs // would remain foreach ($matches['dirs'] as $key) { - if ($limit < $this->filesystem->mtime($key)) { + if ($maxAge <= $now-$this->filesystem->mtime($key)) { $toDelete[] = $key; } } // The same directory is returned for every file it contains array_unique($toDelete); foreach ($matches['keys'] as $key) { - if ($limit < $this->filesystem->mtime($key)) { + if ($maxAge <= $now-$this->filesystem->mtime($key)) { $this->filesystem->delete($key); } }
0
d4355f62565163f25e4637860a431ce5e721f898
1up-lab/OneupUploaderBundle
Added doc blocks for StorageInterface.
commit d4355f62565163f25e4637860a431ce5e721f898 Author: Jim Schmid <[email protected]> Date: Tue Aug 13 16:03:50 2013 +0200 Added doc blocks for StorageInterface. diff --git a/Uploader/Storage/StorageInterface.php b/Uploader/Storage/StorageInterface.php index 090db1a..79fb3ae 100644 --- a/Uploader/Storage/StorageInterface.php +++ b/Uploader/Storage/StorageInterface.php @@ -6,5 +6,12 @@ use Symfony\Component\HttpFoundation\File\File; interface StorageInterface { + /** + * Uploads a File instance to the configured storage. + * + * @param File $file + * @param string $name + * @param string $path + */ public function upload(File $file, $name, $path = null); }
0
5f132712944010de0c2b119f708e9eee96d6c5ec
1up-lab/OneupUploaderBundle
Added cache dir settings and improved test matrix
commit 5f132712944010de0c2b119f708e9eee96d6c5ec Author: David Greminger <[email protected]> Date: Thu Dec 10 10:54:08 2015 +0100 Added cache dir settings and improved test matrix diff --git a/.travis.yml b/.travis.yml index 0af42e4..1b0403c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -9,25 +9,36 @@ php: - hhvm env: + - SYMFONY_VERSION=2.3.* - SYMFONY_VERSION=2.7.* + - SYMFONY_VERSION=2.8.* + +cache: + directories: + - $COMPOSER_CACHE_DIR matrix: + allow_failures: + - php: hhvm + - env: SYMFONY_VERSION=dev-master + include: - php: 5.6 env: SYMFONY_VERSION=2.3.* + - php: 5.6 + env: SYMFONY_VERSION=2.4.* + - php: 5.6 + env: SYMFONY_VERSION=2.5.* - php: 5.6 env: SYMFONY_VERSION=2.6.* - php: 5.6 env: SYMFONY_VERSION=2.7.* - php: 5.6 - env: SYMFONY_VERSION=2.8.*@dev + env: SYMFONY_VERSION=2.8.* - php: 5.6 - env: SYMFONY_VERSION="3.0.x-dev as 2.8" - allow_failures: - - php: 7.0 - - php: hhvm - - env: SYMFONY_VERSION=2.8.*@dev - - env: SYMFONY_VERSION="3.0.x-dev as 2.8" + env: SYMFONY_VERSION=3.0.* + - php: 5.6 + env: SYMFONY_VERSION=dev-master before_script: - composer selfupdate
0
1cb71fe663a68e095b6a831c34dd7c9625d41b3d
1up-lab/OneupUploaderBundle
Fixed a few bugs. This is cleanup commit before the whole Orphenaga-System is getting refactored.
commit 1cb71fe663a68e095b6a831c34dd7c9625d41b3d Author: Jim Schmid <[email protected]> Date: Wed Mar 13 13:09:29 2013 +0100 Fixed a few bugs. This is cleanup commit before the whole Orphenaga-System is getting refactored. diff --git a/Controller/UploaderController.php b/Controller/UploaderController.php index 7c2b423..2ad0377 100644 --- a/Controller/UploaderController.php +++ b/Controller/UploaderController.php @@ -14,13 +14,14 @@ class UploaderController implements UploadControllerInterface protected $namer; protected $storage; - public function __construct($request, $namer, $storage, $config, $dispatcher) + public function __construct($request, $namer, $storage, $dispatcher, $type, $config) { $this->request = $request; $this->namer = $namer; $this->storage = $storage; $this->config = $config; $this->dispatcher = $dispatcher; + $this->type = $type; } public function upload() @@ -39,7 +40,7 @@ class UploaderController implements UploadControllerInterface { $name = $this->namer->name($file, $this->config['directory_prefix']); - $postUploadEvent = new PostUploadEvent($file, $this->request, array( + $postUploadEvent = new PostUploadEvent($file, $this->request, $this->type, array( 'use_orphanage' => $this->config['use_orphanage'], 'file_name' => $name, )); @@ -50,7 +51,7 @@ class UploaderController implements UploadControllerInterface $uploaded = $this->storage->upload($file, $name); // dispatch post upload event - $postPersistEvent = new PostPersistEvent($uploaded, $this->request); + $postPersistEvent = new PostPersistEvent($uploaded, $this->request, $this->type); $this->dispatcher->dispatch(UploadEvents::POST_PERSIST, $postPersistEvent); } } diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index 5f8cd6d..e9e67b3 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -90,11 +90,12 @@ class OneupUploaderExtension extends Extension // add the correspoding storage service as argument ->addArgument(new Reference($mapping['storage'])) - // after all, add the config as argument - ->addArgument($mapping) - // we need the EventDispatcher for post upload events ->addArgument(new Reference('event_dispatcher')) + + // after all, add the type and config as argument + ->addArgument($type) + ->addArgument($mapping) ->addTag('oneup_uploader.routable', array('type' => $type)) ->setScope('request') diff --git a/Event/PostPersistEvent.php b/Event/PostPersistEvent.php index e4716c2..dac4fc9 100644 --- a/Event/PostPersistEvent.php +++ b/Event/PostPersistEvent.php @@ -11,11 +11,13 @@ class PostPersistEvent extends Event { protected $file; protected $request; + protected $type; - public function __construct(File $file, Request $request) + public function __construct(File $file, Request $request, $type) { $this->file = $file; $this->request = $request; + $this->type = $type; } public function getFile() @@ -27,4 +29,9 @@ class PostPersistEvent extends Event { return $this->request; } + + public function getType() + { + return $this->type; + } } \ No newline at end of file diff --git a/Event/PostUploadEvent.php b/Event/PostUploadEvent.php index 709095b..eb88843 100644 --- a/Event/PostUploadEvent.php +++ b/Event/PostUploadEvent.php @@ -11,11 +11,14 @@ class PostUploadEvent extends Event { protected $file; protected $request; + protected $type; + protected $options; - public function __construct(File $file, Request $request, array $options = array()) + public function __construct(File $file, Request $request, $type, array $options = array()) { $this->file = $file; $this->request = $request; + $this->type = $type; $this->options = $options; } @@ -29,6 +32,11 @@ class PostUploadEvent extends Event return $this->request; } + public function getType() + { + return $this->type; + } + public function getOptions() { return $this->options; diff --git a/EventListener/OrphanageListener.php b/EventListener/OrphanageListener.php index a7d909f..15bd7c9 100644 --- a/EventListener/OrphanageListener.php +++ b/EventListener/OrphanageListener.php @@ -24,7 +24,7 @@ class OrphanageListener implements EventSubscriberInterface $request = $event->getRequest(); $file = $event->getFile(); - if(!$options['use_orphanage']) + if(!array_key_exists('use_orphanage', $options) || !$options['use_orphanage']) return; $this->orphanage->addFile($file, $options['file_name']); diff --git a/Uploader/Orphanage/Orphanage.php b/Uploader/Orphanage/Orphanage.php index 0109f1f..4a7971d 100644 --- a/Uploader/Orphanage/Orphanage.php +++ b/Uploader/Orphanage/Orphanage.php @@ -27,11 +27,6 @@ class Orphanage implements OrphanageInterface return $file->move($this->getPath(), $name); } - public function removeFile(File $file) - { - - } - public function getFiles() {
0
72d462607f31c92c02ad8340c6eb35fc8650bd6e
1up-lab/OneupUploaderBundle
Added a pre upload event. This event will be given an instance of UploadedFile instead of a moved file. Addresses #21.
commit 72d462607f31c92c02ad8340c6eb35fc8650bd6e Author: Jim Schmid <[email protected]> Date: Fri Jun 21 23:22:34 2013 +0200 Added a pre upload event. This event will be given an instance of UploadedFile instead of a moved file. Addresses #21. diff --git a/Controller/AbstractController.php b/Controller/AbstractController.php index 1f6b0dd..ab4db65 100644 --- a/Controller/AbstractController.php +++ b/Controller/AbstractController.php @@ -8,6 +8,7 @@ use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\Request; use Oneup\UploaderBundle\UploadEvents; +use Oneup\UploaderBundle\Event\PreUploadEvent; use Oneup\UploaderBundle\Event\PostPersistEvent; use Oneup\UploaderBundle\Event\PostUploadEvent; use Oneup\UploaderBundle\Event\ValidationEvent; @@ -42,13 +43,13 @@ abstract class AbstractController * @param UploadedFile The file to upload * @param response A response object. * @param request The request object. - * - * @return File the actual file */ protected function handleUpload(UploadedFile $file, ResponseInterface $response, Request $request) { $this->validate($file); + $this->dispatchPreUploadEvent($file, $response, $request); + // no error happend, proceed $namer = $this->container->get($this->config['namer']); $name = $namer->name($file); @@ -56,7 +57,24 @@ abstract class AbstractController // perform the real upload $uploaded = $this->storage->upload($file, $name); - $this->dispatchEvents($uploaded, $response, $request); + $this->dispatchPostEvents($uploaded, $response, $request); + } + + /** + * This function is a helper function which dispatches pre upload event + * + * @param uploaded The uploaded file. + * @param response A response object. + * @param request The request object. + */ + protected function dispatchPreUploadEvent(UploadedFile $uploaded, ResponseInterface $response, Request $request) + { + $dispatcher = $this->container->get('event_dispatcher'); + + // dispatch pre upload event (both the specific and the general) + $postUploadEvent = new PreUploadEvent($uploaded, $response, $request, $this->type, $this->config); + $dispatcher->dispatch(UploadEvents::PRE_UPLOAD, $postUploadEvent); + $dispatcher->dispatch(sprintf('%s.%s', UploadEvents::PRE_UPLOAD, $this->type), $postUploadEvent); } /** @@ -67,7 +85,7 @@ abstract class AbstractController * @param response A response object. * @param request The request object. */ - protected function dispatchEvents($uploaded, ResponseInterface $response, Request $request) + protected function dispatchPostEvents($uploaded, ResponseInterface $response, Request $request) { $dispatcher = $this->container->get('event_dispatcher'); diff --git a/Event/PreUploadEvent.php b/Event/PreUploadEvent.php new file mode 100644 index 0000000..e277365 --- /dev/null +++ b/Event/PreUploadEvent.php @@ -0,0 +1,50 @@ +<?php + +namespace Oneup\UploaderBundle\Event; + +use Symfony\Component\EventDispatcher\Event; +use Symfony\Component\HttpFoundation\Request; +use Oneup\UploaderBundle\Uploader\Response\ResponseInterface; + +class PreUploadEvent extends Event +{ + protected $file; + protected $request; + protected $type; + protected $response; + protected $config; + + public function __construct($file, ResponseInterface $response, Request $request, $type, array $config) + { + $this->file = $file; + $this->request = $request; + $this->response = $response; + $this->type = $type; + $this->config = $config; + } + + public function getFile() + { + return $this->file; + } + + public function getRequest() + { + return $this->request; + } + + public function getType() + { + return $this->type; + } + + public function getResponse() + { + return $this->response; + } + + public function getConfig() + { + return $this->config; + } +} diff --git a/Resources/doc/events.md b/Resources/doc/events.md index a789691..5fb6c4e 100644 --- a/Resources/doc/events.md +++ b/Resources/doc/events.md @@ -3,6 +3,7 @@ OneupUploaderBundle Events For a list of general Events, you can always have a look at the `UploadEvents.php` file in the root of this bundle. +* `oneup_uploader.pre_upload` Will be fired after validation but before naming and moving the uploaded file. * `oneup_uploader.post_upload` Will be dispatched after a file has been uploaded and moved. * `oneup_uploader.post_persist` The same as `oneup_uploader.post_upload` but will only be dispatched if no `Orphanage` is used. @@ -12,8 +13,10 @@ In case you are using chunked uploads on your frontend, you can listen to: Moreover this bundles also dispatches some special kind of generic events you can listen to. +* `oneup_uploader.pre_upload.{mapping}` * `oneup_uploader.post_upload.{mapping}` * `oneup_uploader.post_persist.{mapping}` +* `oneup_uploader.post_chunk_upload.{mapping}` The `{mapping}` part is the key of your configured mapping. The examples in this documentation always uses the mapping key `gallery`. So the dispatched event would be called `oneup_uploader.post_upload.gallery`. Using these generic events can save you some time and coding lines, as you don't have to check for the correct type in the `EventListener`. diff --git a/Tests/Controller/AbstractUploadTest.php b/Tests/Controller/AbstractUploadTest.php index 37c2b67..1024613 100644 --- a/Tests/Controller/AbstractUploadTest.php +++ b/Tests/Controller/AbstractUploadTest.php @@ -4,6 +4,7 @@ namespace Oneup\UploaderBundle\Tests\Controller; use Oneup\UploaderBundle\Tests\Controller\AbstractControllerTest; use Oneup\UploaderBundle\UploadEvents; +use Oneup\UploaderBundle\Event\PreUploadEvent; use Oneup\UploaderBundle\Event\PostUploadEvent; abstract class AbstractUploadTest extends AbstractControllerTest @@ -47,9 +48,19 @@ abstract class AbstractUploadTest extends AbstractControllerTest // event data $me = $this; $uploadCount = 0; + $preValidation = 1; + + $dispatcher->addListener(UploadEvents::PRE_UPLOAD, function(PreUploadEvent $event) use (&$uploadCount, &$me, &$preValidation) { + $preValidation -= 2; - $dispatcher->addListener(UploadEvents::POST_UPLOAD, function(PostUploadEvent $event) use (&$uploadCount, &$me) { + $file = $event->getFile(); + + $me->assertInstanceOf('Symfony\Component\HttpFoundation\File\UploadedFile', $file); + }); + + $dispatcher->addListener(UploadEvents::POST_UPLOAD, function(PostUploadEvent $event) use (&$uploadCount, &$me, &$preValidation) { ++ $uploadCount; + $preValidation *= -1; $file = $event->getFile(); @@ -61,5 +72,6 @@ abstract class AbstractUploadTest extends AbstractControllerTest $this->assertCount(1, $this->getUploadedFiles()); $this->assertEquals($uploadCount, count($this->getUploadedFiles())); + $this->assertEquals(1, $preValidation); } } diff --git a/UploadEvents.php b/UploadEvents.php index 12b97a6..aed3341 100644 --- a/UploadEvents.php +++ b/UploadEvents.php @@ -4,8 +4,9 @@ namespace Oneup\UploaderBundle; final class UploadEvents { - const POST_PERSIST = 'oneup_uploader.post_persist'; + const PRE_UPLOAD = 'oneup_uploader.pre_upload'; const POST_UPLOAD = 'oneup_uploader.post_upload'; + const POST_PERSIST = 'oneup_uploader.post_persist'; const POST_CHUNK_UPLOAD = 'oneup_uploader.post_chunk_upload'; const VALIDATION = 'oneup_uploader.validation'; }
0
04db98f3e5a9d1a14ea381e003e3ec40c8a99f45
1up-lab/OneupUploaderBundle
Use the blueimp error handler in the tests.
commit 04db98f3e5a9d1a14ea381e003e3ec40c8a99f45 Author: Jim Schmid <[email protected]> Date: Sun Jul 14 23:55:12 2013 +0200 Use the blueimp error handler in the tests. diff --git a/Tests/App/config/config.yml b/Tests/App/config/config.yml index 77da381..5c31e2c 100644 --- a/Tests/App/config/config.yml +++ b/Tests/App/config/config.yml @@ -103,12 +103,14 @@ oneup_uploader: frontend: blueimp storage: directory: %kernel.root_dir%/cache/%kernel.environment%/upload + error_handler: oneup_uploader.error_handler.blueimp blueimp_validation: frontend: blueimp max_size: 256 storage: directory: %kernel.root_dir%/cache/%kernel.environment%/upload + error_handler: oneup_uploader.error_handler.blueimp allowed_extensions: [ "ok" ] disallowed_extensions: [ "fail" ] allowed_mimetypes: [ "image/jpg", "text/plain" ] diff --git a/Uploader/ErrorHandler/BlueimpErrorHandler.php b/Uploader/ErrorHandler/BlueimpErrorHandler.php index 299dae1..69836c3 100644 --- a/Uploader/ErrorHandler/BlueimpErrorHandler.php +++ b/Uploader/ErrorHandler/BlueimpErrorHandler.php @@ -16,6 +16,6 @@ class BlueimpErrorHandler implements ErrorHandlerInterface $message = $exception->getMessage(); } - $response->addToOffset(array('error' => $message), 'files'); + $response->addToOffset('files', array('error' => $message)); } }
0
70d745fed42b4744e70a50c4dfb2dd3a70ea712c
1up-lab/OneupUploaderBundle
Use the EventDispatcher in AbstractControllerValidationTest.
commit 70d745fed42b4744e70a50c4dfb2dd3a70ea712c Author: Jim Schmid <[email protected]> Date: Mon Apr 22 18:50:31 2013 +0200 Use the EventDispatcher in AbstractControllerValidationTest. diff --git a/Tests/Controller/AbstractControllerValidationTest.php b/Tests/Controller/AbstractControllerValidationTest.php index b066e3b..348c7a2 100644 --- a/Tests/Controller/AbstractControllerValidationTest.php +++ b/Tests/Controller/AbstractControllerValidationTest.php @@ -122,7 +122,32 @@ abstract class AbstractControllerValidationTest extends \PHPUnit_Framework_TestC protected function getContainerMock() { - return $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); + $mock = $this->getMock('Symfony\Component\DependencyInjection\ContainerInterface'); + $mock + ->expects($this->any()) + ->method('get') + ->will($this->returnCallback(array($this, 'containerGetCb'))) + ; + + return $mock; + } + + public function containerGetCb($inp) + { + if($inp == 'event_dispatcher') + return $this->getEventDispatcherMock(); + } + + protected function getEventDispatcherMock() + { + $mock = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface'); + $mock + ->expects($this->any()) + ->method('dispatch') + ->will($this->returnValue(true)) + ; + + return $mock; } protected function getStorageMock()
0
2b98963842287be1f7e1c44befbb59148d66b2d9
1up-lab/OneupUploaderBundle
Fixed an xml property in a sample configuration.
commit 2b98963842287be1f7e1c44befbb59148d66b2d9 Author: Jim Schmid <[email protected]> Date: Thu Feb 6 13:12:08 2014 +0100 Fixed an xml property in a sample configuration. diff --git a/Resources/doc/custom_logic.md b/Resources/doc/custom_logic.md index a42926c..88c6d71 100644 --- a/Resources/doc/custom_logic.md +++ b/Resources/doc/custom_logic.md @@ -33,7 +33,7 @@ And register it in your `services.xml`. ```xml <services> - <service id="acme_hello.upload_listener" class="Acme\HelloBundle\EventListener"> + <service id="acme_hello.upload_listener" class="Acme\HelloBundle\EventListener\UploadListener"> <argument type="service" id="doctrine" /> <tag name="kernel.event_listener" event="oneup_uploader.post_persist" method="onUpload" /> </service>
0
d2049802deb5eb1e8621903dc98fe099458b1268
1up-lab/OneupUploaderBundle
Changes to 1.4
commit d2049802deb5eb1e8621903dc98fe099458b1268 Author: David Greminger <[email protected]> Date: Mon Jan 4 11:43:36 2016 +0100 Changes to 1.4 diff --git a/Resources/doc/index.md b/Resources/doc/index.md index 2e90a51..f5d2e21 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -5,7 +5,7 @@ The OneupUploaderBundle is a Symfony2 bundle developed and tested for versions 2 ## Prerequisites -This bundle is tested using Symfony2 versions 2.1+. +This bundle is tested using Symfony2 versions 2.4+. ### Translations If you wish to use the default texts provided with this bundle, you have to make sure that you have translator @@ -34,7 +34,7 @@ Add OneupUploaderBundle to your composer.json using the following construct: ```js { "require": { - "oneup/uploader-bundle": "~1.3" + "oneup/uploader-bundle": "~1.4" } } ```
0
e91f3a76464f340191cc3f3ccbecbe37d2f36971
1up-lab/OneupUploaderBundle
Marked some tests skipped if directories mismatch. Strangly on my machine the function tempnam returns something different than expected. tempnam('/foo', 'bar'); returns a file located in /private/foo. The way this test works does not allow this behaviour. This is why we test this condition and mark the test skipped.
commit e91f3a76464f340191cc3f3ccbecbe37d2f36971 Author: Jim Schmid <[email protected]> Date: Mon Oct 14 19:56:20 2013 +0200 Marked some tests skipped if directories mismatch. Strangly on my machine the function tempnam returns something different than expected. tempnam('/foo', 'bar'); returns a file located in /private/foo. The way this test works does not allow this behaviour. This is why we test this condition and mark the test skipped. diff --git a/Tests/Uploader/Storage/GaufretteOrphanageStorageTest.php b/Tests/Uploader/Storage/GaufretteOrphanageStorageTest.php index bc3a671..418298c 100644 --- a/Tests/Uploader/Storage/GaufretteOrphanageStorageTest.php +++ b/Tests/Uploader/Storage/GaufretteOrphanageStorageTest.php @@ -28,6 +28,10 @@ class GaufretteOrphanageStorageTest extends OrphanageTest $this->tempDirectory = $this->realDirectory . '/' . $this->orphanageKey; $this->payloads = array(); + if (!$this->checkIfTempnameMatchesAfterCreation()) { + $this->markTestSkipped('Temporary directories do not match'); + } + $filesystem = new \Symfony\Component\Filesystem\Filesystem(); $filesystem->mkdir($this->realDirectory); $filesystem->mkdir($this->chunkDirectory); @@ -107,4 +111,8 @@ class GaufretteOrphanageStorageTest extends OrphanageTest $this->assertCount($this->numberOfPayloads, $finder); } + public function checkIfTempnameMatchesAfterCreation() + { + return strpos(tempnam($this->chunkDirectory, 'uploader'), $this->chunkDirectory) === 0; + } }
0
7c0f4bb6c13c6f73bfe62b55d3c564f8e526a517
1up-lab/OneupUploaderBundle
Merge pull request #227 from p1rox/master Fixed typo in documentation
commit 7c0f4bb6c13c6f73bfe62b55d3c564f8e526a517 (from 9fa868f0f92759d421787dea82c53274e83063b1) Merge: 9fa868f 2138609 Author: David Greminger <[email protected]> Date: Sun Feb 14 15:11:32 2016 +0100 Merge pull request #227 from p1rox/master Fixed typo in documentation diff --git a/Resources/doc/custom_logic.md b/Resources/doc/custom_logic.md index 6fea373..1aa1cfd 100644 --- a/Resources/doc/custom_logic.md +++ b/Resources/doc/custom_logic.md @@ -50,7 +50,7 @@ And register it in your `services.xml`. services: acme_hello.upload_listener: class: AppBundle\EventListener\UploadListener - argument: ["@doctrine.orm.entity_manager"] + arguments: ["@doctrine.orm.entity_manager"] tags: - { name: kernel.event_listener, event: oneup_uploader.post_persist, method: onUpload } ```
0
8a40040e78546ba95819480bc64e167827ad42e3
1up-lab/OneupUploaderBundle
Add Exception about the ValidationEvent It does not contain the response. (Is there any reason by the way)?
commit 8a40040e78546ba95819480bc64e167827ad42e3 Author: Schyzophrenic <[email protected]> Date: Sat May 10 20:51:19 2014 +0200 Add Exception about the ValidationEvent It does not contain the response. (Is there any reason by the way)? diff --git a/Resources/doc/response.md b/Resources/doc/response.md index bfef2ca..39d9968 100644 --- a/Resources/doc/response.md +++ b/Resources/doc/response.md @@ -1,7 +1,7 @@ Return custom data to the Frontend ================================== -There are some use cases where you need custom data to be returned to the frontend. For example the id of a generated Doctrine Entity or the like. To cover this, you can use `UploaderResponse` passed through all `Events`. +There are some use cases where you need custom data to be returned to the frontend. For example the id of a generated Doctrine Entity or the like. To cover this, you can use `UploaderResponse` passed through all `Events` (except the `ValidationEvent`). ```php namespace Acme\HelloBundle\EventListener; @@ -33,4 +33,4 @@ $response->setError($msg); > Do not use the keys `success` and `error` if you provide custom data, they will be overwritten by the internal properties of `UploaderResponse`. -Due to limitations of the `\ArrayAccess` regarding multi-dimensional array access, there is a method `addToOffset` which can be used to attach values to specific pathes in the array. \ No newline at end of file +Due to limitations of the `\ArrayAccess` regarding multi-dimensional array access, there is a method `addToOffset` which can be used to attach values to specific pathes in the array.
0
128180053ee6fdf0cee5d72139608fd1be75a93e
1up-lab/OneupUploaderBundle
Configure a route prefix You can define a route prefix per mapping which will be used for the route generation. This is especially usefull if you have different mappings assinged to different firewall areas. Fixed #94.
commit 128180053ee6fdf0cee5d72139608fd1be75a93e Author: Jim Schmid <[email protected]> Date: Wed Mar 5 07:22:04 2014 +0100 Configure a route prefix You can define a route prefix per mapping which will be used for the route generation. This is especially usefull if you have different mappings assinged to different firewall areas. Fixed #94. diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 34df9d3..3374889 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -74,6 +74,7 @@ class Configuration implements ConfigurationInterface ->scalarNode('sync_buffer_size')->defaultValue('100K')->end() ->end() ->end() + ->scalarNode('route_prefix')->defaultValue('')->end() ->arrayNode('allowed_mimetypes') ->prototype('scalar')->end() ->end() diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index 1d52140..480d8ec 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -76,7 +76,8 @@ class OneupUploaderExtension extends Extension return array($controllerName, array( 'enable_progress' => $mapping['enable_progress'], - 'enable_cancelation' => $mapping['enable_cancelation'] + 'enable_cancelation' => $mapping['enable_cancelation'], + 'route_prefix' => $mapping['route_prefix'] )); } diff --git a/Routing/RouteLoader.php b/Routing/RouteLoader.php index a464dc2..fad6c0f 100644 --- a/Routing/RouteLoader.php +++ b/Routing/RouteLoader.php @@ -30,14 +30,14 @@ class RouteLoader extends Loader $options = $controllerArray[1]; $upload = new Route( - sprintf('/_uploader/%s/upload', $type), + sprintf('%s/_uploader/%s/upload', $options['route_prefix'], $type), array('_controller' => $service . ':upload', '_format' => 'json'), array('_method' => 'POST') ); if ($options['enable_progress'] === true) { $progress = new Route( - sprintf('/_uploader/%s/progress', $type), + sprintf('%s/_uploader/%s/progress', $options['route_prefix'], $type), array('_controller' => $service . ':progress', '_format' => 'json'), array('_method' => 'POST') ); @@ -47,7 +47,7 @@ class RouteLoader extends Loader if ($options['enable_cancelation'] === true) { $progress = new Route( - sprintf('/_uploader/%s/cancel', $type), + sprintf('%s/_uploader/%s/cancel', $options['route_prefix'], $type), array('_controller' => $service . ':cancel', '_format' => 'json'), array('_method' => 'POST') ); diff --git a/Tests/Routing/RouteLoaderTest.php b/Tests/Routing/RouteLoaderTest.php index 08d433c..4058039 100644 --- a/Tests/Routing/RouteLoaderTest.php +++ b/Tests/Routing/RouteLoaderTest.php @@ -14,11 +14,13 @@ class RouteLoaderTest extends \PHPUnit_Framework_TestCase $routeLoader = new RouteLoader(array( 'cat' => array($cat, array( 'enable_progress' => false, - 'enable_cancelation' => false + 'enable_cancelation' => false, + 'route_prefix' => '' )), 'dog' => array($dog, array( 'enable_progress' => true, - 'enable_cancelation' => true + 'enable_cancelation' => true, + 'route_prefix' => '' )), )); @@ -35,4 +37,28 @@ class RouteLoaderTest extends \PHPUnit_Framework_TestCase $this->assertEquals($route->getRequirement('_method'), 'POST'); } } + + public function testPrefixedRoutes() + { + $prefix = '/admin'; + $cat = 'GrumpyCatController'; + + $routeLoader = new RouteLoader(array( + 'cat' => array($cat, array( + 'enable_progress' => false, + 'enable_cancelation' => false, + 'route_prefix' => $prefix + )) + )); + + $routes = $routeLoader->load(null); + + foreach ($routes as $route) { + $this->assertInstanceOf('Symfony\Component\Routing\Route', $route); + $this->assertEquals($route->getDefault('_format'), 'json'); + $this->assertEquals($route->getRequirement('_method'), 'POST'); + + $this->assertEquals(0, strpos($route->getPath(), $prefix)); + } + } }
0
3361b73c806eb3d952a17b0e6d50e77eee9e8d26
1up-lab/OneupUploaderBundle
Merge pull request #27 from 1up-lab/error-handler Proper error handling.
commit 3361b73c806eb3d952a17b0e6d50e77eee9e8d26 (from 9dbd9056dfe403ce6f1273d2d75fe814d517731a) Merge: 9dbd905 1e91e1e Author: Jim Schmid <[email protected]> Date: Mon Jul 15 03:00:36 2013 -0700 Merge pull request #27 from 1up-lab/error-handler Proper error handling. diff --git a/Controller/AbstractController.php b/Controller/AbstractController.php index c72861e..865517d 100644 --- a/Controller/AbstractController.php +++ b/Controller/AbstractController.php @@ -4,7 +4,6 @@ namespace Oneup\UploaderBundle\Controller; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\DependencyInjection\ContainerInterface; -use Symfony\Component\HttpFoundation\File\Exception\UploadException; use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\Request; @@ -15,7 +14,7 @@ use Oneup\UploaderBundle\Event\PostUploadEvent; use Oneup\UploaderBundle\Event\ValidationEvent; use Oneup\UploaderBundle\Uploader\Storage\StorageInterface; use Oneup\UploaderBundle\Uploader\Response\ResponseInterface; -use Oneup\UploaderBundle\Uploader\Exception\ValidationException; +use Oneup\UploaderBundle\Uploader\ErrorHandler\ErrorHandlerInterface; abstract class AbstractController { @@ -24,8 +23,9 @@ abstract class AbstractController protected $config; protected $type; - public function __construct(ContainerInterface $container, StorageInterface $storage, array $config, $type) + public function __construct(ContainerInterface $container, StorageInterface $storage, ErrorHandlerInterface $errorHandler, array $config, $type) { + $this->errorHandler = $errorHandler; $this->container = $container; $this->storage = $storage; $this->config = $config; @@ -142,11 +142,6 @@ abstract class AbstractController $dispatcher = $this->container->get('event_dispatcher'); $event = new ValidationEvent($file, $this->config, $this->type); - try { - $dispatcher->dispatch(UploadEvents::VALIDATION, $event); - } catch (ValidationException $exception) { - // pass the exception one level up - throw new UploadException($exception->getMessage()); - } + $dispatcher->dispatch(UploadEvents::VALIDATION, $event); } } diff --git a/Controller/BlueimpController.php b/Controller/BlueimpController.php index 607797b..c0842a8 100644 --- a/Controller/BlueimpController.php +++ b/Controller/BlueimpController.php @@ -15,21 +15,18 @@ class BlueimpController extends AbstractChunkedController { $request = $this->container->get('request'); $response = new EmptyResponse(); - $files = $request->files; + $files = $request->files->get('files'); $chunked = !is_null($request->headers->get('content-range')); - foreach ($files as $file) { - $file = $file[0]; - + foreach ((array) $files as $file) { try { $chunked ? $this->handleChunkedUpload($file, $response, $request) : $this->handleUpload($file, $response, $request) ; } catch (UploadException $e) { - // return nothing - return new JsonResponse(array()); + $this->errorHandler->addException($response, $e); } } diff --git a/Controller/FancyUploadController.php b/Controller/FancyUploadController.php index c26f040..00858f6 100644 --- a/Controller/FancyUploadController.php +++ b/Controller/FancyUploadController.php @@ -20,8 +20,7 @@ class FancyUploadController extends AbstractController try { $uploaded = $this->handleUpload($file, $response, $request); } catch (UploadException $e) { - // return nothing - return new JsonResponse(array()); + $this->errorHandler->addException($response, $e); } } diff --git a/Controller/FineUploaderController.php b/Controller/FineUploaderController.php index 2fcfe00..a9dc1b1 100644 --- a/Controller/FineUploaderController.php +++ b/Controller/FineUploaderController.php @@ -31,6 +31,8 @@ class FineUploaderController extends AbstractChunkedController $response->setSuccess(false); $response->setError($translator->trans($e->getMessage(), array(), 'OneupUploaderBundle')); + $this->errorHandler->addException($response, $e); + // an error happended, return this error message. return new JsonResponse($response->assemble()); } diff --git a/Controller/MooUploadController.php b/Controller/MooUploadController.php index dbc75f6..8b6cce5 100644 --- a/Controller/MooUploadController.php +++ b/Controller/MooUploadController.php @@ -50,6 +50,8 @@ class MooUploadController extends AbstractChunkedController $response->setFinish(true); $response->setError(-1); + $this->errorHandler->addException($response, $e); + // return nothing return new JsonResponse($response->assemble()); } diff --git a/Controller/PluploadController.php b/Controller/PluploadController.php index 162f6a8..d2b6a8a 100644 --- a/Controller/PluploadController.php +++ b/Controller/PluploadController.php @@ -26,8 +26,7 @@ class PluploadController extends AbstractChunkedController $this->handleUpload($file, $response, $request) ; } catch (UploadException $e) { - // return nothing - return new JsonResponse(array()); + $this->errorHandler->addException($response, $e); } } diff --git a/Controller/UploadifyController.php b/Controller/UploadifyController.php index fe57183..de75cdd 100644 --- a/Controller/UploadifyController.php +++ b/Controller/UploadifyController.php @@ -20,8 +20,7 @@ class UploadifyController extends AbstractController try { $uploaded = $this->handleUpload($file, $response, $request); } catch (UploadException $e) { - // return nothing - return new JsonResponse(array()); + $this->errorHandler->addException($response, $e); } } diff --git a/Controller/YUI3Controller.php b/Controller/YUI3Controller.php index 5b1e98f..ac4760c 100644 --- a/Controller/YUI3Controller.php +++ b/Controller/YUI3Controller.php @@ -20,8 +20,7 @@ class YUI3Controller extends AbstractController try { $uploaded = $this->handleUpload($file, $response, $request); } catch (UploadException $e) { - // return nothing - return new JsonResponse(array()); + $this->errorHandler->addException($response, $e); } } diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 02085e0..cbf59dd 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -71,6 +71,7 @@ class Configuration implements ConfigurationInterface ->arrayNode('disallowed_mimetypes') ->prototype('scalar')->end() ->end() + ->scalarNode('error_handler')->defaultValue('oneup_uploader.error_handler.noop')->end() ->scalarNode('max_size')->defaultValue(\PHP_INT_MAX)->end() ->booleanNode('use_orphanage')->defaultFalse()->end() ->booleanNode('enable_progress')->defaultFalse()->end() diff --git a/DependencyInjection/OneupUploaderExtension.php b/DependencyInjection/OneupUploaderExtension.php index d1435fa..108394c 100644 --- a/DependencyInjection/OneupUploaderExtension.php +++ b/DependencyInjection/OneupUploaderExtension.php @@ -23,6 +23,7 @@ class OneupUploaderExtension extends Extension $loader->load('uploader.xml'); $loader->load('templating.xml'); $loader->load('validators.xml'); + $loader->load('errorhandler.xml'); if ($config['twig']) { $loader->load('twig.xml'); @@ -116,12 +117,15 @@ class OneupUploaderExtension extends Extension throw new ServiceNotFoundException('Empty controller class or name. If you really want to use a custom frontend implementation, be sure to provide a class and a name.'); } + $errorHandler = new Reference($mapping['error_handler']); + // create controllers based on mapping $container ->register($controllerName, $controllerType) ->addArgument(new Reference('service_container')) ->addArgument($storageService) + ->addArgument($errorHandler) ->addArgument($mapping) ->addArgument($key) @@ -129,8 +133,8 @@ class OneupUploaderExtension extends Extension ->setScope('request') ; - if($mapping['enable_progress'] || $mapping['enable_cancelation']) { - if(strnatcmp(phpversion(), '5.4.0') < 0) { + if ($mapping['enable_progress'] || $mapping['enable_cancelation']) { + if (strnatcmp(phpversion(), '5.4.0') < 0) { throw new InvalidArgumentException('You need to run PHP version 5.4.0 or above to use the progress/cancelation feature.'); } } diff --git a/README.md b/README.md index f72f219..3737275 100644 --- a/README.md +++ b/README.md @@ -31,8 +31,9 @@ The entry point of the documentation can be found in the file `Resources/docs/in Upgrade Notes ------------- -* Event names [changed](https://github.com/1up-lab/OneupUploaderBundle/commit/f5d5fe4b6f7b9a04ce633acbc9c94a2dd0e0d6be) in Version **0.9.3**, update your EventListener accordingly. +* Error management [changed](https://github.com/1up-lab/OneupUploaderBundle/pull/25) in Version **0.9.6**. You can now register an `ErrorHandler` per configured frontend. This comes bundled with some adjustments to the `blueimp` controller. More information is available in [the documentation](https://github.com/1up-lab/OneupUploaderBundle/blob/master/Resources/doc/custom_error_handler.md). * Event dispatching [changed](https://github.com/1up-lab/OneupUploaderBundle/commit/a408548b241f47af3539b2137c1817a21a51fde9) in Version **0.9.5**. The dispatching is now handled in the `upload*` functions. So if you have created your own implementation, be sure to remove the call to the `dispatchEvents` function, otherwise it will be called twice. Furthermore no `POST_UPLOAD` event will be fired anymore after uploading a chunk. You can get more information on this topic in the [documentation](https://github.com/1up-lab/OneupUploaderBundle/blob/master/Resources/doc/custom_logic.md#using-chunked-uploads). +* Event names [changed](https://github.com/1up-lab/OneupUploaderBundle/commit/f5d5fe4b6f7b9a04ce633acbc9c94a2dd0e0d6be) in Version **0.9.3**, update your EventListener accordingly. License ------- diff --git a/Resources/config/errorhandler.xml b/Resources/config/errorhandler.xml new file mode 100644 index 0000000..025e38a --- /dev/null +++ b/Resources/config/errorhandler.xml @@ -0,0 +1,16 @@ +<?xml version="1.0" encoding="utf-8" ?> +<container xmlns="http://symfony.com/schema/dic/services" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"> + + <parameters> + <parameter key="oneup_uploader.error_handler.noop.class">Oneup\UploaderBundle\Uploader\ErrorHandler\NoopErrorHandler</parameter> + <parameter key="oneup_uploader.error_handler.blueimp.class">Oneup\UploaderBundle\Uploader\ErrorHandler\BlueimpErrorHandler</parameter> + </parameters> + + <services> + <service id="oneup_uploader.error_handler.noop" class="%oneup_uploader.error_handler.noop.class%" public="false" /> + <service id="oneup_uploader.error_handler.blueimp" class="%oneup_uploader.error_handler.blueimp.class%" public="false" /> + </services> + +</container> diff --git a/Resources/config/validators.xml b/Resources/config/validators.xml index 8f435c5..5b2ffe0 100644 --- a/Resources/config/validators.xml +++ b/Resources/config/validators.xml @@ -8,7 +8,7 @@ <tag name="kernel.event_listener" event="oneup_uploader.validation" method="onValidate" /> </service> - <service id="oneup_uploader.validation_listener.allowed_extension" class="Oneup\UploaderBundle\EventListener\AllowedExtensionValidationListener" > + <service id="oneup_uploader.validation_listener.allowed_extension" class="Oneup\UploaderBundle\EventListener\AllowedExtensionValidationListener"> <tag name="kernel.event_listener" event="oneup_uploader.validation" method="onValidate" /> </service> diff --git a/Resources/doc/configuration_reference.md b/Resources/doc/configuration_reference.md index 144c091..52edb2d 100644 --- a/Resources/doc/configuration_reference.md +++ b/Resources/doc/configuration_reference.md @@ -29,6 +29,7 @@ oneup_uploader: disallowed_extensions: [] allowed_mimetypes: [] disallowed_mimetypes: [] + error_handler: oneup_uploader.error_handler.noop max_size: 9223372036854775807 use_orphanage: false enable_progress: false diff --git a/Resources/doc/custom_error_handler.md b/Resources/doc/custom_error_handler.md new file mode 100644 index 0000000..baf4507 --- /dev/null +++ b/Resources/doc/custom_error_handler.md @@ -0,0 +1,45 @@ +Error Handlers +============== + +Since version **0.9.6** of this bundle, the error management is using special error handler services. Its main purpose is to recieve an `UploadException` and the `Response` object and handle the error according to the frontend specification. You can define an own error handler for each entry in your configuration. The default handler is the so called `NoopErrorHandler` which does nothing, when recieving an exception. + +To create your own error handler, implement the `ErrorHandlerInterface` and add your custom logic. + +```php +<?php + +namespace Acme\DemoBundle\ErrorHandler; + +use Symfony\Component\HttpFoundation\File\Exception\UploadException; +use Oneup\UploaderBundle\Uploader\ErrorHandler\ErrorHandlerInterface; +use Oneup\UploaderBundle\Uploader\Response\ResponseInterface; + +class CustomErrorHandler implements ErrorHandlerInterface +{ + public function addException(ResponseInterface $response, UploadException $exception) + { + $message = $exception->getErrorMessage(); + $response['error'] = $message; + } +} + +``` + +Define a service for your class. + +```xml +<services> + <service id="acme_demo.custom_error_handler" class="Acme\DemoBundle\ErrorHandler\CustomErrorHandler" /> +</services> +``` + +And configure the mapping to use your shiny new service. + +```yml +oneup_uploader: + mappings: + gallery: + error_handler: acme_demo.custom_error_handler +``` + +**Note**: As of [9dbd905](https://github.com/1up-lab/OneupUploaderBundle/commit/9dbd9056dfe403ce6f1273d2d75fe814d517731a) only the `BlueimpErrorHandler` is implemented. If you know how to implement the error handlers for the other supported frontends, please create a pull request or drop me a note. \ No newline at end of file diff --git a/Resources/doc/index.md b/Resources/doc/index.md index d5b5721..4080132 100644 --- a/Resources/doc/index.md +++ b/Resources/doc/index.md @@ -118,12 +118,13 @@ some more advanced features. * [Using the Orphanage](orphanage.md) * [Use Gaufrette as storage layer](gaufrette_storage.md) * [Include your own Namer](custom_namer.md) -* [Testing this bundle](testing.md) +* [Use custom error handlers](custom_error_handler.md) * [Support a custom uploader](custom_uploader.md) * [Validate your uploads](custom_validator.md) * [General/Generic Events](events.md) * [Enable Session upload progress / upload cancelation](progress.md) * [Configuration Reference](configuration_reference.md) +* [Testing this bundle](testing.md) ## FAQ diff --git a/Resources/doc/response.md b/Resources/doc/response.md index 60807e6..bfef2ca 100644 --- a/Resources/doc/response.md +++ b/Resources/doc/response.md @@ -32,3 +32,5 @@ $response->setError($msg); ``` > Do not use the keys `success` and `error` if you provide custom data, they will be overwritten by the internal properties of `UploaderResponse`. + +Due to limitations of the `\ArrayAccess` regarding multi-dimensional array access, there is a method `addToOffset` which can be used to attach values to specific pathes in the array. \ No newline at end of file diff --git a/Tests/App/config/config.yml b/Tests/App/config/config.yml index 77da381..5c31e2c 100644 --- a/Tests/App/config/config.yml +++ b/Tests/App/config/config.yml @@ -103,12 +103,14 @@ oneup_uploader: frontend: blueimp storage: directory: %kernel.root_dir%/cache/%kernel.environment%/upload + error_handler: oneup_uploader.error_handler.blueimp blueimp_validation: frontend: blueimp max_size: 256 storage: directory: %kernel.root_dir%/cache/%kernel.environment%/upload + error_handler: oneup_uploader.error_handler.blueimp allowed_extensions: [ "ok" ] disallowed_extensions: [ "fail" ] allowed_mimetypes: [ "image/jpg", "text/plain" ] diff --git a/Tests/Controller/BlueimpTest.php b/Tests/Controller/BlueimpTest.php index 0d515b5..44e07bd 100644 --- a/Tests/Controller/BlueimpTest.php +++ b/Tests/Controller/BlueimpTest.php @@ -4,9 +4,74 @@ namespace Oneup\UploaderBundle\Tests\Controller; use Symfony\Component\HttpFoundation\File\UploadedFile; use Oneup\UploaderBundle\Tests\Controller\AbstractUploadTest; +use Oneup\UploaderBundle\UploadEvents; +use Oneup\UploaderBundle\Event\PreUploadEvent; +use Oneup\UploaderBundle\Event\PostUploadEvent; class BlueimpTest extends AbstractUploadTest { + public function testSingleUpload() + { + // assemble a request + $client = $this->client; + $endpoint = $this->helper->endpoint($this->getConfigKey()); + + $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getRequestFile()); + $response = $client->getResponse(); + + $this->assertTrue($response->isSuccessful()); + $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); + $this->assertCount(1, $this->getUploadedFiles()); + + foreach ($this->getUploadedFiles() as $file) { + $this->assertTrue($file->isFile()); + $this->assertTrue($file->isReadable()); + $this->assertEquals(128, $file->getSize()); + } + } + + public function testEvents() + { + $client = $this->client; + $endpoint = $this->helper->endpoint($this->getConfigKey()); + $dispatcher = $client->getContainer()->get('event_dispatcher'); + + // event data + $me = $this; + $uploadCount = 0; + $preValidation = 1; + + $dispatcher->addListener(UploadEvents::PRE_UPLOAD, function(PreUploadEvent $event) use (&$uploadCount, &$me, &$preValidation) { + $preValidation -= 2; + + $file = $event->getFile(); + $request = $event->getRequest(); + + // add a new key to the attribute list + $request->attributes->set('grumpy', 'cat'); + + $me->assertInstanceOf('Symfony\Component\HttpFoundation\File\UploadedFile', $file); + }); + + $dispatcher->addListener(UploadEvents::POST_UPLOAD, function(PostUploadEvent $event) use (&$uploadCount, &$me, &$preValidation) { + ++ $uploadCount; + $preValidation *= -1; + + $file = $event->getFile(); + $request = $event->getRequest(); + + $me->assertInstanceOf('Symfony\Component\HttpFoundation\File\File', $file); + $me->assertEquals(128, $file->getSize()); + $me->assertEquals('cat', $request->get('grumpy')); + }); + + $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getRequestFile()); + + $this->assertCount(1, $this->getUploadedFiles()); + $this->assertEquals($uploadCount, count($this->getUploadedFiles())); + $this->assertEquals(1, $preValidation); + } + protected function getConfigKey() { return 'blueimp'; @@ -19,11 +84,11 @@ class BlueimpTest extends AbstractUploadTest protected function getRequestFile() { - return array(new UploadedFile( + return array('files' => array(new UploadedFile( $this->createTempFile(128), 'cat.txt', 'text/plain', 128 - )); + ))); } } diff --git a/Tests/Controller/BlueimpValidationTest.php b/Tests/Controller/BlueimpValidationTest.php index e2cd6cd..dc90c38 100644 --- a/Tests/Controller/BlueimpValidationTest.php +++ b/Tests/Controller/BlueimpValidationTest.php @@ -4,9 +4,113 @@ namespace Oneup\UploaderBundle\Tests\Controller; use Symfony\Component\HttpFoundation\File\UploadedFile; use Oneup\UploaderBundle\Tests\Controller\AbstractValidationTest; +use Oneup\UploaderBundle\Event\ValidationEvent; +use Oneup\UploaderBundle\UploadEvents; class BlueimpValidationTest extends AbstractValidationTest { + public function testAgainstMaxSize() + { + // assemble a request + $client = $this->client; + $endpoint = $this->helper->endpoint($this->getConfigKey()); + + $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getOversizedFile()); + $response = $client->getResponse(); + + //$this->assertTrue($response->isNotSuccessful()); + $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); + $this->assertCount(0, $this->getUploadedFiles()); + } + + public function testAgainstCorrectExtension() + { + // assemble a request + $client = $this->client; + $endpoint = $this->helper->endpoint($this->getConfigKey()); + + $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getFileWithCorrectExtension()); + $response = $client->getResponse(); + + $this->assertTrue($response->isSuccessful()); + $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); + $this->assertCount(1, $this->getUploadedFiles()); + + foreach ($this->getUploadedFiles() as $file) { + $this->assertTrue($file->isFile()); + $this->assertTrue($file->isReadable()); + $this->assertEquals(128, $file->getSize()); + } + } + + public function testEvents() + { + $client = $this->client; + $endpoint = $this->helper->endpoint($this->getConfigKey()); + $dispatcher = $client->getContainer()->get('event_dispatcher'); + + // event data + $validationCount = 0; + + $dispatcher->addListener(UploadEvents::VALIDATION, function(ValidationEvent $event) use (&$validationCount) { + ++ $validationCount; + }); + + $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getFileWithCorrectExtension()); + + $this->assertEquals(1, $validationCount); + } + + public function testAgainstIncorrectExtension() + { + // assemble a request + $client = $this->client; + $endpoint = $this->helper->endpoint($this->getConfigKey()); + + $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getFileWithIncorrectExtension()); + $response = $client->getResponse(); + + //$this->assertTrue($response->isNotSuccessful()); + $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); + $this->assertCount(0, $this->getUploadedFiles()); + } + + public function testAgainstCorrectMimeType() + { + // assemble a request + $client = $this->client; + $endpoint = $this->helper->endpoint($this->getConfigKey()); + + $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getFileWithCorrectMimeType()); + $response = $client->getResponse(); + + $this->assertTrue($response->isSuccessful()); + $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); + $this->assertCount(1, $this->getUploadedFiles()); + + foreach ($this->getUploadedFiles() as $file) { + $this->assertTrue($file->isFile()); + $this->assertTrue($file->isReadable()); + $this->assertEquals(128, $file->getSize()); + } + } + + public function testAgainstIncorrectMimeType() + { + $this->markTestSkipped('Mock mime type getter.'); + + // assemble a request + $client = $this->client; + $endpoint = $this->helper->endpoint($this->getConfigKey()); + + $client->request('POST', $endpoint, $this->getRequestParameters(), $this->getFileWithIncorrectMimeType()); + $response = $client->getResponse(); + + //$this->assertTrue($response->isNotSuccessful()); + $this->assertEquals($response->headers->get('Content-Type'), 'application/json'); + $this->assertCount(0, $this->getUploadedFiles()); + } + protected function getConfigKey() { return 'blueimp_validation'; @@ -19,42 +123,42 @@ class BlueimpValidationTest extends AbstractValidationTest protected function getOversizedFile() { - return array(new UploadedFile( + return array('files' => array(new UploadedFile( $this->createTempFile(512), 'cat.ok', 'text/plain', 512 - )); + ))); } protected function getFileWithCorrectExtension() { - return array(new UploadedFile( + return array('files' => array(new UploadedFile( $this->createTempFile(128), 'cat.ok', 'text/plain', 128 - )); + ))); } protected function getFileWithIncorrectExtension() { - return array(new UploadedFile( + return array('files' => array(new UploadedFile( $this->createTempFile(128), 'cat.fail', 'text/plain', 128 - )); + ))); } protected function getFileWithCorrectMimeType() { - return array(new UploadedFile( + return array('files' => array(new UploadedFile( $this->createTempFile(128), 'cat.ok', 'image/jpg', 128 - )); + ))); } protected function getFileWithIncorrectMimeType() diff --git a/Uploader/ErrorHandler/BlueimpErrorHandler.php b/Uploader/ErrorHandler/BlueimpErrorHandler.php new file mode 100644 index 0000000..600d933 --- /dev/null +++ b/Uploader/ErrorHandler/BlueimpErrorHandler.php @@ -0,0 +1,16 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\ErrorHandler; + +use Symfony\Component\HttpFoundation\File\Exception\UploadException; +use Oneup\UploaderBundle\Uploader\ErrorHandler\ErrorHandlerInterface; +use Oneup\UploaderBundle\Uploader\Response\ResponseInterface; + +class BlueimpErrorHandler implements ErrorHandlerInterface +{ + public function addException(ResponseInterface $response, UploadException $exception) + { + $message = $exception->getErrorMessage(); + $response->addToOffset(array('error' => $message), array('files')); + } +} diff --git a/Uploader/ErrorHandler/ErrorHandlerInterface.php b/Uploader/ErrorHandler/ErrorHandlerInterface.php new file mode 100644 index 0000000..a2614a1 --- /dev/null +++ b/Uploader/ErrorHandler/ErrorHandlerInterface.php @@ -0,0 +1,11 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\ErrorHandler; + +use Symfony\Component\HttpFoundation\File\Exception\UploadException; +use Oneup\UploaderBundle\Uploader\Response\ResponseInterface; + +interface ErrorHandlerInterface +{ + public function addException(ResponseInterface $response, UploadException $exception); +} diff --git a/Uploader/ErrorHandler/NoopErrorHandler.php b/Uploader/ErrorHandler/NoopErrorHandler.php new file mode 100644 index 0000000..e131408 --- /dev/null +++ b/Uploader/ErrorHandler/NoopErrorHandler.php @@ -0,0 +1,15 @@ +<?php + +namespace Oneup\UploaderBundle\Uploader\ErrorHandler; + +use Symfony\Component\HttpFoundation\File\Exception\UploadException; +use Oneup\UploaderBundle\Uploader\ErrorHandler\ErrorHandlerInterface; +use Oneup\UploaderBundle\Uploader\Response\ResponseInterface; + +class NoopErrorHandler implements ErrorHandlerInterface +{ + public function addException(ResponseInterface $response, UploadException $exception) + { + // noop + } +} diff --git a/Uploader/Exception/ValidationException.php b/Uploader/Exception/ValidationException.php index 6d632f1..47b75c0 100644 --- a/Uploader/Exception/ValidationException.php +++ b/Uploader/Exception/ValidationException.php @@ -2,7 +2,26 @@ namespace Oneup\UploaderBundle\Uploader\Exception; -class ValidationException extends \DomainException +use Symfony\Component\HttpFoundation\File\Exception\UploadException; + +class ValidationException extends UploadException { + protected $errorMessage; + + public function setErrorMessage($message) + { + $this->errorMessage = $message; + + return $this; + } + + public function getErrorMessage() + { + // if no error message is set, return the exception message + if (!$this->errorMessage) { + return $this->getMessage(); + } + return $this->errorMessage; + } } diff --git a/Uploader/Response/AbstractResponse.php b/Uploader/Response/AbstractResponse.php index 561c7b7..fb5cc27 100644 --- a/Uploader/Response/AbstractResponse.php +++ b/Uploader/Response/AbstractResponse.php @@ -32,4 +32,32 @@ abstract class AbstractResponse implements \ArrayAccess, ResponseInterface { return isset($this->data[$offset]) ? $this->data[$offset] : null; } + + /** + * The \ArrayAccess interface does not support multi-dimensional array syntax such as $array["foo"][] = bar + * This function will take a path of arrays and add a new element to it, creating the path if needed. + * + * @param mixed $value + * @param array $offsets + * + * @throws \InvalidArgumentException if the path contains non-array items. + * + */ + public function addToOffset($value, array $offsets) + { + $element =& $this->data; + foreach ($offsets as $offset) { + if (isset($element[$offset])) { + if (is_array($element[$offset])) { + $element =& $element[$offset]; + } else { + throw new \InvalidArgumentException("The specified offset is set but is not an array at" . $offset); + } + } else { + $element[$offset] = array(); + $element =& $element[$offset]; + } + } + $element = $value; + } } commit 3361b73c806eb3d952a17b0e6d50e77eee9e8d26 (from 1e91e1e47f1a5e591e0adff95751df44843f9f85) Merge: 9dbd905 1e91e1e Author: Jim Schmid <[email protected]> Date: Mon Jul 15 03:00:36 2013 -0700 Merge pull request #27 from 1up-lab/error-handler Proper error handling. diff --git a/Controller/AbstractChunkedController.php b/Controller/AbstractChunkedController.php index 4d797d1..f053703 100644 --- a/Controller/AbstractChunkedController.php +++ b/Controller/AbstractChunkedController.php @@ -57,16 +57,20 @@ abstract class AbstractChunkedController extends AbstractController $chunk = $chunkManager->addChunk($uuid, $index, $file, $orig); $this->dispatchChunkEvents($chunk, $response, $request, $last); + + if ($chunkManager->getLoadDistribution()) { + $chunks = $chunkManager->getChunks($uuid); + $assembled = $chunkManager->assembleChunks($chunks); + } // if all chunks collected and stored, proceed // with reassembling the parts if ($last) { - // we'll take the first chunk and append the others to it - // this way we don't need another file in temporary space for assembling - $chunks = $chunkManager->getChunks($uuid); - - // assemble parts - $assembled = $chunkManager->assembleChunks($chunks); + if (!$chunkManager->getLoadDistribution()) { + $chunks = $chunkManager->getChunks($uuid); + $assembled = $chunkManager->assembleChunks($chunks); + } + $path = $assembled->getPath(); // create a temporary uploaded file to meet the interface restrictions diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 6a1736f..cbf59dd 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -19,6 +19,7 @@ class Configuration implements ConfigurationInterface ->children() ->scalarNode('maxage')->defaultValue(604800)->end() ->scalarNode('directory')->defaultNull()->end() + ->booleanNode('load_distribution')->defaultTrue()->end() ->end() ->end() ->arrayNode('orphanage') diff --git a/Uploader/Chunk/ChunkManager.php b/Uploader/Chunk/ChunkManager.php index 5bfa4b5..310cd0b 100644 --- a/Uploader/Chunk/ChunkManager.php +++ b/Uploader/Chunk/ChunkManager.php @@ -48,7 +48,7 @@ class ChunkManager implements ChunkManagerInterface return $chunk->move($path, $name); } - public function assembleChunks(\IteratorAggregate $chunks) + public function assembleChunks(\IteratorAggregate $chunks, $removeChunk = true) { $iterator = $chunks->getIterator()->getInnerIterator(); @@ -63,6 +63,11 @@ class ChunkManager implements ChunkManagerInterface throw new \RuntimeException('Reassembling chunks failed.'); } + if ($removeChunk) { + $filesystem = new Filesystem(); + $filesystem->remove($file->getPathname()); + } + $iterator->next(); } @@ -97,4 +102,9 @@ class ChunkManager implements ChunkManagerInterface return $finder; } + + public function getLoadDistribution() + { + return $this->configuration['load_distribution']; + } }
0
b9c441c0b30ea4ccb4fd405944ade8924fe00f80
389ds/389-ds-base
Ticket 48236 - Add get effective rights helper to lib389 From: William Brown <[email protected]> Date: Sat, 1 Aug 2015 13:12:10 +0930 Description: Add get effective rights search helper into dirsrv object Reviewed by: mreynolds https://fedorahosted.org/389/ticket/48236
commit b9c441c0b30ea4ccb4fd405944ade8924fe00f80 Author: Mark Reynolds <[email protected]> Date: Tue Aug 4 15:31:57 2015 -0400 Ticket 48236 - Add get effective rights helper to lib389 From: William Brown <[email protected]> Date: Sat, 1 Aug 2015 13:12:10 +0930 Description: Add get effective rights search helper into dirsrv object Reviewed by: mreynolds https://fedorahosted.org/389/ticket/48236 diff --git a/src/lib389/lib389/__init__.py b/src/lib389/lib389/__init__.py index 42df56625..90785f4b1 100644 --- a/src/lib389/lib389/__init__.py +++ b/src/lib389/lib389/__init__.py @@ -67,6 +67,11 @@ from lib389.tools import DirSrvTools # mixin #from lib389.tools import DirSrvTools +MAJOR, MINOR, _, _, _ = sys.version_info + +if MAJOR >= 3 or (MAJOR == 2 and MINOR >= 7): + from ldap.controls.simple import GetEffectiveRightsControl + RE_DBMONATTR = re.compile(r'^([a-zA-Z]+)-([1-9][0-9]*)$') RE_DBMONATTRSUN = re.compile(r'^([a-zA-Z]+)-([a-zA-Z]+)$') @@ -2266,4 +2271,50 @@ class DirSrv(SimpleLDAPObject): return DirSrvTools.searchFile(self.errlog, pattern) def detectDisorderlyShutdown(self): - return DirSrvTools.searchFile(self.errlog, DISORDERLY_SHUTDOWN) \ No newline at end of file + return DirSrvTools.searchFile(self.errlog, DISORDERLY_SHUTDOWN) + + def get_effective_rights(self, sourcedn, base=DEFAULT_SUFFIX, scope=ldap.SCOPE_SUBTREE, *args, **kwargs): + """ + Conduct a search on effective rights for some object (sourcedn) against a filter. + For arguments to this function, please see LDAPObject.search_s. For example: + + LDAPObject.search_s(base, scope[, filterstr='(objectClass=*)'[, attrlist=None[, attrsonly=0]]]) -> list|None + + The sourcedn is the object that is having it's rights checked against all objects matched by filterstr + If sourcedn is '', anonymous is checked. + If you set targetattrs to "*" you will see ALL possible attributes for all possible objectclasses on the object. + If you set targetattrs to "+" you will see operation attributes only. + If you set targetattrs to "*@objectclass" you will only see the attributes from that class. + You will want to look at entryLevelRights and attributeLevelRights in the result. + entryLevelRights: + * a - add + * d - delete + * n - rename + * v - view + attributeLevelRights + * r - read + * s - search + * w - write to the attribute (add / replace) + * o - obliterate (Delete the attribute) + * c - Compare the attributes directory side + * W - self write the attribute + * O - self obliterate + See: https://access.redhat.com/documentation/en-US/Red_Hat_Directory_Server/10/html/Administration_Guide/Viewing_the_ACIs_for_an_Entry-Get_Effective_Rights_Control.html + """ + #Is there a better way to do this check? + if not (MAJOR >= 3 or (MAJOR == 2 and MINOR >= 7)): + raise Exception("UNSUPPORTED EXTENDED OPERATION ON THIS VERSION OF PYTHON") + ldap_result = None + # This may not be thread safe. Is there a better way to do this? + try: + gerc = GetEffectiveRightsControl(True, authzId='dn:' + sourcedn.encode('UTF-8')) + sctrl = [gerc] + self.set_option(ldap.OPT_SERVER_CONTROLS, sctrl) + #ldap_result = self.search_s(base, scope, *args, **kwargs) + res = self.search(base, scope, *args, **kwargs) + restype, ldap_result = self.result(res) + finally: + self.set_option(ldap.OPT_SERVER_CONTROLS, []) + return ldap_result + + diff --git a/src/lib389/tests/effective_rights_test.py b/src/lib389/tests/effective_rights_test.py new file mode 100644 index 000000000..a02ce7ce4 --- /dev/null +++ b/src/lib389/tests/effective_rights_test.py @@ -0,0 +1,63 @@ +''' +Created on Aug 1, 2015 + +@author: William Brown +''' +from lib389._constants import * +from lib389 import DirSrv,Entry + +INSTANCE_PORT = 54321 +INSTANCE_SERVERID = 'effectiverightsds' +INSTANCE_PREFIX = None + +class Test_effective_rights(): + def setUp(self): + instance = DirSrv(verbose=False) + instance.log.debug("Instance allocated") + args = {SER_HOST: LOCALHOST, + SER_PORT: INSTANCE_PORT, + SER_DEPLOYED_DIR: INSTANCE_PREFIX, + SER_SERVERID_PROP: INSTANCE_SERVERID + } + instance.allocate(args) + if instance.exists(): + instance.delete() + instance.create() + instance.open() + self.instance = instance + + def tearDown(self): + if self.instance.exists(): + self.instance.delete() + + def add_user(self): + # Create a user entry + uentry = Entry('uid=test,%s' % DEFAULT_SUFFIX) + uentry.setValues('objectclass', 'top', 'extensibleobject') + uentry.setValues('uid', 'test') + self.instance.add_s(uentry) + #self.instance.log.debug("Created user entry as:" ,uentry.dn) + + def add_group(self): + # Create a group for the user to have some rights to + gentry = Entry('cn=testgroup,%s' % DEFAULT_SUFFIX) + gentry.setValues('objectclass', 'top', 'extensibleobject') + gentry.setValues('cn', 'testgroup') + self.instance.add_s(gentry) + + def test_effective_rights(self): + # Run an effective rights search + result = self.instance.get_effective_rights('uid=test,%s' % DEFAULT_SUFFIX, filterstr='(cn=testgroup)', attrlist=['cn']) + + rights = result[0] + assert rights.getValue('attributeLevelRights') == 'cn:rsc' + assert rights.getValue('entryLevelRights') == 'v' + +if __name__ == "__main__": + test = Test_effective_rights() + test.setUp() + test.add_user() + test.add_group() + test.test_effective_rights() + test.tearDown() +
0
0235b062d49388243a97c3e4e68d88c1579b6fb7
389ds/389-ds-base
Issue 5653 - covscan - fix invalid dereference Description: 389-ds-base-2.2.4/ldap/servers/slapd/tools/dbscan.c:1111: var_deref_model: Passing null pointer "dump" to "fclose", which dereferences it. 389-ds-base-2.2.4/ldap/servers/slapd/result.c:2022: check_after_deref: Null-checking "op" suggests that it may be null, but it has already been dereferenced on all paths leading to the check. 389-ds-base-2.2.4/ldap/servers/slapd/result.c:2019: var_deref_model: Passing null pointer "op" to "operation_is_flag_set", which dereferences it. relates: https://github.com/389ds/389-ds-base/issues/5653 Reviewed by: jchapman(Thanks!)
commit 0235b062d49388243a97c3e4e68d88c1579b6fb7 Author: Mark Reynolds <[email protected]> Date: Fri Feb 10 16:20:56 2023 -0500 Issue 5653 - covscan - fix invalid dereference Description: 389-ds-base-2.2.4/ldap/servers/slapd/tools/dbscan.c:1111: var_deref_model: Passing null pointer "dump" to "fclose", which dereferences it. 389-ds-base-2.2.4/ldap/servers/slapd/result.c:2022: check_after_deref: Null-checking "op" suggests that it may be null, but it has already been dereferenced on all paths leading to the check. 389-ds-base-2.2.4/ldap/servers/slapd/result.c:2019: var_deref_model: Passing null pointer "op" to "operation_is_flag_set", which dereferences it. relates: https://github.com/389ds/389-ds-base/issues/5653 Reviewed by: jchapman(Thanks!) diff --git a/ldap/servers/slapd/result.c b/ldap/servers/slapd/result.c index 2ba205e04..d87a75ad9 100644 --- a/ldap/servers/slapd/result.c +++ b/ldap/servers/slapd/result.c @@ -1,6 +1,6 @@ /** BEGIN COPYRIGHT BLOCK * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. - * Copyright (C) 2021 Red Hat, Inc. + * Copyright (C) 2023 Red Hat, Inc. * All rights reserved. * * License: GPL (version 3 or any later version). @@ -2014,14 +2014,16 @@ log_op_stat(Slapi_PBlock *pb, uint64_t connid, int32_t op_id, int32_t op_interna if (config_get_statlog_level() == 0) { return; } - slapi_pblock_get(pb, SLAPI_OPERATION, &op); + if (op == NULL) { + return; + } internal_op = operation_is_flag_set(op, OP_FLAG_INTERNAL); op_stat = op_stat_get_operation_extension(pb); - - if (op == NULL || op_stat == NULL) { + if (op_stat == NULL) { return; } + /* process the operation */ switch (operation_get_type(op)) { case SLAPI_OPERATION_BIND: @@ -2380,7 +2382,7 @@ encode_read_entry(Slapi_PBlock *pb, Slapi_Entry *e, char **attrs, int alluseratt if (conn == NULL || op == NULL) { slapi_log_err(SLAPI_LOG_ERR, "encode_read_entry", - "NULL param error: conn (0x%p) op (0x%p)\n", conn, op); + "NULL param error: conn (%p) op (%p)\n", conn, op); rc = -1; goto cleanup; } diff --git a/ldap/servers/slapd/tools/dbscan.c b/ldap/servers/slapd/tools/dbscan.c index 8bead9d93..2d28dd951 100644 --- a/ldap/servers/slapd/tools/dbscan.c +++ b/ldap/servers/slapd/tools/dbscan.c @@ -1,5 +1,5 @@ /** BEGIN COPYRIGHT BLOCK - * Copyright (C) 2021 Red Hat, Inc. + * Copyright (C) 2023 Red Hat, Inc. * All rights reserved. * * License: GPL (version 3 or any later version). @@ -1108,7 +1108,7 @@ _read_line(FILE *file, int *keyword, dbi_val_t *val) int importdb(const char *dbimpl_name, const char *filename, const char *dump_name) { - FILE *dump = fopen(dump_name, "r"); + FILE *dump = NULL; dbi_val_t key = {0}, data = {0}; struct back_txn txn = {0}; dbi_env_t *env = NULL; @@ -1116,6 +1116,13 @@ importdb(const char *dbimpl_name, const char *filename, const char *dump_name) int keyword = 0; int ret = 0; + if (dump_name == NULL) { + printf("Error: dump_name can not be NULL\n"); + return 1; + } + + dump = fopen(dump_name, "r"); + dblayer_init_pvt_txn(); if (!dump) {
0
0f1a203a0fe85f3cf0440006685f63409502f093
389ds/389-ds-base
Ticket #47895 - If no effective ciphers are available, disable security setting. Description: If nsslapd-security is "on" and nsSSL3Ciphers is given AND none of the ciphers are available or some syntax error is detected, the server sets nsslapd-security "off" and starts up. https://fedorahosted.org/389/ticket/47895 Reviewed by [email protected] (Thank you, Nathan!!)
commit 0f1a203a0fe85f3cf0440006685f63409502f093 Author: Noriko Hosoi <[email protected]> Date: Wed Sep 10 18:56:43 2014 -0700 Ticket #47895 - If no effective ciphers are available, disable security setting. Description: If nsslapd-security is "on" and nsSSL3Ciphers is given AND none of the ciphers are available or some syntax error is detected, the server sets nsslapd-security "off" and starts up. https://fedorahosted.org/389/ticket/47895 Reviewed by [email protected] (Thank you, Nathan!!) diff --git a/ldap/servers/slapd/main.c b/ldap/servers/slapd/main.c index d57751428..6bad2a08d 100644 --- a/ldap/servers/slapd/main.c +++ b/ldap/servers/slapd/main.c @@ -3077,6 +3077,24 @@ slapd_debug_level_usage( void ) } #endif /* LDAP_DEBUG */ +static int +force_to_disable_security(const char *what, int *init_ssl, daemon_ports_t *ports_info) +{ + char errorbuf[SLAPI_DSE_RETURNTEXT_SIZE]; + errorbuf[0] = '\0'; + + LDAPDebug2Args(LDAP_DEBUG_ANY, "ERROR: %s Initialization Failed. Disabling %s.\n", what, what); + ports_info->s_socket = SLAPD_INVALID_SOCKET; + ports_info->s_port = 0; + *init_ssl = 0; + if (config_set_security(CONFIG_SECURITY_ATTRIBUTE, "off", errorbuf, 1)) { + LDAPDebug2Args(LDAP_DEBUG_ANY, "ERROR: Failed to disable %s: \"%s\".\n", + CONFIG_SECURITY_ATTRIBUTE, errorbuf[0]?errorbuf:"no error message"); + return 1; + } + return 0; +} + /* This function does all NSS and SSL related initialization required during startup. We use this function rather @@ -3113,20 +3131,20 @@ slapd_do_all_nss_ssl_init(int slapd_exemode, int importexport_encrypt, * modules can assume NSS is available */ if ( slapd_nss_init((slapd_exemode == SLAPD_EXEMODE_SLAPD), - (slapd_exemode != SLAPD_EXEMODE_REFERRAL) /* have config? */ )) { - LDAPDebug(LDAP_DEBUG_ANY, - "ERROR: NSS Initialization Failed.\n", 0, 0, 0); - return 1; + (slapd_exemode != SLAPD_EXEMODE_REFERRAL) /* have config? */ )) { + if (force_to_disable_security("NSS", &init_ssl, ports_info)) { + return 1; + } } if (slapd_exemode == SLAPD_EXEMODE_SLAPD) { client_auth_init(); } - if ( init_ssl && ( 0 != slapd_ssl_init())) { - LDAPDebug(LDAP_DEBUG_ANY, - "ERROR: SSL Initialization Failed.\n", 0, 0, 0 ); - return 1; + if (init_ssl && slapd_ssl_init()) { + if (force_to_disable_security("SSL", &init_ssl, ports_info)) { + return 1; + } } if ((slapd_exemode == SLAPD_EXEMODE_SLAPD) || @@ -3134,10 +3152,10 @@ slapd_do_all_nss_ssl_init(int slapd_exemode, int importexport_encrypt, if ( init_ssl ) { PRFileDesc **sock; for (sock = ports_info->s_socket; sock && *sock; sock++) { - if ( 0 != slapd_ssl_init2(sock, 0) ) { - LDAPDebug(LDAP_DEBUG_ANY, - "ERROR: SSL Initialization phase 2 Failed.\n", 0, 0, 0 ); - return 1; + if ( slapd_ssl_init2(sock, 0) ) { + if (force_to_disable_security("SSL2", &init_ssl, ports_info)) { + return 1; + } } } }
0
07bb0d48ebb67db1bb8fa365754b40778a881bc2
389ds/389-ds-base
Resolves: #485321 Summary: Entry cache: invalid counter usage Description: if new entry size is larger than old size, the delta is added to the cache size using slapi_counter_add; otherwise, the delta is subtracted from the cache size using slapi_counter_subtract.
commit 07bb0d48ebb67db1bb8fa365754b40778a881bc2 Author: Noriko Hosoi <[email protected]> Date: Fri Feb 13 00:16:32 2009 +0000 Resolves: #485321 Summary: Entry cache: invalid counter usage Description: if new entry size is larger than old size, the delta is added to the cache size using slapi_counter_add; otherwise, the delta is subtracted from the cache size using slapi_counter_subtract. diff --git a/ldap/servers/slapd/back-ldbm/cache.c b/ldap/servers/slapd/back-ldbm/cache.c index c95c78677..84e935c99 100644 --- a/ldap/servers/slapd/back-ldbm/cache.c +++ b/ldap/servers/slapd/back-ldbm/cache.c @@ -865,7 +865,11 @@ int cache_replace(struct cache *cache, struct backentry *olde, /* adjust cache meta info */ newe->ep_refcnt = 1; newe->size = cache_entry_size(newe); - slapi_counter_add(cache->c_cursize, newe->size - olde->size); + if (newe->size > olde->size) { + slapi_counter_add(cache->c_cursize, newe->size - olde->size); + } else if (newe->size < olde->size) { + slapi_counter_subtract(cache->c_cursize, olde->size - newe->size); + } olde->ep_state = ENTRY_STATE_DELETED; newe->ep_state = 0; PR_Unlock(cache->c_mutex);
0
89e32553a8a31b1e3e99e5c1e36b80b07da1c0b0
389ds/389-ds-base
need time and datetime - add str method for RUV to format RUV in a readable format Reviewed by: tbordaz (Thanks!)
commit 89e32553a8a31b1e3e99e5c1e36b80b07da1c0b0 Author: Rich Megginson <[email protected]> Date: Wed Nov 20 19:15:42 2013 -0700 need time and datetime - add str method for RUV to format RUV in a readable format Reviewed by: tbordaz (Thanks!) diff --git a/src/lib389/lib389/_replication.py b/src/lib389/lib389/_replication.py index fc9e8cb52..2eade309d 100644 --- a/src/lib389/lib389/_replication.py +++ b/src/lib389/lib389/_replication.py @@ -1,3 +1,5 @@ +import time +import datetime class CSN(object): """CSN is Change Sequence Number @@ -144,6 +146,13 @@ class RUV(object): def __eq__(self, oth): return cmp(self, oth) == 0 + def __str__(self): + ret = 'generation: %s\n' % self.gen + for rid in self.rid.keys(): + ret = ret + 'rid: %s url: %s min: [%s] max: [%s]\n' % \ + (rid, self.rid[rid]['url'], self.rid[rid].get('min', ''), self. rid[rid].get('max', '')) + return ret + def getdiffs(self, oth): """Compare two ruvs and return the differences returns a tuple - the first element is the
0
4a6a280072bb6e6cb93b18f5a376e429de2d4968
389ds/389-ds-base
Issue 50758 - Enable CLI arg completion Description: We need to make sure the bash_completion package is installed, and that we call activate-global-python-argcomplete in %post relates: https://pagure.io/389-ds-base/issue/50758 Reviewed by: mhonek, and firstyear(Thanks!)
commit 4a6a280072bb6e6cb93b18f5a376e429de2d4968 Author: Mark Reynolds <[email protected]> Date: Tue Dec 3 11:17:06 2019 -0500 Issue 50758 - Enable CLI arg completion Description: We need to make sure the bash_completion package is installed, and that we call activate-global-python-argcomplete in %post relates: https://pagure.io/389-ds-base/issue/50758 Reviewed by: mhonek, and firstyear(Thanks!) diff --git a/rpm/389-ds-base.spec.in b/rpm/389-ds-base.spec.in index 53f3a0b82..ec635b36d 100644 --- a/rpm/389-ds-base.spec.in +++ b/rpm/389-ds-base.spec.in @@ -304,6 +304,7 @@ Requires: python%{python3_pkgversion}-dateutil Requires: python%{python3_pkgversion}-argcomplete Requires: python%{python3_pkgversion}-libselinux Requires: python%{python3_pkgversion}-setuptools +Requires: bash-completion %{?python_provide:%python_provide python%{python3_pkgversion}-lib389} %description -n python%{python3_pkgversion}-lib389 @@ -467,6 +468,9 @@ if ! make DESTDIR="$RPM_BUILD_ROOT" check; then cat ./test-suite.log && false; f rm -rf $RPM_BUILD_ROOT %post +# activate arg completion for CLI tools +activate-global-python-argcomplete > /dev/null + if [ -n "$DEBUGPOSTTRANS" ] ; then output=$DEBUGPOSTTRANS output2=${DEBUGPOSTTRANS}.upgrade
0
d0ae48cbbfae65215b1212dc66bfd7c49c30ddd7
389ds/389-ds-base
Issue 6800 - Check for minimal supported Python version Description: Add a new check for minimal supported Python version for lib389 and dirsrvtests Fixes: https://github.com/389ds/389-ds-base/issues/6800 Reviewed by: @progier389, @droideck (Thanks)
commit d0ae48cbbfae65215b1212dc66bfd7c49c30ddd7 Author: Viktor Ashirov <[email protected]> Date: Tue Jul 1 13:35:09 2025 +0200 Issue 6800 - Check for minimal supported Python version Description: Add a new check for minimal supported Python version for lib389 and dirsrvtests Fixes: https://github.com/389ds/389-ds-base/issues/6800 Reviewed by: @progier389, @droideck (Thanks) diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 3b120c2be..8b38bca2a 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -1,4 +1,4 @@ -name: Validate tests +name: Validate tests and minimal Python version on: push: @@ -29,3 +29,11 @@ jobs: - name: Check for duplicate IDs if: always() run: python3 dirsrvtests/check_for_duplicate_ids.py dirsrvtests/tests/suites + + - name: Check for minimal Python version for lib389 + if: always() + run: uv tool run vermin --target=3.8 src/lib389 + + - name: Check for minimal Python version for dirsrvtests + if: always() + run: uv tool run vermin --target=3.8 dirsrvtests diff --git a/src/lib389/lib389/instance/options.py b/src/lib389/lib389/instance/options.py index ce8678ae0..928e5f796 100644 --- a/src/lib389/lib389/instance/options.py +++ b/src/lib389/lib389/instance/options.py @@ -16,10 +16,7 @@ from lib389.utils import get_default_db_lib, get_default_mdb_max_size, socket_ch MAJOR, MINOR, _, _, _ = sys.version_info -if MAJOR >= 3: - import configparser -else: - import ConfigParser as configparser +import configparser format_keys = [ 'prefix', diff --git a/src/lib389/lib389/paths.py b/src/lib389/lib389/paths.py index 406e2c12a..48e7bd0f0 100644 --- a/src/lib389/lib389/paths.py +++ b/src/lib389/lib389/paths.py @@ -14,10 +14,7 @@ from lib389._constants import DIRSRV_STATE_ONLINE, DSRC_CONTAINER MAJOR, MINOR, _, _, _ = sys.version_info -if MAJOR >= 3: - import configparser -else: - import ConfigParser as configparser +import configparser # Read the paths from default.inf diff --git a/src/lib389/lib389/tools.py b/src/lib389/lib389/tools.py index df6ba7923..e342f6d43 100644 --- a/src/lib389/lib389/tools.py +++ b/src/lib389/lib389/tools.py @@ -39,12 +39,6 @@ from lib389.utils import ( ) __all__ = ['DirSrvTools'] -try: - from subprocess import Popen, PIPE, STDOUT - HASPOPEN = True -except ImportError: - import popen2 - HASPOPEN = False _ds_paths = Paths() @@ -98,16 +92,11 @@ class DirSrvTools(object): env['NETSITE_ROOT'] = sroot env['CONTENT_LENGTH'] = str(length) progdir = os.path.dirname(prog) - if HASPOPEN: - pipe = Popen(prog, cwd=progdir, env=env, - stdin=PIPE, stdout=PIPE, stderr=STDOUT) - child_stdin = pipe.stdin - child_stdout = pipe.stdout - else: - saveenv = os.environ - os.environ = env - child_stdout, child_stdin = popen2.popen2(prog) - os.environ = saveenv + pipe = subprocess.Popen(prog, cwd=progdir, env=env, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT) + child_stdin = pipe.stdin + child_stdout = pipe.stdout child_stdin.write(content) child_stdin.close() for line in child_stdout: @@ -118,10 +107,9 @@ class DirSrvTools(object): exitCode = ary[1].strip() break child_stdout.close() - if HASPOPEN: - osCode = pipe.wait() - print("%s returned NMC code %s and OS code %s" % - (prog, exitCode, osCode)) + osCode = pipe.wait() + print("%s returned NMC code %s and OS code %s" % + (prog, exitCode, osCode)) return exitCode @staticmethod @@ -457,14 +445,10 @@ class DirSrvTools(object): cmd.extend(['-l', '/dev/null']) cmd.extend(['-s', '-f', '-']) log.debug("running: %s " % cmd) - if HASPOPEN: - pipe = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=STDOUT) - child_stdin = pipe.stdin - child_stdout = pipe.stdout - else: - pipe = popen2.Popen4(cmd) - child_stdin = pipe.tochild - child_stdout = pipe.fromchild + pipe = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT) + child_stdin = pipe.stdin + child_stdout = pipe.stdout child_stdin.write(ensure_bytes(content)) child_stdin.close() if verbose: diff --git a/src/lib389/lib389/utils.py b/src/lib389/lib389/utils.py index 33cc1b6ba..6e4ec76f5 100644 --- a/src/lib389/lib389/utils.py +++ b/src/lib389/lib389/utils.py @@ -11,19 +11,6 @@ TODO put them in a module! """ -try: - from subprocess import Popen as my_popen, PIPE -except ImportError: - from popen2 import popen2 - - def my_popen(cmd_l, stdout=None): - class MockPopenResult(object): - def wait(self): - pass - p = MockPopenResult() - p.stdout, p.stdin = popen2(cmd_l) - return p - import json import re import os @@ -859,7 +846,7 @@ def isLocalHost(host_name): # next, see if this IP addr is one of our # local addresses - p = my_popen(['/sbin/ip', 'addr'], stdout=PIPE) + p = subprocess.Popen(['/sbin/ip', 'addr'], stdout=subprocess.PIPE) child_stdout = p.stdout.read() found = ('inet %s' % ip_addr).encode() in child_stdout p.wait()
0
b22fcdfaf8c7d96826ddc75c2db0ba17e70112df
389ds/389-ds-base
Resolves: #237040 Summary: Remove obsolete makefiles
commit b22fcdfaf8c7d96826ddc75c2db0ba17e70112df Author: Noriko Hosoi <[email protected]> Date: Thu Apr 19 17:54:45 2007 +0000 Resolves: #237040 Summary: Remove obsolete makefiles diff --git a/lib/ldaputil/Makefile b/lib/ldaputil/Makefile deleted file mode 100644 index 190e1ddd7..000000000 --- a/lib/ldaputil/Makefile +++ /dev/null @@ -1,96 +0,0 @@ -# -# BEGIN COPYRIGHT BLOCK -# This Program is free software; you can redistribute it and/or modify it under -# the terms of the GNU General Public License as published by the Free Software -# Foundation; version 2 of the License. -# -# This Program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License along with -# this Program; if not, write to the Free Software Foundation, Inc., 59 Temple -# Place, Suite 330, Boston, MA 02111-1307 USA. -# -# In addition, as a special exception, Red Hat, Inc. gives You the additional -# right to link the code of this Program with code not covered under the GNU -# General Public License ("Non-GPL Code") and to distribute linked combinations -# including the two, subject to the limitations in this paragraph. Non-GPL Code -# permitted under this exception must only link to the code of this Program -# through those well defined interfaces identified in the file named EXCEPTION -# found in the source code files (the "Approved Interfaces"). The files of -# Non-GPL Code may instantiate templates or use macros or inline functions from -# the Approved Interfaces without causing the resulting work to be covered by -# the GNU General Public License. Only Red Hat, Inc. may make changes or -# additions to the list of Approved Interfaces. You must obey the GNU General -# Public License in all respects for all of the Program code and other code used -# in conjunction with the Program except the Non-GPL Code covered by this -# exception. If you modify this file, you may extend this exception to your -# version of the file, but you are not obligated to do so. If you do not wish to -# provide this exception without modification, you must delete this exception -# statement from your version and license this file solely under the GPL without -# exception. -# -# -# Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. -# Copyright (C) 2005 Red Hat, Inc. -# All rights reserved. -# END COPYRIGHT BLOCK -# -# -# Makefile for libldapu.a (ldaputil library) -# -BUILD_ROOT=../.. -MODULE=LibLdapUtil - -OBJDEST=$(OBJDIR)/lib/ldaputil - -include $(BUILD_ROOT)/nsconfig.mk - -ifeq ($(ARCH), WINNT) -LIBS=$(OBJDIR)/lib/libldapu.lib -MODULE_CFLAGS+= -DWINSOCK -else -LIBS=$(OBJDIR)/lib/libldapu.a -endif - -LOCAL_DEPS = $(LDAPSDK_DEP) - -MCC_INCLUDE=-I$(BUILD_ROOT)/include \ - $(DBM_INCLUDE) $(LDAPSDK_INCLUDE) \ - $(SECURITY_INCLUDE) $(NSPR_INCLUDE) - -all: $(OBJDEST) $(LOCAL_DEPS) $(LIBS) - -$(OBJDEST): - mkdir -p $(OBJDEST) - -OSOBJS = - -OBJS=$(addprefix $(OBJDEST)/, \ - ldapauth.o \ - ldapdb.o \ - dbconf.o \ - certmap.o \ - cert.o \ - init.o \ - encode.o \ - errors.o \ - vtable.o \ - ) - -MODULE_CFLAGS+= $(TESTFLAGS) -MODULE_CFLAGS+= -I. - -ifeq ($(LDAP_NO_LIBLCACHE),1) -MODULE_CFLAGS+=-DNO_LIBLCACHE -endif - - -$(LIBS): $(OBJS) - rm -f $@ - $(AR) $(OBJS) - $(RANLIB) $@ - -include $(INCLUDE_DEPENDS) -
0
59a3cc8efdd6ffd129a59df846ef2d9fa44dff0e
389ds/389-ds-base
Resolves: #469800 Summary: Slow import post-processing with large number of non-leaf entries (comment #15) Change description: Fixed ldbm_ancestorid_new_idl_create_index so that the ancestor key has the value including all the descendent ids in the IDlist. The code checked in previously only stores the direct children and their children.
commit 59a3cc8efdd6ffd129a59df846ef2d9fa44dff0e Author: Noriko Hosoi <[email protected]> Date: Thu Jan 15 22:44:40 2009 +0000 Resolves: #469800 Summary: Slow import post-processing with large number of non-leaf entries (comment #15) Change description: Fixed ldbm_ancestorid_new_idl_create_index so that the ancestor key has the value including all the descendent ids in the IDlist. The code checked in previously only stores the direct children and their children. diff --git a/ldap/servers/slapd/back-ldbm/ancestorid.c b/ldap/servers/slapd/back-ldbm/ancestorid.c index 51647506f..c3edea064 100644 --- a/ldap/servers/slapd/back-ldbm/ancestorid.c +++ b/ldap/servers/slapd/back-ldbm/ancestorid.c @@ -455,35 +455,38 @@ static int ldbm_ancestorid_new_idl_create_index(backend *be) /* Insert into ancestorid for this node */ ret = idl_store_block(be, db_aid, &key, children, txn, ai_aid); - if (ret != 0) { - idl_free(children); - break; - } - - /* Get parentid for this entry */ - ret = ldbm_parentid(be, txn, id, &parentid); if (ret != 0) { idl_free(children); break; } - /* A suffix entry does not have a parent */ - if (parentid == NOID) { - idl_free(children); - continue; + /* Get parentid(s) for this entry */ + while (1) { + ret = ldbm_parentid(be, txn, id, &parentid); + if (ret != 0) { + idl_free(children); + goto out; + } + + /* A suffix entry does not have a parent */ + if (parentid == NOID) { + idl_free(children); + break; + } + + /* Reset the key to the parent id */ + key.size = PR_snprintf(key.data, key.ulen, "%c%lu", + EQ_PREFIX, (u_long)parentid); + key.size++; + + /* Insert into ancestorid for this node's parent */ + ret = idl_store_block(be, db_aid, &key, children, txn, ai_aid); + if (ret != 0) { + idl_free(children); + goto out; + } + id = parentid; } - - /* Reset the key to the parent id */ - key.size = PR_snprintf(key.data, key.ulen, "%c%lu", - EQ_PREFIX, (u_long)parentid); - key.size++; - - /* Insert into ancestorid for this node's parent */ - ret = idl_store_block(be, db_aid, &key, children, txn, ai_aid); - idl_free(children); - if (ret != 0) { - break; - } } while (nids > 0); if (ret != 0) {
0
2521eb7a649fab115366a652d2ec499ad205ae03
389ds/389-ds-base
Workaround bogus base64 encoded passwords that end in newline https://bugzilla.redhat.com/show_bug.cgi?id=552421 Resolves: bug 552421 Bug Description: Cannot log into admin server after upgrade (fedora-ds-admin-1.1.6 -> 389-admin-1.1.9 Reviewed by: nkinder (Thanks!) Branch: HEAD Fix Description: Some older versions of setup encoded the admin password in SHA and added a trailing newline to the userPassword attribute when adding the admin entry. This changes the SHA passsword compare routine to ignore a trailing newline character in the dbpwd. newline is not a valid base64 character. Platforms tested: RHEL5 x86_64 Flag Day: no Doc impact: no
commit 2521eb7a649fab115366a652d2ec499ad205ae03 Author: Rich Megginson <[email protected]> Date: Mon Jan 11 11:51:39 2010 -0700 Workaround bogus base64 encoded passwords that end in newline https://bugzilla.redhat.com/show_bug.cgi?id=552421 Resolves: bug 552421 Bug Description: Cannot log into admin server after upgrade (fedora-ds-admin-1.1.6 -> 389-admin-1.1.9 Reviewed by: nkinder (Thanks!) Branch: HEAD Fix Description: Some older versions of setup encoded the admin password in SHA and added a trailing newline to the userPassword attribute when adding the admin entry. This changes the SHA passsword compare routine to ignore a trailing newline character in the dbpwd. newline is not a valid base64 character. Platforms tested: RHEL5 x86_64 Flag Day: no Doc impact: no diff --git a/ldap/servers/plugins/pwdstorage/pwd_util.c b/ldap/servers/plugins/pwdstorage/pwd_util.c index c7b4fdad6..1b0f5942a 100644 --- a/ldap/servers/plugins/pwdstorage/pwd_util.c +++ b/ldap/servers/plugins/pwdstorage/pwd_util.c @@ -50,10 +50,14 @@ * calculate the number of bytes the base64 encoded encval * will have when decoded, taking into account padding */ -int -pwdstorage_base64_decode_len(const char *encval) +PRUint32 +pwdstorage_base64_decode_len(const char *encval, PRUint32 enclen) { - int len = strlen(encval); + PRUint32 len = enclen; + + if (len == 0) { + len = strlen(encval); + } if (len && (0 == (len & 3))) { if('=' == encval[len - 1]) { if('=' == encval[len - 2]) { diff --git a/ldap/servers/plugins/pwdstorage/pwdstorage.h b/ldap/servers/plugins/pwdstorage/pwdstorage.h index f43e63e5b..f215ba262 100644 --- a/ldap/servers/plugins/pwdstorage/pwdstorage.h +++ b/ldap/servers/plugins/pwdstorage/pwdstorage.h @@ -113,6 +113,6 @@ int smd5_pw_cmp( const char *userpwd, const char *dbpwd ); char *smd5_pw_enc( const char *pwd ); /* Utility functions */ -int pwdstorage_base64_decode_len(const char *encval); +PRUint32 pwdstorage_base64_decode_len(const char *encval, PRUint32 enclen); #endif /* _PWDSTORAGE_H */ diff --git a/ldap/servers/plugins/pwdstorage/sha_pwd.c b/ldap/servers/plugins/pwdstorage/sha_pwd.c index d7fb693df..94cce6c05 100644 --- a/ldap/servers/plugins/pwdstorage/sha_pwd.c +++ b/ldap/servers/plugins/pwdstorage/sha_pwd.c @@ -83,6 +83,7 @@ sha_pw_cmp (const char *userpwd, const char *dbpwd, unsigned int shaLen ) unsigned int secOID; char *schemeName; char *hashresult = NULL; + PRUint32 dbpwd_len; /* Determine which algorithm we're using */ switch (shaLen) { @@ -107,17 +108,25 @@ sha_pw_cmp (const char *userpwd, const char *dbpwd, unsigned int shaLen ) goto loser; } + /* in some cases, the password was stored incorrectly - the base64 dbpwd ends + in a newline - we check for this case and remove the newline, if any - + see bug 552421 */ + dbpwd_len = strlen(dbpwd); + if ((dbpwd_len > 0) && (dbpwd[dbpwd_len-1] == '\n')) { + dbpwd_len--; + } + /* * Decode hash stored in database. */ - hash_len = pwdstorage_base64_decode_len(dbpwd); + hash_len = pwdstorage_base64_decode_len(dbpwd, dbpwd_len); if ( hash_len > sizeof(quick_dbhash) ) { /* get more space: */ dbhash = (char*) slapi_ch_calloc( hash_len, sizeof(char) ); if ( dbhash == NULL ) goto loser; } else { memset( quick_dbhash, 0, sizeof(quick_dbhash) ); } - hashresult = PL_Base64Decode( dbpwd, 0, dbhash ); + hashresult = PL_Base64Decode( dbpwd, dbpwd_len, dbhash ); if (NULL == hashresult) { slapi_log_error( SLAPI_LOG_PLUGIN, plugin_name, hasherrmsg, schemeName, dbpwd ); goto loser; diff --git a/ldap/servers/plugins/pwdstorage/smd5_pwd.c b/ldap/servers/plugins/pwdstorage/smd5_pwd.c index f7689ed40..6747a2023 100644 --- a/ldap/servers/plugins/pwdstorage/smd5_pwd.c +++ b/ldap/servers/plugins/pwdstorage/smd5_pwd.c @@ -82,7 +82,7 @@ smd5_pw_cmp( const char *userpwd, const char *dbpwd ) /* * Decode hash stored in database. */ - hash_len = pwdstorage_base64_decode_len(dbpwd); + hash_len = pwdstorage_base64_decode_len(dbpwd, 0); if ( hash_len >= sizeof(quick_dbhash) ) { /* get more space: */ dbhash = (char*) slapi_ch_calloc( hash_len + 1, sizeof(char) ); if ( dbhash == NULL ) goto loser;
0
2263bd9fab124dbd84a58a2b7d4ab8e3ee84e2d4
389ds/389-ds-base
Ticket #48048 - Fix coverity issues - 2015/2/24 Coverity defect 13057 - Explicit null dereferenced (FORWARD_NULL) Description: Added NULL check for mrTYPE. modified: extensible_candidates in filterindex.c
commit 2263bd9fab124dbd84a58a2b7d4ab8e3ee84e2d4 Author: Noriko Hosoi <[email protected]> Date: Tue Feb 24 15:50:22 2015 -0800 Ticket #48048 - Fix coverity issues - 2015/2/24 Coverity defect 13057 - Explicit null dereferenced (FORWARD_NULL) Description: Added NULL check for mrTYPE. modified: extensible_candidates in filterindex.c diff --git a/ldap/servers/slapd/back-ldbm/filterindex.c b/ldap/servers/slapd/back-ldbm/filterindex.c index c8c40c49e..7054ef8ac 100644 --- a/ldap/servers/slapd/back-ldbm/filterindex.c +++ b/ldap/servers/slapd/back-ldbm/filterindex.c @@ -453,7 +453,7 @@ extensible_candidates( slapi_pblock_get (pb, SLAPI_PLUGIN_MR_OID, &mrOID); slapi_pblock_get (pb, SLAPI_PLUGIN_MR_TYPE, &mrTYPE); - if (mrVALUES != NULL && *mrVALUES != NULL) + if (mrVALUES && *mrVALUES && mrTYPE) { /* * Compute keys for each of the values, individually.
0
922b3d85f45362fb1de3bd35bd329cfd4c260500
389ds/389-ds-base
Resolves: 446697 Summary: Added new remove-ds.pl script and manpage.
commit 922b3d85f45362fb1de3bd35bd329cfd4c260500 Author: Nathan Kinder <[email protected]> Date: Fri Feb 13 20:05:59 2009 +0000 Resolves: 446697 Summary: Added new remove-ds.pl script and manpage. diff --git a/Makefile.am b/Makefile.am index 9dfe565c8..ddfe01164 100644 --- a/Makefile.am +++ b/Makefile.am @@ -61,7 +61,7 @@ LIBCRUN=@LIBCRUN@ BUILT_SOURCES = dirver.h dberrstrs.h CLEANFILES = dirver.h dberrstrs.h ns-slapd.properties \ - ldap/admin/src/scripts/dscreate.map \ + ldap/admin/src/scripts/dscreate.map ldap/admin/src/scripts/remove-ds.pl \ ldap/admin/src/scripts/DSCreate.pm ldap/admin/src/scripts/DSMigration.pm \ ldap/admin/src/scripts/dsorgentries.map ldap/admin/src/scripts/migrate-ds.pl \ ldap/admin/src/scripts/Migration.pm ldap/admin/src/scripts/SetupDialogs.pm \ @@ -232,7 +232,8 @@ schema_DATA = $(srcdir)/ldap/schema/00core.ldif \ $(srcdir)/ldap/schema/99user.ldif sbin_SCRIPTS = ldap/admin/src/scripts/setup-ds.pl \ - ldap/admin/src/scripts/migrate-ds.pl + ldap/admin/src/scripts/migrate-ds.pl \ + ldap/admin/src/scripts/remove-ds.pl bin_SCRIPTS = ldap/servers/slapd/tools/rsearch/scripts/dbgen.pl \ wrappers/dbscan \ @@ -332,7 +333,8 @@ dist_man_MANS = man/man1/dbscan.1 \ man/man1/rsearch.1 \ man/man8/migrate-ds.pl.8 \ man/man8/ns-slapd.8 \ - man/man8/setup-ds.pl.8 + man/man8/setup-ds.pl.8 \ + man/man8/remove-ds.pl.8 #//////////////////////////////////////////////////////////////// # diff --git a/Makefile.in b/Makefile.in index 3c9c72b30..5e7f0d9db 100644 --- a/Makefile.in +++ b/Makefile.in @@ -935,7 +935,6 @@ PACKAGE_VERSION = @PACKAGE_VERSION@ PATH_SEPARATOR = @PATH_SEPARATOR@ PKG_CONFIG = @PKG_CONFIG@ RANLIB = @RANLIB@ -SED = @SED@ SET_MAKE = @SET_MAKE@ SHELL = @SHELL@ SOLARIS_FALSE = @SOLARIS_FALSE@ @@ -1111,7 +1110,7 @@ KERBEROS_LINK = $(kerberos_lib) #------------------------ BUILT_SOURCES = dirver.h dberrstrs.h CLEANFILES = dirver.h dberrstrs.h ns-slapd.properties \ - ldap/admin/src/scripts/dscreate.map \ + ldap/admin/src/scripts/dscreate.map ldap/admin/src/scripts/remove-ds.pl \ ldap/admin/src/scripts/DSCreate.pm ldap/admin/src/scripts/DSMigration.pm \ ldap/admin/src/scripts/dsorgentries.map ldap/admin/src/scripts/migrate-ds.pl \ ldap/admin/src/scripts/Migration.pm ldap/admin/src/scripts/SetupDialogs.pm \ @@ -1239,7 +1238,8 @@ schema_DATA = $(srcdir)/ldap/schema/00core.ldif \ $(srcdir)/ldap/schema/99user.ldif sbin_SCRIPTS = ldap/admin/src/scripts/setup-ds.pl \ - ldap/admin/src/scripts/migrate-ds.pl + ldap/admin/src/scripts/migrate-ds.pl \ + ldap/admin/src/scripts/remove-ds.pl bin_SCRIPTS = ldap/servers/slapd/tools/rsearch/scripts/dbgen.pl \ wrappers/dbscan \ @@ -1338,7 +1338,8 @@ dist_man_MANS = man/man1/dbscan.1 \ man/man1/rsearch.1 \ man/man8/migrate-ds.pl.8 \ man/man8/ns-slapd.8 \ - man/man8/setup-ds.pl.8 + man/man8/setup-ds.pl.8 \ + man/man8/remove-ds.pl.8 #//////////////////////////////////////////////////////////////// diff --git a/aclocal.m4 b/aclocal.m4 index 2b62cd1e7..64ecbe7fa 100644 --- a/aclocal.m4 +++ b/aclocal.m4 @@ -1578,27 +1578,10 @@ linux*) # before this can be enabled. hardcode_into_libs=yes - # find out which ABI we are using - libsuff= - case "$host_cpu" in - x86_64*|s390x*|powerpc64*) - echo '[#]line __oline__ "configure"' > conftest.$ac_ext - if AC_TRY_EVAL(ac_compile); then - case `/usr/bin/file conftest.$ac_objext` in - *64-bit*) - libsuff=64 - sys_lib_search_path_spec="/lib${libsuff} /usr/lib${libsuff} /usr/local/lib${libsuff}" - ;; - esac - fi - rm -rf conftest* - ;; - esac - # Append ld.so.conf contents to the search path if test -f /etc/ld.so.conf; then - lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \[$]2)); skip = 1; } { if (!skip) print \[$]0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '` - sys_lib_dlsearch_path_spec="/lib${libsuff} /usr/lib${libsuff} $lt_ld_extra" + lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s", \[$]2)); skip = 1; } { if (!skip) print \[$]0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '` + sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" fi # We used to test for /lib/ld.so.1 and disable shared libraries on @@ -4305,9 +4288,6 @@ CC=$lt_[]_LT_AC_TAGVAR(compiler, $1) # Is the compiler the GNU C compiler? with_gcc=$_LT_AC_TAGVAR(GCC, $1) -gcc_dir=\`gcc -print-file-name=. | $SED 's,/\.$,,'\` -gcc_ver=\`gcc -dumpversion\` - # An ERE matcher. EGREP=$lt_EGREP @@ -4441,11 +4421,11 @@ striplib=$lt_striplib # Dependencies to place before the objects being linked to create a # shared library. -predep_objects=\`echo $lt_[]_LT_AC_TAGVAR(predep_objects, $1) | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` +predep_objects=$lt_[]_LT_AC_TAGVAR(predep_objects, $1) # Dependencies to place after the objects being linked to create a # shared library. -postdep_objects=\`echo $lt_[]_LT_AC_TAGVAR(postdep_objects, $1) | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` +postdep_objects=$lt_[]_LT_AC_TAGVAR(postdep_objects, $1) # Dependencies to place before the objects being linked to create a # shared library. @@ -4457,7 +4437,7 @@ postdeps=$lt_[]_LT_AC_TAGVAR(postdeps, $1) # The library search path used internally by the compiler when linking # a shared library. -compiler_lib_search_path=\`echo $lt_[]_LT_AC_TAGVAR(compiler_lib_search_path, $1) | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` +compiler_lib_search_path=$lt_[]_LT_AC_TAGVAR(compiler_lib_search_path, $1) # Method to check whether dependent libraries are shared objects. deplibs_check_method=$lt_deplibs_check_method @@ -4537,7 +4517,7 @@ variables_saved_for_relink="$variables_saved_for_relink" link_all_deplibs=$_LT_AC_TAGVAR(link_all_deplibs, $1) # Compile-time system search path for libraries -sys_lib_search_path_spec=\`echo $lt_sys_lib_search_path_spec | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` +sys_lib_search_path_spec=$lt_sys_lib_search_path_spec # Run-time system search path for libraries sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec @@ -6373,7 +6353,6 @@ do done done done -IFS=$as_save_IFS lt_ac_max=0 lt_ac_count=0 # Add /usr/xpg4/bin/sed as it is typically found on Solaris @@ -6406,7 +6385,6 @@ for lt_ac_sed in $lt_ac_sed_list /usr/xpg4/bin/sed; do done ]) SED=$lt_cv_path_SED -AC_SUBST([SED]) AC_MSG_RESULT([$SED]) ]) diff --git a/configure b/configure index 8c3377ad4..9648f85e4 100755 --- a/configure +++ b/configure @@ -465,7 +465,7 @@ ac_includes_default="\ #endif" ac_default_prefix=/opt/$PACKAGE_NAME -ac_subst_vars='SHELL PATH_SEPARATOR PACKAGE_NAME PACKAGE_TARNAME PACKAGE_VERSION PACKAGE_STRING PACKAGE_BUGREPORT exec_prefix prefix program_transform_name bindir sbindir libexecdir datadir sysconfdir sharedstatedir localstatedir libdir includedir oldincludedir infodir mandir build_alias host_alias target_alias DEFS ECHO_C ECHO_N ECHO_T LIBS INSTALL_PROGRAM INSTALL_SCRIPT INSTALL_DATA CYGPATH_W PACKAGE VERSION ACLOCAL AUTOCONF AUTOMAKE AUTOHEADER MAKEINFO install_sh STRIP ac_ct_STRIP INSTALL_STRIP_PROGRAM mkdir_p AWK SET_MAKE am__leading_dot AMTAR am__tar am__untar MAINTAINER_MODE_TRUE MAINTAINER_MODE_FALSE MAINT build build_cpu build_vendor build_os host host_cpu host_vendor host_os CXX CXXFLAGS LDFLAGS CPPFLAGS ac_ct_CXX EXEEXT OBJEXT DEPDIR am__include am__quote AMDEP_TRUE AMDEP_FALSE AMDEPBACKSLASH CXXDEPMODE am__fastdepCXX_TRUE am__fastdepCXX_FALSE CC CFLAGS ac_ct_CC CCDEPMODE am__fastdepCC_TRUE am__fastdepCC_FALSE CCAS CCASFLAGS SED EGREP LN_S ECHO AR ac_ct_AR RANLIB ac_ct_RANLIB CPP CXXCPP F77 FFLAGS ac_ct_F77 LIBTOOL LIBOBJS debug_defs BUNDLE_TRUE BUNDLE_FALSE enable_pam_passthru_TRUE enable_pam_passthru_FALSE enable_dna_TRUE enable_dna_FALSE enable_ldapi_TRUE enable_ldapi_FALSE enable_autobind_TRUE enable_autobind_FALSE enable_auto_dn_suffix_TRUE enable_auto_dn_suffix_FALSE enable_bitwise_TRUE enable_bitwise_FALSE with_fhs_opt configdir sampledatadir propertydir schemadir serverdir serverplugindir scripttemplatedir perldir infdir mibdir defaultuser defaultgroup instconfigdir WINNT_TRUE WINNT_FALSE LIBSOCKET LIBNSL LIBDL LIBCSTD LIBCRUN initdir perlexec initconfigdir HPUX_TRUE HPUX_FALSE SOLARIS_TRUE SOLARIS_FALSE PKG_CONFIG ICU_CONFIG NETSNMP_CONFIG KRB5_CONFIG_BIN kerberos_inc kerberos_lib kerberos_libdir PACKAGE_BASE_VERSION nspr_inc nspr_lib nspr_libdir nss_inc nss_lib nss_libdir ldapsdk_inc ldapsdk_lib ldapsdk_libdir ldapsdk_bindir db_inc db_incdir db_lib db_libdir db_bindir db_libver sasl_inc sasl_lib sasl_libdir sasl_path svrcore_inc svrcore_lib icu_lib icu_inc icu_bin netsnmp_inc netsnmp_lib netsnmp_libdir netsnmp_link brand capbrand vendor LTLIBOBJS' +ac_subst_vars='SHELL PATH_SEPARATOR PACKAGE_NAME PACKAGE_TARNAME PACKAGE_VERSION PACKAGE_STRING PACKAGE_BUGREPORT exec_prefix prefix program_transform_name bindir sbindir libexecdir datadir sysconfdir sharedstatedir localstatedir libdir includedir oldincludedir infodir mandir build_alias host_alias target_alias DEFS ECHO_C ECHO_N ECHO_T LIBS INSTALL_PROGRAM INSTALL_SCRIPT INSTALL_DATA CYGPATH_W PACKAGE VERSION ACLOCAL AUTOCONF AUTOMAKE AUTOHEADER MAKEINFO install_sh STRIP ac_ct_STRIP INSTALL_STRIP_PROGRAM mkdir_p AWK SET_MAKE am__leading_dot AMTAR am__tar am__untar MAINTAINER_MODE_TRUE MAINTAINER_MODE_FALSE MAINT build build_cpu build_vendor build_os host host_cpu host_vendor host_os CXX CXXFLAGS LDFLAGS CPPFLAGS ac_ct_CXX EXEEXT OBJEXT DEPDIR am__include am__quote AMDEP_TRUE AMDEP_FALSE AMDEPBACKSLASH CXXDEPMODE am__fastdepCXX_TRUE am__fastdepCXX_FALSE CC CFLAGS ac_ct_CC CCDEPMODE am__fastdepCC_TRUE am__fastdepCC_FALSE CCAS CCASFLAGS EGREP LN_S ECHO AR ac_ct_AR RANLIB ac_ct_RANLIB CPP CXXCPP F77 FFLAGS ac_ct_F77 LIBTOOL LIBOBJS debug_defs BUNDLE_TRUE BUNDLE_FALSE enable_pam_passthru_TRUE enable_pam_passthru_FALSE enable_dna_TRUE enable_dna_FALSE enable_ldapi_TRUE enable_ldapi_FALSE enable_autobind_TRUE enable_autobind_FALSE enable_auto_dn_suffix_TRUE enable_auto_dn_suffix_FALSE enable_bitwise_TRUE enable_bitwise_FALSE with_fhs_opt configdir sampledatadir propertydir schemadir serverdir serverplugindir scripttemplatedir perldir infdir mibdir defaultuser defaultgroup instconfigdir WINNT_TRUE WINNT_FALSE LIBSOCKET LIBNSL LIBDL LIBCSTD LIBCRUN initdir perlexec initconfigdir HPUX_TRUE HPUX_FALSE SOLARIS_TRUE SOLARIS_FALSE PKG_CONFIG ICU_CONFIG NETSNMP_CONFIG KRB5_CONFIG_BIN kerberos_inc kerberos_lib kerberos_libdir PACKAGE_BASE_VERSION nspr_inc nspr_lib nspr_libdir nss_inc nss_lib nss_libdir ldapsdk_inc ldapsdk_lib ldapsdk_libdir ldapsdk_bindir db_inc db_incdir db_lib db_libdir db_bindir db_libver sasl_inc sasl_lib sasl_libdir sasl_path svrcore_inc svrcore_lib icu_lib icu_inc icu_bin netsnmp_inc netsnmp_lib netsnmp_libdir netsnmp_link brand capbrand vendor LTLIBOBJS' ac_subst_files='' # Initialize some variables set by options. @@ -3876,7 +3876,6 @@ do done done done -IFS=$as_save_IFS lt_ac_max=0 lt_ac_count=0 # Add /usr/xpg4/bin/sed as it is typically found on Solaris @@ -3911,7 +3910,6 @@ done fi SED=$lt_cv_path_SED - echo "$as_me:$LINENO: result: $SED" >&5 echo "${ECHO_T}$SED" >&6 @@ -4352,7 +4350,7 @@ ia64-*-hpux*) ;; *-*-irix6*) # Find out which ABI we are using. - echo '#line 4355 "configure"' > conftest.$ac_ext + echo '#line 4353 "configure"' > conftest.$ac_ext if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 (eval $ac_compile) 2>&5 ac_status=$? @@ -5487,7 +5485,7 @@ fi # Provide some information about the compiler. -echo "$as_me:5490:" \ +echo "$as_me:5488:" \ "checking for Fortran 77 compiler version" >&5 ac_compiler=`set X $ac_compile; echo $2` { (eval echo "$as_me:$LINENO: \"$ac_compiler --version </dev/null >&5\"") >&5 @@ -6550,11 +6548,11 @@ else -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:6553: $lt_compile\"" >&5) + (eval echo "\"\$as_me:6551: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 - echo "$as_me:6557: \$? = $ac_status" >&5 + echo "$as_me:6555: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. @@ -6818,11 +6816,11 @@ else -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:6821: $lt_compile\"" >&5) + (eval echo "\"\$as_me:6819: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 - echo "$as_me:6825: \$? = $ac_status" >&5 + echo "$as_me:6823: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. @@ -6922,11 +6920,11 @@ else -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:6925: $lt_compile\"" >&5) + (eval echo "\"\$as_me:6923: $lt_compile\"" >&5) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&5 - echo "$as_me:6929: \$? = $ac_status" >&5 + echo "$as_me:6927: \$? = $ac_status" >&5 if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized @@ -8387,31 +8385,10 @@ linux*) # before this can be enabled. hardcode_into_libs=yes - # find out which ABI we are using - libsuff= - case "$host_cpu" in - x86_64*|s390x*|powerpc64*) - echo '#line 8394 "configure"' > conftest.$ac_ext - if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; then - case `/usr/bin/file conftest.$ac_objext` in - *64-bit*) - libsuff=64 - sys_lib_search_path_spec="/lib${libsuff} /usr/lib${libsuff} /usr/local/lib${libsuff}" - ;; - esac - fi - rm -rf conftest* - ;; - esac - # Append ld.so.conf contents to the search path if test -f /etc/ld.so.conf; then - lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '` - sys_lib_dlsearch_path_spec="/lib${libsuff} /usr/lib${libsuff} $lt_ld_extra" + lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '` + sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" fi # We used to test for /lib/ld.so.1 and disable shared libraries on @@ -9288,7 +9265,7 @@ else lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 lt_status=$lt_dlunknown cat > conftest.$ac_ext <<EOF -#line 9291 "configure" +#line 9268 "configure" #include "confdefs.h" #if HAVE_DLFCN_H @@ -9388,7 +9365,7 @@ else lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 lt_status=$lt_dlunknown cat > conftest.$ac_ext <<EOF -#line 9391 "configure" +#line 9368 "configure" #include "confdefs.h" #if HAVE_DLFCN_H @@ -9719,9 +9696,6 @@ CC=$lt_compiler # Is the compiler the GNU C compiler? with_gcc=$GCC -gcc_dir=\`gcc -print-file-name=. | $SED 's,/\.$,,'\` -gcc_ver=\`gcc -dumpversion\` - # An ERE matcher. EGREP=$lt_EGREP @@ -9855,11 +9829,11 @@ striplib=$lt_striplib # Dependencies to place before the objects being linked to create a # shared library. -predep_objects=\`echo $lt_predep_objects | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` +predep_objects=$lt_predep_objects # Dependencies to place after the objects being linked to create a # shared library. -postdep_objects=\`echo $lt_postdep_objects | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` +postdep_objects=$lt_postdep_objects # Dependencies to place before the objects being linked to create a # shared library. @@ -9871,7 +9845,7 @@ postdeps=$lt_postdeps # The library search path used internally by the compiler when linking # a shared library. -compiler_lib_search_path=\`echo $lt_compiler_lib_search_path | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` +compiler_lib_search_path=$lt_compiler_lib_search_path # Method to check whether dependent libraries are shared objects. deplibs_check_method=$lt_deplibs_check_method @@ -9951,7 +9925,7 @@ variables_saved_for_relink="$variables_saved_for_relink" link_all_deplibs=$link_all_deplibs # Compile-time system search path for libraries -sys_lib_search_path_spec=\`echo $lt_sys_lib_search_path_spec | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` +sys_lib_search_path_spec=$lt_sys_lib_search_path_spec # Run-time system search path for libraries sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec @@ -11731,11 +11705,11 @@ else -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:11734: $lt_compile\"" >&5) + (eval echo "\"\$as_me:11708: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 - echo "$as_me:11738: \$? = $ac_status" >&5 + echo "$as_me:11712: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. @@ -11835,11 +11809,11 @@ else -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:11838: $lt_compile\"" >&5) + (eval echo "\"\$as_me:11812: $lt_compile\"" >&5) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&5 - echo "$as_me:11842: \$? = $ac_status" >&5 + echo "$as_me:11816: \$? = $ac_status" >&5 if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized @@ -12367,31 +12341,10 @@ linux*) # before this can be enabled. hardcode_into_libs=yes - # find out which ABI we are using - libsuff= - case "$host_cpu" in - x86_64*|s390x*|powerpc64*) - echo '#line 12374 "configure"' > conftest.$ac_ext - if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; then - case `/usr/bin/file conftest.$ac_objext` in - *64-bit*) - libsuff=64 - sys_lib_search_path_spec="/lib${libsuff} /usr/lib${libsuff} /usr/local/lib${libsuff}" - ;; - esac - fi - rm -rf conftest* - ;; - esac - # Append ld.so.conf contents to the search path if test -f /etc/ld.so.conf; then - lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '` - sys_lib_dlsearch_path_spec="/lib${libsuff} /usr/lib${libsuff} $lt_ld_extra" + lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '` + sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" fi # We used to test for /lib/ld.so.1 and disable shared libraries on @@ -12775,9 +12728,6 @@ CC=$lt_compiler_CXX # Is the compiler the GNU C compiler? with_gcc=$GCC_CXX -gcc_dir=\`gcc -print-file-name=. | $SED 's,/\.$,,'\` -gcc_ver=\`gcc -dumpversion\` - # An ERE matcher. EGREP=$lt_EGREP @@ -12911,11 +12861,11 @@ striplib=$lt_striplib # Dependencies to place before the objects being linked to create a # shared library. -predep_objects=\`echo $lt_predep_objects_CXX | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` +predep_objects=$lt_predep_objects_CXX # Dependencies to place after the objects being linked to create a # shared library. -postdep_objects=\`echo $lt_postdep_objects_CXX | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` +postdep_objects=$lt_postdep_objects_CXX # Dependencies to place before the objects being linked to create a # shared library. @@ -12927,7 +12877,7 @@ postdeps=$lt_postdeps_CXX # The library search path used internally by the compiler when linking # a shared library. -compiler_lib_search_path=\`echo $lt_compiler_lib_search_path_CXX | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` +compiler_lib_search_path=$lt_compiler_lib_search_path_CXX # Method to check whether dependent libraries are shared objects. deplibs_check_method=$lt_deplibs_check_method @@ -13007,7 +12957,7 @@ variables_saved_for_relink="$variables_saved_for_relink" link_all_deplibs=$link_all_deplibs_CXX # Compile-time system search path for libraries -sys_lib_search_path_spec=\`echo $lt_sys_lib_search_path_spec | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` +sys_lib_search_path_spec=$lt_sys_lib_search_path_spec # Run-time system search path for libraries sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec @@ -13429,11 +13379,11 @@ else -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:13432: $lt_compile\"" >&5) + (eval echo "\"\$as_me:13382: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 - echo "$as_me:13436: \$? = $ac_status" >&5 + echo "$as_me:13386: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. @@ -13533,11 +13483,11 @@ else -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:13536: $lt_compile\"" >&5) + (eval echo "\"\$as_me:13486: $lt_compile\"" >&5) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&5 - echo "$as_me:13540: \$? = $ac_status" >&5 + echo "$as_me:13490: \$? = $ac_status" >&5 if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized @@ -14978,31 +14928,10 @@ linux*) # before this can be enabled. hardcode_into_libs=yes - # find out which ABI we are using - libsuff= - case "$host_cpu" in - x86_64*|s390x*|powerpc64*) - echo '#line 14985 "configure"' > conftest.$ac_ext - if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; then - case `/usr/bin/file conftest.$ac_objext` in - *64-bit*) - libsuff=64 - sys_lib_search_path_spec="/lib${libsuff} /usr/lib${libsuff} /usr/local/lib${libsuff}" - ;; - esac - fi - rm -rf conftest* - ;; - esac - # Append ld.so.conf contents to the search path if test -f /etc/ld.so.conf; then - lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '` - sys_lib_dlsearch_path_spec="/lib${libsuff} /usr/lib${libsuff} $lt_ld_extra" + lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '` + sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" fi # We used to test for /lib/ld.so.1 and disable shared libraries on @@ -15386,9 +15315,6 @@ CC=$lt_compiler_F77 # Is the compiler the GNU C compiler? with_gcc=$GCC_F77 -gcc_dir=\`gcc -print-file-name=. | $SED 's,/\.$,,'\` -gcc_ver=\`gcc -dumpversion\` - # An ERE matcher. EGREP=$lt_EGREP @@ -15522,11 +15448,11 @@ striplib=$lt_striplib # Dependencies to place before the objects being linked to create a # shared library. -predep_objects=\`echo $lt_predep_objects_F77 | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` +predep_objects=$lt_predep_objects_F77 # Dependencies to place after the objects being linked to create a # shared library. -postdep_objects=\`echo $lt_postdep_objects_F77 | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` +postdep_objects=$lt_postdep_objects_F77 # Dependencies to place before the objects being linked to create a # shared library. @@ -15538,7 +15464,7 @@ postdeps=$lt_postdeps_F77 # The library search path used internally by the compiler when linking # a shared library. -compiler_lib_search_path=\`echo $lt_compiler_lib_search_path_F77 | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` +compiler_lib_search_path=$lt_compiler_lib_search_path_F77 # Method to check whether dependent libraries are shared objects. deplibs_check_method=$lt_deplibs_check_method @@ -15618,7 +15544,7 @@ variables_saved_for_relink="$variables_saved_for_relink" link_all_deplibs=$link_all_deplibs_F77 # Compile-time system search path for libraries -sys_lib_search_path_spec=\`echo $lt_sys_lib_search_path_spec | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` +sys_lib_search_path_spec=$lt_sys_lib_search_path_spec # Run-time system search path for libraries sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec @@ -15760,11 +15686,11 @@ else -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:15763: $lt_compile\"" >&5) + (eval echo "\"\$as_me:15689: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 - echo "$as_me:15767: \$? = $ac_status" >&5 + echo "$as_me:15693: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. @@ -16028,11 +15954,11 @@ else -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:16031: $lt_compile\"" >&5) + (eval echo "\"\$as_me:15957: $lt_compile\"" >&5) (eval "$lt_compile" 2>conftest.err) ac_status=$? cat conftest.err >&5 - echo "$as_me:16035: \$? = $ac_status" >&5 + echo "$as_me:15961: \$? = $ac_status" >&5 if (exit $ac_status) && test -s "$ac_outfile"; then # The compiler can only warn and ignore the option if not recognized # So say no if there are warnings other than the usual output. @@ -16132,11 +16058,11 @@ else -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ -e 's:$: $lt_compiler_flag:'` - (eval echo "\"\$as_me:16135: $lt_compile\"" >&5) + (eval echo "\"\$as_me:16061: $lt_compile\"" >&5) (eval "$lt_compile" 2>out/conftest.err) ac_status=$? cat out/conftest.err >&5 - echo "$as_me:16139: \$? = $ac_status" >&5 + echo "$as_me:16065: \$? = $ac_status" >&5 if (exit $ac_status) && test -s out/conftest2.$ac_objext then # The compiler can only warn and ignore the option if not recognized @@ -17597,31 +17523,10 @@ linux*) # before this can be enabled. hardcode_into_libs=yes - # find out which ABI we are using - libsuff= - case "$host_cpu" in - x86_64*|s390x*|powerpc64*) - echo '#line 17604 "configure"' > conftest.$ac_ext - if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5 - (eval $ac_compile) 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; then - case `/usr/bin/file conftest.$ac_objext` in - *64-bit*) - libsuff=64 - sys_lib_search_path_spec="/lib${libsuff} /usr/lib${libsuff} /usr/local/lib${libsuff}" - ;; - esac - fi - rm -rf conftest* - ;; - esac - # Append ld.so.conf contents to the search path if test -f /etc/ld.so.conf; then - lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s 2>/dev/null", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '` - sys_lib_dlsearch_path_spec="/lib${libsuff} /usr/lib${libsuff} $lt_ld_extra" + lt_ld_extra=`awk '/^include / { system(sprintf("cd /etc; cat %s", \$2)); skip = 1; } { if (!skip) print \$0; skip = 0; }' < /etc/ld.so.conf | $SED -e 's/#.*//;s/[:, ]/ /g;s/=[^=]*$//;s/=[^= ]* / /g;/^$/d' | tr '\n' ' '` + sys_lib_dlsearch_path_spec="/lib /usr/lib $lt_ld_extra" fi # We used to test for /lib/ld.so.1 and disable shared libraries on @@ -18005,9 +17910,6 @@ CC=$lt_compiler_GCJ # Is the compiler the GNU C compiler? with_gcc=$GCC_GCJ -gcc_dir=\`gcc -print-file-name=. | $SED 's,/\.$,,'\` -gcc_ver=\`gcc -dumpversion\` - # An ERE matcher. EGREP=$lt_EGREP @@ -18141,11 +18043,11 @@ striplib=$lt_striplib # Dependencies to place before the objects being linked to create a # shared library. -predep_objects=\`echo $lt_predep_objects_GCJ | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` +predep_objects=$lt_predep_objects_GCJ # Dependencies to place after the objects being linked to create a # shared library. -postdep_objects=\`echo $lt_postdep_objects_GCJ | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` +postdep_objects=$lt_postdep_objects_GCJ # Dependencies to place before the objects being linked to create a # shared library. @@ -18157,7 +18059,7 @@ postdeps=$lt_postdeps_GCJ # The library search path used internally by the compiler when linking # a shared library. -compiler_lib_search_path=\`echo $lt_compiler_lib_search_path_GCJ | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` +compiler_lib_search_path=$lt_compiler_lib_search_path_GCJ # Method to check whether dependent libraries are shared objects. deplibs_check_method=$lt_deplibs_check_method @@ -18237,7 +18139,7 @@ variables_saved_for_relink="$variables_saved_for_relink" link_all_deplibs=$link_all_deplibs_GCJ # Compile-time system search path for libraries -sys_lib_search_path_spec=\`echo $lt_sys_lib_search_path_spec | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` +sys_lib_search_path_spec=$lt_sys_lib_search_path_spec # Run-time system search path for libraries sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec @@ -18489,9 +18391,6 @@ CC=$lt_compiler_RC # Is the compiler the GNU C compiler? with_gcc=$GCC_RC -gcc_dir=\`gcc -print-file-name=. | $SED 's,/\.$,,'\` -gcc_ver=\`gcc -dumpversion\` - # An ERE matcher. EGREP=$lt_EGREP @@ -18625,11 +18524,11 @@ striplib=$lt_striplib # Dependencies to place before the objects being linked to create a # shared library. -predep_objects=\`echo $lt_predep_objects_RC | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` +predep_objects=$lt_predep_objects_RC # Dependencies to place after the objects being linked to create a # shared library. -postdep_objects=\`echo $lt_postdep_objects_RC | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` +postdep_objects=$lt_postdep_objects_RC # Dependencies to place before the objects being linked to create a # shared library. @@ -18641,7 +18540,7 @@ postdeps=$lt_postdeps_RC # The library search path used internally by the compiler when linking # a shared library. -compiler_lib_search_path=\`echo $lt_compiler_lib_search_path_RC | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` +compiler_lib_search_path=$lt_compiler_lib_search_path_RC # Method to check whether dependent libraries are shared objects. deplibs_check_method=$lt_deplibs_check_method @@ -18721,7 +18620,7 @@ variables_saved_for_relink="$variables_saved_for_relink" link_all_deplibs=$link_all_deplibs_RC # Compile-time system search path for libraries -sys_lib_search_path_spec=\`echo $lt_sys_lib_search_path_spec | \$SED -e "s@\${gcc_dir}@\\\${gcc_dir}@g;s@\${gcc_ver}@\\\${gcc_ver}@g"\` +sys_lib_search_path_spec=$lt_sys_lib_search_path_spec # Run-time system search path for libraries sys_lib_dlsearch_path_spec=$lt_sys_lib_dlsearch_path_spec @@ -27183,7 +27082,6 @@ s,@am__fastdepCC_TRUE@,$am__fastdepCC_TRUE,;t t s,@am__fastdepCC_FALSE@,$am__fastdepCC_FALSE,;t t s,@CCAS@,$CCAS,;t t s,@CCASFLAGS@,$CCASFLAGS,;t t -s,@SED@,$SED,;t t s,@EGREP@,$EGREP,;t t s,@LN_S@,$LN_S,;t t s,@ECHO@,$ECHO,;t t diff --git a/ldap/admin/src/scripts/remove-ds.pl.in b/ldap/admin/src/scripts/remove-ds.pl.in new file mode 100755 index 000000000..fadbbe908 --- /dev/null +++ b/ldap/admin/src/scripts/remove-ds.pl.in @@ -0,0 +1,233 @@ +#!@perlexec@ +# BEGIN COPYRIGHT BLOCK +# This Program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation; version 2 of the License. +# +# This Program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this Program; if not, write to the Free Software Foundation, Inc., 59 Temple +# Place, Suite 330, Boston, MA 02111-1307 USA. +# +# Copyright (C) 2007 Red Hat, Inc. +# All rights reserved. +# END COPYRIGHT BLOCK +# + +use lib qw(@perlpath@); + +use strict; + +use File::Basename; +use File::Path; +use Util; +use FileConn; + +sub usage { + print(STDERR "Usage: $0 [-f] -i instance\n\n"); + print(STDERR " Opts: -f - force removal\n"); + print(STDERR " -i instance - instance name to remove (e.g. - slapd-example)\n"); +} + +# remove_tree($centry, $key, $instname, [$isparent, [$dontremove]]) +# $centry: entry to look for the path to be removed +# $key: key to look for the path in the entry +# $instname: instance name "slapd-<ID>" to check the path +# $isparent: specify 1 to remove from the parent dir +# $dontremove: pattern not to be removed (e.g., ".db$") +sub remove_tree +{ + my $centry = shift; + my $key = shift; + my $instname = shift; + my $isparent = shift; + my $dontremove = shift; + + foreach my $path ( @{$centry->{$key}} ) + { + my $rmdir = ""; + my $rc = 0; + if ( 1 == $isparent ) + { + $rmdir = dirname($path); + } + else + { + $rmdir = $path; + } + if ( -d $rmdir && $rmdir =~ /$instname/ ) + { + if ( "" eq "$dontremove" ) + { + $rc = rmtree($rmdir); + if ( 0 == $rc ) + { + print STDERR "Warning: $rmdir was not removed.\n"; + } + } + else + { + # Skip the dontremove files + $rc = opendir(DIR, $rmdir); + if ($rc) + { + while (defined(my $file = readdir(DIR))) + { + next if ( "$file" =~ /$dontremove/ ); + next if ( "$file" eq "." ); + next if ( "$file" eq ".." ); + my $rmfile = $rmdir . "/" . $file; + my $rc0 = rmtree($rmfile); + if ( 0 == $rc0 ) + { + print STDERR "Warning: $rmfile was not removed.\n"; + } + } + closedir(DIR); + } + my $newrmdir = $rmdir . ".removed"; + my $rc1 = 1; + if ( -d $newrmdir ) + { + $rc1 = rmtree($newrmdir); + if ( 0 == $rc1 ) + { + print STDERR "Warning: $newrmdir was not removed.\n"; + } + } + if ( 0 < $rc1 ) + { + rename($rmdir, $newrmdir); + } + } + } + } +} + +sub remove_pidfile +{ + my ($type, $instdir, $instname) = @_; + + my $pattern = "^" . $type . ".*="; + my $pidline = `grep $pattern $instdir/start-slapd`; + chomp($pidline); + my ($key, $pidfile) = split(/=/, $pidline); + if ( -e $pidfile && $pidfile =~ /$instname/ ) + { + unlink($pidfile); + } +} + +my $i = 0; +my $force = ""; +my $instname = ""; + +if ($#ARGV > 2) { + &usage; exit(1); +} + +# load args from the command line +while ($i <= $#ARGV) { + if ( "$ARGV[$i]" eq "-f" ) { + $force = 1; + } elsif ("$ARGV[$i]" eq "-i") { + $i++; + $instname = $ARGV[$i]; + } + $i++; +} + +# Make sure the instance name option was provided. +unless ($instname) { + &usage; exit(1); +} + +# Make sure a full instance name was provided. +my ($slapd, $inst) = split(/-/, $instname, 2); +unless ($inst) { + print STDERR "Full instance name must be specified (e.g. - slapd-example)\n"; + exit 1; +} + +my $configdir = "@instconfigdir@/slapd-$inst"; +if ( ! -d $configdir ) +{ + print STDERR "Error: $configdir does not exist\n"; + exit 1; +} + +# read the config file to find out the paths +my $dseldif = "@instconfigdir@/$instname/dse.ldif"; +my $conn = new FileConn($dseldif); + +my $dn = "cn=config"; +my $entry = $conn->search($dn, "base", "(cn=*)", 0); +if (!$entry) +{ + print STDERR "Error: Search $dn in $dseldif failed: $entry\n"; + exit 1; +} + +$dn = "cn=config,cn=ldbm database,cn=plugins,cn=config"; +my $dbentry = $conn->search($dn, "base", "(cn=*)", 0); +if (!$dbentry) +{ + print "Error: Search $dn in $dseldif failed: $dbentry\n"; + exit 1; +} +$conn->close(); + +# stop the server +my $instdir = ""; +foreach my $path ( @{$entry->{"nsslapd-instancedir"}} ) +{ + if ( -d $path ) + { + my $prog = $path . "/stop-slapd"; + if (-x $prog) { + $? = 0; + # run the stop command + my $output = `$prog 2>&1`; + my $status = $?; + if ($status) { + # Ignore the stop failure + print STDERR "Warning: Could not stop directory server: $output\n"; + } + $instdir = $path; # need to use it later... + } elsif (!$force) { + print STDERR "Error: The program $prog does not exist\n"; + exit 1; + } + } +} + +# remove physical dirs/files +remove_tree($dbentry, "nsslapd-directory", $instname, 1); +remove_tree($dbentry, "nsslapd-db-logdirectory", $instname, 1); +remove_tree($entry, "nsslapd-lockdir", $instname); +remove_tree($entry, "nsslapd-tmpdir", $instname); +remove_tree($entry, "nsslapd-bakdir", $instname, 1); +remove_tree($entry, "nsslapd-errorlog", $instname, 1); + +# instance dir +if ( -d $instdir && $instdir =~ /$instname/ ) +{ + # clean up pid files (if any) + remove_pidfile("STARTPIDFILE", $instdir, $instname); + remove_pidfile("PIDFILE", $instdir, $instname); + + my $rc = rmtree($instdir); + if ( 0 == $rc ) + { + print STDERR "Warning: $instdir was not removed.\n"; + } +} +# Finally, config dir +remove_tree($entry, "nsslapd-schemadir", $instname, 1, "\.db\$"); + +# if we got here, report success +print "Instance $instname removed.\n"; +exit 0; diff --git a/ltmain.sh b/ltmain.sh index 0223495a0..06823e057 100644 --- a/ltmain.sh +++ b/ltmain.sh @@ -46,16 +46,10 @@ PACKAGE=libtool VERSION=1.5.22 TIMESTAMP=" (1.1220.2.365 2005/12/18 22:14:06)" -# Be Bourne compatible (taken from Autoconf:_AS_BOURNE_COMPATIBLE). -if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then - emulate sh - NULLCMD=: - # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which - # is contrary to our usage. Disable this feature. - alias -g '${1+"$@"}'='"$@"' +# See if we are running on zsh, and set the options which allow our +# commands through without removal of \ escapes. +if test -n "${ZSH_VERSION+set}" ; then setopt NO_GLOB_SUBST -else - case `(set -o) 2>/dev/null` in *posix*) set -o posix;; esac fi # Check that we have a working $echo. @@ -111,14 +105,12 @@ esac # These must not be set unconditionally because not all systems understand # e.g. LANG=C (notably SCO). # We save the old values to restore during execute mode. -for lt_var in LANG LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES -do - eval "if test \"\${$lt_var+set}\" = set; then - save_$lt_var=\$$lt_var - $lt_var=C - export $lt_var - fi" -done +if test "${LC_ALL+set}" = set; then + save_LC_ALL="$LC_ALL"; LC_ALL=C; export LC_ALL +fi +if test "${LANG+set}" = set; then + save_LANG="$LANG"; LANG=C; export LANG +fi # Make sure IFS has a sensible default lt_nl=' @@ -144,8 +136,6 @@ duplicate_deps=no preserve_args= lo2o="s/\\.lo\$/.${objext}/" o2lo="s/\\.${objext}\$/.lo/" -extracted_archives= -extracted_serial=0 ##################################### # Shell function definitions: @@ -337,17 +327,7 @@ func_extract_archives () *) my_xabs=`pwd`"/$my_xlib" ;; esac my_xlib=`$echo "X$my_xlib" | $Xsed -e 's%^.*/%%'` - my_xlib_u=$my_xlib - while :; do - case " $extracted_archives " in - *" $my_xlib_u "*) - extracted_serial=`expr $extracted_serial + 1` - my_xlib_u=lt$extracted_serial-$my_xlib ;; - *) break ;; - esac - done - extracted_archives="$extracted_archives $my_xlib_u" - my_xdir="$my_gentop/$my_xlib_u" + my_xdir="$my_gentop/$my_xlib" $show "${rm}r $my_xdir" $run ${rm}r "$my_xdir" @@ -778,7 +758,6 @@ if test -z "$show_help"; then *.f90) xform=f90 ;; *.for) xform=for ;; *.java) xform=java ;; - *.obj) xform=obj ;; esac libobj=`$echo "X$libobj" | $Xsed -e "s/\.$xform$/.lo/"` @@ -1159,9 +1138,8 @@ EOF for arg do case $arg in - -all-static | -static | -static-libtool-libs) - case $arg in - -all-static) + -all-static | -static) + if test "X$arg" = "X-all-static"; then if test "$build_libtool_libs" = yes && test -z "$link_static_flag"; then $echo "$modename: warning: complete static linking is impossible in this configuration" 1>&2 fi @@ -1169,20 +1147,12 @@ EOF dlopen_self=$dlopen_self_static fi prefer_static_libs=yes - ;; - -static) + else if test -z "$pic_flag" && test -n "$link_static_flag"; then dlopen_self=$dlopen_self_static fi prefer_static_libs=built - ;; - -static-libtool-libs) - if test -z "$pic_flag" && test -n "$link_static_flag"; then - dlopen_self=$dlopen_self_static - fi - prefer_static_libs=yes - ;; - esac + fi build_libtool_libs=no build_old_libs=yes break @@ -1742,7 +1712,7 @@ EOF continue ;; - -static | -static-libtool-libs) + -static) # The effects of -static are defined in a previous loop. # We used to do the same as -all-static on platforms that # didn't have a PIC flag, but the assumption that the effects @@ -2520,9 +2490,7 @@ EOF if test "$linkmode,$pass" = "prog,link"; then if test -n "$library_names" && - { { test "$prefer_static_libs" = no || - test "$prefer_static_libs,$installed" = "built,yes"; } || - test -z "$old_library"; }; then + { test "$prefer_static_libs" = no || test -z "$old_library"; }; then # We need to hardcode the library path if test -n "$shlibpath_var" && test -z "$avoidtemprpath" ; then # Make sure the rpath contains only unique directories. @@ -3218,7 +3186,7 @@ EOF # which has an extra 1 added just for fun # case $version_type in - darwin|linux|osf|windows|none) + darwin|linux|osf|windows) current=`expr $number_major + $number_minor` age="$number_minor" revision="$number_revision" @@ -3442,11 +3410,11 @@ EOF fi # Eliminate all temporary directories. -# for path in $notinst_path; do -# lib_search_path=`$echo "$lib_search_path " | ${SED} -e "s% $path % %g"` -# deplibs=`$echo "$deplibs " | ${SED} -e "s% -L$path % %g"` -# dependency_libs=`$echo "$dependency_libs " | ${SED} -e "s% -L$path % %g"` -# done + for path in $notinst_path; do + lib_search_path=`$echo "$lib_search_path " | ${SED} -e "s% $path % %g"` + deplibs=`$echo "$deplibs " | ${SED} -e "s% -L$path % %g"` + dependency_libs=`$echo "$dependency_libs " | ${SED} -e "s% -L$path % %g"` + done if test -n "$xrpath"; then # If the user specified any rpath flags, then add them. @@ -3547,12 +3515,13 @@ EOF int main() { return 0; } EOF $rm conftest - if $LTCC $LTCFLAGS -o conftest conftest.c $deplibs; then + $LTCC $LTCFLAGS -o conftest conftest.c $deplibs + if test "$?" -eq 0 ; then ldd_output=`ldd conftest` for i in $deplibs; do name=`expr $i : '-l\(.*\)'` # If $name is empty we are operating on a -L argument. - if test "$name" != "" && test "$name" != "0"; then + if test "$name" != "" && test "$name" -ne "0"; then if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then case " $predeps $postdeps " in *" $i "*) @@ -3591,7 +3560,9 @@ EOF # If $name is empty we are operating on a -L argument. if test "$name" != "" && test "$name" != "0"; then $rm conftest - if $LTCC $LTCFLAGS -o conftest conftest.c $i; then + $LTCC $LTCFLAGS -o conftest conftest.c $i + # Did it work? + if test "$?" -eq 0 ; then ldd_output=`ldd conftest` if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then case " $predeps $postdeps " in @@ -3623,7 +3594,7 @@ EOF droppeddeps=yes $echo $echo "*** Warning! Library $i is needed by this library but I was not able to" - $echo "*** make it link in! You will probably need to install it or some" + $echo "*** make it link in! You will probably need to install it or some" $echo "*** library that it depends on before this library will be fully" $echo "*** functional. Installing it before continuing would be even better." fi @@ -4268,14 +4239,12 @@ EOF reload_conv_objs= gentop= # reload_cmds runs $LD directly, so let us get rid of - # -Wl from whole_archive_flag_spec and hope we can get by with - # turning comma into space.. + # -Wl from whole_archive_flag_spec wl= if test -n "$convenience"; then if test -n "$whole_archive_flag_spec"; then - eval tmp_whole_archive_flags=\"$whole_archive_flag_spec\" - reload_conv_objs=$reload_objs\ `$echo "X$tmp_whole_archive_flags" | $Xsed -e 's|,| |g'` + eval reload_conv_objs=\"\$reload_objs $whole_archive_flag_spec\" else gentop="$output_objdir/${obj}x" generated="$generated $gentop" @@ -4723,16 +4692,16 @@ static const void *lt_preloaded_setup() { case $host in *cygwin* | *mingw* ) if test -f "$output_objdir/${outputname}.def" ; then - compile_command=`$echo "X$compile_command" | $SP2NL | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}.def $output_objdir/${outputname}S.${objext}%" | $NL2SP` - finalize_command=`$echo "X$finalize_command" | $SP2NL | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}.def $output_objdir/${outputname}S.${objext}%" | $NL2SP` + compile_command=`$echo "X$compile_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}.def $output_objdir/${outputname}S.${objext}%"` + finalize_command=`$echo "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}.def $output_objdir/${outputname}S.${objext}%"` else - compile_command=`$echo "X$compile_command" | $SP2NL | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%" | $NL2SP` - finalize_command=`$echo "X$finalize_command" | $SP2NL | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%" | $NL2SP` + compile_command=`$echo "X$compile_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%"` + finalize_command=`$echo "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%"` fi ;; * ) - compile_command=`$echo "X$compile_command" | $SP2NL | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%" | $NL2SP` - finalize_command=`$echo "X$finalize_command" | $SP2NL | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%" | $NL2SP` + compile_command=`$echo "X$compile_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%"` + finalize_command=`$echo "X$finalize_command" | $Xsed -e "s%@SYMFILE@%$output_objdir/${outputname}S.${objext}%"` ;; esac ;; @@ -4747,13 +4716,13 @@ static const void *lt_preloaded_setup() { # really was required. # Nullify the symbol file. - compile_command=`$echo "X$compile_command" | $SP2NL | $Xsed -e "s% @SYMFILE@%%" | $NL2SP` - finalize_command=`$echo "X$finalize_command" | $SP2NL | $Xsed -e "s% @SYMFILE@%%" | $NL2SP` + compile_command=`$echo "X$compile_command" | $Xsed -e "s% @SYMFILE@%%"` + finalize_command=`$echo "X$finalize_command" | $Xsed -e "s% @SYMFILE@%%"` fi if test "$need_relink" = no || test "$build_libtool_libs" != yes; then # Replace the output file specification. - compile_command=`$echo "X$compile_command" | $SP2NL | $Xsed -e 's%@OUTPUT@%'"$output"'%g' | $NL2SP` + compile_command=`$echo "X$compile_command" | $Xsed -e 's%@OUTPUT@%'"$output"'%g'` link_command="$compile_command$compile_rpath" # We have no uninstalled library dependencies, so finalize right now. @@ -4840,7 +4809,7 @@ static const void *lt_preloaded_setup() { if test "$fast_install" != no; then link_command="$finalize_var$compile_command$finalize_rpath" if test "$fast_install" = yes; then - relink_command=`$echo "X$compile_var$compile_command$compile_rpath" | $SP2NL | $Xsed -e 's%@OUTPUT@%\$progdir/\$file%g' | $NL2SP` + relink_command=`$echo "X$compile_var$compile_command$compile_rpath" | $Xsed -e 's%@OUTPUT@%\$progdir/\$file%g'` else # fast_install is set to needless relink_command= @@ -4877,7 +4846,7 @@ static const void *lt_preloaded_setup() { fi done relink_command="(cd `pwd`; $relink_command)" - relink_command=`$echo "X$relink_command" | $SP2NL | $Xsed -e "$sed_quote_subst" | $NL2SP` + relink_command=`$echo "X$relink_command" | $Xsed -e "$sed_quote_subst"` fi # Quote $echo for shipping. @@ -5284,18 +5253,6 @@ EOF Xsed='${SED} -e 1s/^X//' sed_quote_subst='$sed_quote_subst' -# Be Bourne compatible (taken from Autoconf:_AS_BOURNE_COMPATIBLE). -if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then - emulate sh - NULLCMD=: - # Zsh 3.x and 4.x performs word splitting on \${1+\"\$@\"}, which - # is contrary to our usage. Disable this feature. - alias -g '\${1+\"\$@\"}'='\"\$@\"' - setopt NO_GLOB_SUBST -else - case \`(set -o) 2>/dev/null\` in *posix*) set -o posix;; esac -fi - # The HP-UX ksh and POSIX shell print the target directory to stdout # if CDPATH is set. (unset CDPATH) >/dev/null 2>&1 && unset CDPATH @@ -5438,7 +5395,7 @@ else ;; esac $echo >> $output "\ - \$echo \"\$0: cannot exec \$program \$*\" + \$echo \"\$0: cannot exec \$program \${1+\"\$@\"}\" exit $EXIT_FAILURE fi else @@ -5624,7 +5581,7 @@ fi\ done # Quote the link command for shipping. relink_command="(cd `pwd`; $SHELL $progpath $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)" - relink_command=`$echo "X$relink_command" | $SP2NL | $Xsed -e "$sed_quote_subst" | $NL2SP` + relink_command=`$echo "X$relink_command" | $Xsed -e "$sed_quote_subst"` if test "$hardcode_automatic" = yes ; then relink_command= fi @@ -5969,9 +5926,9 @@ relink_command=\"$relink_command\"" if test -n "$inst_prefix_dir"; then # Stick the inst_prefix_dir data into the link command. - relink_command=`$echo "$relink_command" | $SP2NL | $SED "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%" | $NL2SP` + relink_command=`$echo "$relink_command" | $SED "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%"` else - relink_command=`$echo "$relink_command" | $SP2NL | $SED "s%@inst_prefix_dir@%%" | $NL2SP` + relink_command=`$echo "$relink_command" | $SED "s%@inst_prefix_dir@%%"` fi $echo "$modename: warning: relinking \`$file'" 1>&2 @@ -6180,7 +6137,7 @@ relink_command=\"$relink_command\"" file=`$echo "X$file$stripped_ext" | $Xsed -e 's%^.*/%%'` outputname="$tmpdir/$file" # Replace the output file specification. - relink_command=`$echo "X$relink_command" | $SP2NL | $Xsed -e 's%@OUTPUT@%'"$outputname"'%g' | $NL2SP` + relink_command=`$echo "X$relink_command" | $Xsed -e 's%@OUTPUT@%'"$outputname"'%g'` $show "$relink_command" if $run eval "$relink_command"; then : @@ -6456,15 +6413,12 @@ relink_command=\"$relink_command\"" fi # Restore saved environment variables - for lt_var in LANG LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES - do - eval "if test \"\${save_$lt_var+set}\" = set; then - $lt_var=\$save_$lt_var; export $lt_var - else - $lt_unset $lt_var - fi" - done - + if test "${save_LC_ALL+set}" = set; then + LC_ALL="$save_LC_ALL"; export LC_ALL + fi + if test "${save_LANG+set}" = set; then + LANG="$save_LANG"; export LANG + fi # Now prepare to actually exec the command. exec_cmd="\$cmd$args" @@ -6821,9 +6775,9 @@ The following components of LINK-COMMAND are treated specially: -dlpreopen FILE link in FILE and add its symbols to lt_preloaded_symbols -export-dynamic allow symbols from OUTPUT-FILE to be resolved with dlsym(3) -export-symbols SYMFILE - try to export only the symbols listed in SYMFILE + try to export only the symbols listed in SYMFILE -export-symbols-regex REGEX - try to export only the symbols matching REGEX + try to export only the symbols matching REGEX -LLIBDIR search LIBDIR for required installed libraries -lNAME OUTPUT-FILE requires the installed library libNAME -module build a library that can dlopened @@ -6837,11 +6791,9 @@ The following components of LINK-COMMAND are treated specially: -release RELEASE specify package release information -rpath LIBDIR the created library will eventually be installed in LIBDIR -R[ ]LIBDIR add LIBDIR to the runtime path of programs and libraries - -static do not do any dynamic linking of uninstalled libtool libraries - -static-libtool-libs - do not do any dynamic linking of libtool libraries + -static do not do any dynamic linking of libtool libraries -version-info CURRENT[:REVISION[:AGE]] - specify library version info [each variable defaults to 0] + specify library version info [each variable defaults to 0] All other options (arguments beginning with \`-') are ignored. diff --git a/man/man8/remove-ds.pl.8 b/man/man8/remove-ds.pl.8 new file mode 100644 index 000000000..c430b0c8b --- /dev/null +++ b/man/man8/remove-ds.pl.8 @@ -0,0 +1,52 @@ +.\" Hey, EMACS: -*- nroff -*- +.\" First parameter, NAME, should be all caps +.\" Second parameter, SECTION, should be 1-8, maybe w/ subsection +.\" other parameters are allowed: see man(7), man(1) +.TH REMOVE-DS.PL 8 "Feb 13, 2009" +.\" Please adjust this date whenever revising the manpage. +.\" +.\" Some roff macros, for reference: +.\" .nh disable hyphenation +.\" .hy enable hyphenation +.\" .ad l left justify +.\" .ad b justify to both left and right margins +.\" .nf disable filling +.\" .fi enable filling +.\" .br insert line break +.\" .sp <n> insert n+1 empty lines +.\" for manpage-specific macros, see man(7) +.SH NAME +remove\-ds.pl \- Remove an instance of Directory Server +.SH SYNOPSIS +.B remove-ds.pl +[\-f] \-i \fIinstance\fR +.SH DESCRIPTION +Removes a Directory Server instance from the system. The instance +will be shutdown and the files will be removed. The certificate +database files will not be removed. The instance configuration +directory will have a .removed extension appended to it, which +will contain the retained certificate database files. +.PP +.\" TeX users may be more comfortable with the \fB<whatever>\fP and +.\" \fI<whatever>\fP escape sequences to invode bold face and italics, +.\" respectively. +.SH OPTIONS +A summary of options is included below: +.TP +.B \fB\-f\fR +Force removal +.TP +.B \fB\-i\fR \fIinstance\fR +The full name of the instance to remove (e.g. slapd-example) +.br +.SH AUTHOR +remove-ds.pl was written by the Fedora Directory Server Project. +.SH "REPORTING BUGS" +Report bugs to http://bugzilla.redhat.com. +.SH COPYRIGHT +Copyright \(co 2009 Red Hat, Inc. +.br +This is free software. You may redistribute copies of it under the terms of +the Directory Server license found in the LICENSE file of this +software distribution. This license is essentially the GNU General Public +License version 2 with an exception for plug-in distribution.
0
e7f7e9127717c1d432b10493b626fed334cc595f
389ds/389-ds-base
Ticket 47729 - Directory Server crashes if shutdown during a replication initialization Bug Description: When a shutdown was detected we marked that the total update was done prematurely(prp->stopped). This allowed the replication plugin to close while the total update was still in progress. Other plugins continued to be shutdown (e.g. ldbm database), while the total update was using shared resources - which lead to a crash. Fix Description: Only mark the total update protocol as stopped, after it is finished using shared resources. https://fedorahosted.org/389/ticket/47729 Reviewed by: nhosoi(Thanks!)
commit e7f7e9127717c1d432b10493b626fed334cc595f Author: Mark Reynolds <[email protected]> Date: Fri Mar 7 14:07:01 2014 -0500 Ticket 47729 - Directory Server crashes if shutdown during a replication initialization Bug Description: When a shutdown was detected we marked that the total update was done prematurely(prp->stopped). This allowed the replication plugin to close while the total update was still in progress. Other plugins continued to be shutdown (e.g. ldbm database), while the total update was using shared resources - which lead to a crash. Fix Description: Only mark the total update protocol as stopped, after it is finished using shared resources. https://fedorahosted.org/389/ticket/47729 Reviewed by: nhosoi(Thanks!) diff --git a/ldap/servers/plugins/replication/repl5_tot_protocol.c b/ldap/servers/plugins/replication/repl5_tot_protocol.c index 3895ace57..2db517897 100644 --- a/ldap/servers/plugins/replication/repl5_tot_protocol.c +++ b/ldap/servers/plugins/replication/repl5_tot_protocol.c @@ -343,7 +343,6 @@ repl5_tot_run(Private_Repl_Protocol *prp) prp->stopped = 0; if (prp->terminate) { - prp->stopped = 1; goto done; } @@ -365,8 +364,7 @@ repl5_tot_run(Private_Repl_Protocol *prp) } else if (prp->terminate) { - conn_disconnect(prp->conn); - prp->stopped = 1; + conn_disconnect(prp->conn); goto done; } @@ -661,7 +659,6 @@ int send_entry (Slapi_Entry *e, void *cb_data) if (prp->terminate) { conn_disconnect(prp->conn); - prp->stopped = 1; ((callback_data*)cb_data)->rc = -1; return -1; } @@ -674,7 +671,6 @@ int send_entry (Slapi_Entry *e, void *cb_data) if (rc) { conn_disconnect(prp->conn); - prp->stopped = 1; ((callback_data*)cb_data)->rc = -1; return -1; }
0
6e794a8eff213d49c933f781006e234984160db2
389ds/389-ds-base
Ticket 49454 - SSL Client Authentication breaks in FIPS mode Bug Description: Replication using SSL Client Auth breaks when FIPS is enabled. This is because FIPS mode changes the internal certificate token name. Fix Description: If FIPS is enabled grab the token name from the internal slot instead of using the default hardcoded internal token name. https://pagure.io/389-ds-base/issue/49454 Reviewed by: firstyear(Thanks!)
commit 6e794a8eff213d49c933f781006e234984160db2 Author: Mark Reynolds <[email protected]> Date: Wed Nov 15 13:27:58 2017 -0500 Ticket 49454 - SSL Client Authentication breaks in FIPS mode Bug Description: Replication using SSL Client Auth breaks when FIPS is enabled. This is because FIPS mode changes the internal certificate token name. Fix Description: If FIPS is enabled grab the token name from the internal slot instead of using the default hardcoded internal token name. https://pagure.io/389-ds-base/issue/49454 Reviewed by: firstyear(Thanks!) diff --git a/ldap/servers/slapd/proto-slap.h b/ldap/servers/slapd/proto-slap.h index 4a30def8b..3b7ab53b2 100644 --- a/ldap/servers/slapd/proto-slap.h +++ b/ldap/servers/slapd/proto-slap.h @@ -1130,6 +1130,7 @@ PRBool slapd_pk11_DoesMechanism(PK11SlotInfo *slot, CK_MECHANISM_TYPE type); PK11SymKey *slapd_pk11_PubUnwrapSymKeyWithFlagsPerm(SECKEYPrivateKey *wrappingKey, SECItem *wrappedKey, CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation, int keySize, CK_FLAGS flags, PRBool isPerm); PK11SymKey *slapd_pk11_TokenKeyGenWithFlags(PK11SlotInfo *slot, CK_MECHANISM_TYPE type, SECItem *param, int keySize, SECItem *keyid, CK_FLAGS opFlags, PK11AttrFlags attrFlags, void *wincx); CK_MECHANISM_TYPE slapd_PK11_GetPBECryptoMechanism(SECAlgorithmID *algid, SECItem **params, SECItem *pwitem); +char *slapd_PK11_GetTokenName(PK11SlotInfo *slot); /* * start_tls_extop.c diff --git a/ldap/servers/slapd/security_wrappers.c b/ldap/servers/slapd/security_wrappers.c index bec28d2f3..41fe03608 100644 --- a/ldap/servers/slapd/security_wrappers.c +++ b/ldap/servers/slapd/security_wrappers.c @@ -401,3 +401,9 @@ slapd_PK11_GetPBECryptoMechanism(SECAlgorithmID *algid, SECItem **params, SECIte { return PK11_GetPBECryptoMechanism(algid, params, pwitem); } + +char * +slapd_PK11_GetTokenName(PK11SlotInfo *slot) +{ + return PK11_GetTokenName(slot); +} diff --git a/ldap/servers/slapd/ssl.c b/ldap/servers/slapd/ssl.c index efe32d5d0..52ac7ea9f 100644 --- a/ldap/servers/slapd/ssl.c +++ b/ldap/servers/slapd/ssl.c @@ -2365,13 +2365,23 @@ slapd_SSL_client_auth(LDAP *ld) ssltoken = slapi_entry_attr_get_charptr(entry, "nsssltoken"); if (ssltoken && personality) { if (!PL_strcasecmp(ssltoken, "internal") || - !PL_strcasecmp(ssltoken, "internal (software)")) { - - /* Translate config internal name to more - * readable form. Certificate name is just - * the personality for internal tokens. - */ - token = slapi_ch_strdup(internalTokenName); + !PL_strcasecmp(ssltoken, "internal (software)")) + { + if ( slapd_pk11_isFIPS() ) { + /* + * FIPS mode changes the internal token name, so we need to + * grab the new token name from the internal slot. + */ + PK11SlotInfo *slot = slapd_pk11_getInternalSlot(); + token = slapi_ch_strdup(slapd_PK11_GetTokenName(slot)); + PK11_FreeSlot(slot); + } else { + /* + * Translate config internal name to more readable form. + * Certificate name is just the personality for internal tokens. + */ + token = slapi_ch_strdup(internalTokenName); + } #if defined(USE_OPENLDAP) /* openldap needs tokenname:certnick */ PR_snprintf(cert_name, sizeof(cert_name), "%s:%s", token, personality);
0
cdc5a82dac9ab1721f99b12512ca90cdc86bc67d
389ds/389-ds-base
Ticket 48949 - configparser fallback not python2 compatible Bug Description: The python 3 dictionary and configure parser allows a default option to be provided. Python 2 does not. We should support this for both versions. Fix Description: Add a ._get_config wrapper that correctly supports the right default fallback mechanism. https://fedorahosted.org/389/ticket/48949 Author: xaellia Review by: wibrown
commit cdc5a82dac9ab1721f99b12512ca90cdc86bc67d Author: xaellia <[email protected]> Date: Thu Aug 4 14:28:27 2016 +1000 Ticket 48949 - configparser fallback not python2 compatible Bug Description: The python 3 dictionary and configure parser allows a default option to be provided. Python 2 does not. We should support this for both versions. Fix Description: Add a ._get_config wrapper that correctly supports the right default fallback mechanism. https://fedorahosted.org/389/ticket/48949 Author: xaellia Review by: wibrown diff --git a/src/lib389/lib389/tools.py b/src/lib389/lib389/tools.py index 351714304..451aa376b 100644 --- a/src/lib389/lib389/tools.py +++ b/src/lib389/lib389/tools.py @@ -1224,15 +1224,29 @@ class SetupDs(object): def _install(self, extra): pass + def _set_config_fallback(self, config, group, attr, value, boolean=False, num=False): + try: + if boolean: + return config.getboolean(group, attr) + elif num: + return config.getint(group, attr) + else: + return config.get(group, attr) + except ValueError: + return value + except configparser.NoOptionError: + log.info("%s not specified:setting to default - %s" % (attr, value)) + return value + def _validate_ds_2_config(self, config): assert config.has_section('slapd') # Extract them in a way that create can understand. general = {} general['config_version'] = config.getint('general', 'config_version') general['full_machine_name'] = config.get('general', 'full_machine_name') - general['strict_host_checking'] = config.getboolean('general', 'strict_host_checking', fallback=True) + general['strict_host_checking'] = self._set_config_fallback(config, 'general', 'strict_host_checking', True, boolean=True) # Change this to detect if SELinux is running - general['selinux'] = config.getboolean('general', 'selinux', fallback=False) + general['selinux'] = self._set_config_fallback(config, 'general', 'selinux', False, boolean=True) if self.verbose: log.info("Configuration general %s" % general) @@ -1243,39 +1257,39 @@ class SetupDs(object): slapd = {} # Can probably set these defaults out of somewhere else ... slapd['instance_name'] = config.get('slapd', 'instance_name') - slapd['user'] = config.get('slapd', 'user', fallback='dirsrv') - slapd['group'] = config.get('slapd', 'group', fallback='dirsrv') - slapd['root_dn'] = config.get('slapd', 'root_dn', fallback='cn=Directory Manager') + slapd['user'] = self._set_config_fallback(config, 'slapd', 'user', 'dirsrv') + slapd['group'] = self._set_config_fallback(config, 'slapd', 'group', 'dirsrv') + slapd['root_dn'] = self._set_config_fallback(config, 'slapd', 'root_dn', 'cn=Directory Manager') slapd['root_password'] = config.get('slapd', 'root_password') - slapd['prefix'] = config.get('slapd', 'prefix', fallback='/') + slapd['prefix'] = self._set_config_fallback(config, 'slapd', 'prefix', '/') # How do we default, defaults to the DS version. - slapd['defaults'] = config.get('slapd', 'defaults', fallback=None) - slapd['port'] = config.getint('slapd', 'port', fallback=389) - slapd['secure_port'] = config.getint('slapd', 'secure_port', fallback=636) + slapd['defaults'] = self._set_config_fallback(config, 'slapd', 'defaults', None) + slapd['port'] = self._set_config_fallback(config, 'slapd', 'port', 389, num=True) + slapd['secure_port'] = self._set_config_fallback(config, 'slapd', 'secure_port', 636, num=True) # These are all the paths for DS, that are RELATIVE to the prefix # This will need to change to cope with configure scripts from DS! # perhaps these should be read as a set of DEFAULTs from a config file? - slapd['bin_dir'] = config.get('slapd', 'bin_dir', fallback='%s/bin/' % slapd['prefix']) - slapd['sysconf_dir'] = config.get('slapd', 'sysconf_dir', fallback='%s/etc' % slapd['prefix']) - slapd['data_dir'] = config.get('slapd', 'data_dir', fallback='%s/share/' % slapd['prefix']) - slapd['local_state_dir'] = config.get('slapd', 'local_state_dir', fallback='%s/var' % slapd['prefix']) - - slapd['lib_dir'] = config.get('slapd', 'lib_dir', fallback='%s/usr/lib64/dirsrv' % (slapd['prefix'])) - slapd['cert_dir'] = config.get('slapd', 'cert_dir', fallback='%s/etc/dirsrv/slapd-%s/' % (slapd['prefix'], slapd['instance_name'])) - slapd['config_dir'] = config.get('slapd', 'config_dir', fallback='%s/etc/dirsrv/slapd-%s/' % (slapd['prefix'], slapd['instance_name'])) - - slapd['inst_dir'] = config.get('slapd', 'inst_dir', fallback='%s/var/lib/dirsrv/slapd-%s' % (slapd['prefix'], slapd['instance_name'])) - slapd['backup_dir'] = config.get('slapd', 'backup_dir', fallback='%s/bak' % (slapd['inst_dir'])) - slapd['db_dir'] = config.get('slapd', 'db_dir', fallback='%s/db' % (slapd['inst_dir'])) - slapd['ldif_dir'] = config.get('slapd', 'ldif_dir', fallback='%s/ldif' % (slapd['inst_dir'])) - - slapd['lock_dir'] = config.get('slapd', 'lock_dir', fallback='%s/var/lock/dirsrv/slapd-%s' % (slapd['prefix'], slapd['instance_name'])) - slapd['log_dir'] = config.get('slapd', 'log_dir', fallback='%s/var/log/dirsrv/slapd-%s' % (slapd['prefix'], slapd['instance_name'])) - slapd['run_dir'] = config.get('slapd', 'run_dir', fallback='%s/var/run/dirsrv' % slapd['prefix']) - slapd['sbin_dir'] = config.get('slapd', 'sbin_dir', fallback='%s/sbin' % slapd['prefix']) - slapd['schema_dir'] = config.get('slapd', 'schema_dir', fallback='%s/etc/dirsrv/slapd-%s/schema' % (slapd['prefix'], slapd['instance_name'])) - slapd['tmp_dir'] = config.get('slapd', 'tmp_dir', fallback='/tmp') + slapd['bin_dir'] = self._set_config_fallback(config, 'slapd', 'bin_dir', '%s/bin/' % (slapd['prefix'])) + slapd['sysconf_dir'] = self._set_config_fallback(config, 'slapd', 'sysconf_dir', '%s/etc' % (slapd['prefix'])) + slapd['data_dir'] = self._set_config_fallback(config, 'slapd', 'data_dir', '%s/share/' % (slapd['prefix'])) + slapd['local_state_dir'] = self._set_config_fallback(config, 'slapd', 'local_state_dir', '%s/var' % (slapd['prefix'])) + + slapd['lib_dir'] = self._set_config_fallback(config, 'slapd', 'lib_dir', '%s/usr/lib64/dirsrv' % (slapd['prefix'])) + slapd['cert_dir'] = self._set_config_fallback(config, 'slapd', 'cert_dir', '%s/etc/dirsrv/slapd-%s/' % (slapd['prefix'], slapd['instance_name'])) + slapd['config_dir'] = self._set_config_fallback(config, 'slapd', 'config_dir', '%s/etc/dirsrv/slapd-%s/' % (slapd['prefix'], slapd['instance_name'])) + + slapd['inst_dir'] = self._set_config_fallback(config, 'slapd', 'inst_dir', '%s/var/lib/dirsrv/slapd-%s' % (slapd['prefix'], slapd['instance_name'])) + slapd['backup_dir'] = self._set_config_fallback(config, 'slapd', 'backup_dir', '%s/bak' % (slapd['inst_dir'])) + slapd['db_dir'] = self._set_config_fallback(config, 'slapd', 'db_dir', '%s/db' % (slapd['inst_dir'])) + slapd['ldif_dir'] = self._set_config_fallback(config, 'slapd', 'ldif_dir', '%s/ldif' % (slapd['inst_dir'])) + + slapd['lock_dir'] = self._set_config_fallback(config, 'slapd', 'lock_dir', '%s/var/lock/dirsrv/slapd-%s' % (slapd['prefix'], slapd['instance_name'])) + slapd['log_dir'] = self._set_config_fallback(config, 'slapd', 'log_dir', '%s/var/log/dirsrv/slapd-%s' % (slapd['prefix'], slapd['instance_name'])) + slapd['run_dir'] = self._set_config_fallback(config, 'slapd', 'run_dir', '%s/var/run/dirsrv' % (slapd['prefix'])) + slapd['sbin_dir'] = self._set_config_fallback(config, 'slapd', 'sbin_dir', '%s/sbin' % (slapd['prefix'])) + slapd['schema_dir'] = self._set_config_fallback(config, 'slapd', 'schema_dir', '%s/etc/dirsrv/slapd-%s/schema' % (slapd['prefix'], slapd['instance_name'])) + slapd['tmp_dir'] = self._set_config_fallback(config, 'slapd', 'tmp_dir', '/tmp') # Need to add all the default filesystem paths.
0
5d1861ea1c62e8eec1659fe7ec46b4b64385278a
389ds/389-ds-base
Issue 6893 - Log user that is updated during password modify extended operation Description: When a user's password is updated via an extended operation (password modify plugin) we only log the bind DN and not what user was updated. While "internal operation" logging will display the the user it should be logged by the default logging level. Add access logging using "EXT_INFO" for the old logging format, and "EXTENDED_OP_INFO" for json logging where we display the bind dn, target dn, and message. Relates: https://github.com/389ds/389-ds-base/issues/6893 Reviewed by: spichugi & tbordaz(Thanks!!)
commit 5d1861ea1c62e8eec1659fe7ec46b4b64385278a Author: Mark Reynolds <[email protected]> Date: Mon Jul 21 18:07:21 2025 -0400 Issue 6893 - Log user that is updated during password modify extended operation Description: When a user's password is updated via an extended operation (password modify plugin) we only log the bind DN and not what user was updated. While "internal operation" logging will display the the user it should be logged by the default logging level. Add access logging using "EXT_INFO" for the old logging format, and "EXTENDED_OP_INFO" for json logging where we display the bind dn, target dn, and message. Relates: https://github.com/389ds/389-ds-base/issues/6893 Reviewed by: spichugi & tbordaz(Thanks!!) diff --git a/dirsrvtests/tests/suites/logging/access_json_logging_test.py b/dirsrvtests/tests/suites/logging/access_json_logging_test.py index f0dc861a7..699bd8c4d 100644 --- a/dirsrvtests/tests/suites/logging/access_json_logging_test.py +++ b/dirsrvtests/tests/suites/logging/access_json_logging_test.py @@ -11,7 +11,7 @@ import os import time import ldap import pytest -from lib389._constants import DEFAULT_SUFFIX, PASSWORD, LOG_ACCESS_LEVEL +from lib389._constants import DEFAULT_SUFFIX, PASSWORD, LOG_ACCESS_LEVEL, DN_DM from lib389.properties import TASK_WAIT from lib389.topologies import topology_m2 as topo_m2 from lib389.idm.group import Groups @@ -548,22 +548,6 @@ def test_access_json_format(topo_m2, setup_test): "2.16.840.1.113730.3.4.3", "LDAP_CONTROL_PERSISTENTSEARCH") - # - # Extended op - # - log.info("Test EXTENDED_OP") - event = get_log_event(inst, "EXTENDED_OP", "oid", - "2.16.840.1.113730.3.5.12") - assert event is not None - assert event['oid_name'] == "REPL_START_NSDS90_REPLICATION_REQUEST_OID" - assert event['name'] == "replication-multisupplier-extop" - - event = get_log_event(inst, "EXTENDED_OP", "oid", - "2.16.840.1.113730.3.5.5") - assert event is not None - assert event['oid_name'] == "REPL_END_NSDS50_REPLICATION_REQUEST_OID" - assert event['name'] == "replication-multisupplier-extop" - # # TLS INFO/TLS CLIENT INFO # @@ -579,7 +563,8 @@ def test_access_json_format(topo_m2, setup_test): 'sn': RDN_TEST_USER, 'uidNumber': '1000', 'gidNumber': '2000', - 'homeDirectory': f'/home/{RDN_TEST_USER}' + 'homeDirectory': f'/home/{RDN_TEST_USER}', + 'userpassword': 'password' }) ssca_dir = inst.get_ssca_dir() @@ -646,6 +631,83 @@ def test_access_json_format(topo_m2, setup_test): assert event['msg'] == "failed to map client certificate to LDAP DN" assert event['err_msg'] == "Certificate couldn't be mapped to an ldap entry" + # + # Extended op + # + log.info("Test EXTENDED_OP") + event = get_log_event(inst, "EXTENDED_OP", "oid", + "2.16.840.1.113730.3.5.12") + assert event is not None + assert event['oid_name'] == "REPL_START_NSDS90_REPLICATION_REQUEST_OID" + assert event['name'] == "replication-multisupplier-extop" + + event = get_log_event(inst, "EXTENDED_OP", "oid", + "2.16.840.1.113730.3.5.5") + assert event is not None + assert event['oid_name'] == "REPL_END_NSDS50_REPLICATION_REQUEST_OID" + assert event['name'] == "replication-multisupplier-extop" + + # + # Extended op info + # + log.info("Test EXTENDED_OP_INFO") + OLD_PASSWD = 'password' + NEW_PASSWD = 'newpassword' + + assert inst.simple_bind_s(DN_DM, PASSWORD) + + assert inst.passwd_s(user.dn, OLD_PASSWD, NEW_PASSWD) + event = get_log_event(inst, "EXTENDED_OP_INFO", "name", + "passwd_modify_plugin") + assert event is not None + assert event['bind_dn'] == "cn=directory manager" + assert event['target_dn'] == user.dn.lower() + assert event['msg'] == "success" + + # Test no such object + BAD_DN = user.dn + ",dc=not" + with pytest.raises(ldap.NO_SUCH_OBJECT): + inst.passwd_s(BAD_DN, OLD_PASSWD, NEW_PASSWD) + + event = get_log_event(inst, "EXTENDED_OP_INFO", "target_dn", BAD_DN) + assert event is not None + assert event['bind_dn'] == "cn=directory manager" + assert event['target_dn'] == BAD_DN.lower() + assert event['msg'] == "No such entry exists." + + # Test invalid old password + with pytest.raises(ldap.INVALID_CREDENTIALS): + inst.passwd_s(user.dn, "not_the_old_pw", NEW_PASSWD) + event = get_log_event(inst, "EXTENDED_OP_INFO", "err", 49) + assert event is not None + assert event['bind_dn'] == "cn=directory manager" + assert event['target_dn'] == user.dn.lower() + assert event['msg'] == "Invalid oldPasswd value." + + # Test user without permissions + user2 = users.create(properties={ + 'uid': RDN_TEST_USER + "2", + 'cn': RDN_TEST_USER + "2", + 'sn': RDN_TEST_USER + "2", + 'uidNumber': '1001', + 'gidNumber': '2001', + 'homeDirectory': f'/home/{RDN_TEST_USER + "2"}', + 'userpassword': 'password' + }) + inst.simple_bind_s(user2.dn, 'password') + with pytest.raises(ldap.INSUFFICIENT_ACCESS): + inst.passwd_s(user.dn, NEW_PASSWD, OLD_PASSWD) + event = get_log_event(inst, "EXTENDED_OP_INFO", "err", 50) + assert event is not None + assert event['bind_dn'] == user2.dn.lower() + assert event['target_dn'] == user.dn.lower() + assert event['msg'] == "Insufficient access rights" + + + # Reset bind + inst.simple_bind_s(DN_DM, PASSWORD) + + if __name__ == '__main__': # Run isolated diff --git a/ldap/servers/slapd/accesslog.c b/ldap/servers/slapd/accesslog.c index 072ace203..46228d4a1 100644 --- a/ldap/servers/slapd/accesslog.c +++ b/ldap/servers/slapd/accesslog.c @@ -1113,6 +1113,53 @@ slapd_log_access_extop(slapd_log_pblock *logpb) return rc; } +/* + * Extended operation information + * + * int32_t log_format + * time_t conn_time + * uint64_t conn_id + * int32_t op_id + * const char *name + * const char *bind_dn + * const char *tartet_dn + * const char *msg + */ +int32_t +slapd_log_access_extop_info(slapd_log_pblock *logpb) +{ + int32_t rc = 0; + char *msg = NULL; + json_object *json_obj = NULL; + + if ((json_obj = build_base_obj(logpb, "EXTENDED_OP_INFO")) == NULL) { + return rc; + } + + if (logpb->name) { + json_object_object_add(json_obj, "name", json_obj_add_str(logpb->name)); + } + if (logpb->target_dn) { + json_object_object_add(json_obj, "target_dn", json_obj_add_str(logpb->target_dn)); + } + if (logpb->bind_dn) { + json_object_object_add(json_obj, "bind_dn", json_obj_add_str(logpb->bind_dn)); + } + if (logpb->msg) { + json_object_object_add(json_obj, "msg", json_obj_add_str(logpb->msg)); + } + json_object_object_add(json_obj, "err", json_object_new_int(logpb->err)); + + /* Convert json object to string and log it */ + msg = (char *)json_object_to_json_string_ext(json_obj, logpb->log_format); + rc = slapd_log_access_json(msg); + + /* Done with JSON object - free it */ + json_object_put(json_obj); + + return rc; +} + /* * Sort * diff --git a/ldap/servers/slapd/passwd_extop.c b/ldap/servers/slapd/passwd_extop.c index 4bb60afd6..69bb3494c 100644 --- a/ldap/servers/slapd/passwd_extop.c +++ b/ldap/servers/slapd/passwd_extop.c @@ -465,12 +465,14 @@ passwd_modify_extop(Slapi_PBlock *pb) BerElement *response_ber = NULL; Slapi_Entry *targetEntry = NULL; Connection *conn = NULL; + Operation *pb_op = NULL; LDAPControl **req_controls = NULL; LDAPControl **resp_controls = NULL; passwdPolicy *pwpolicy = NULL; Slapi_DN *target_sdn = NULL; Slapi_Entry *referrals = NULL; - /* Slapi_DN sdn; */ + Slapi_Backend *be = NULL; + int32_t log_format = config_get_accesslog_log_format(); slapi_log_err(SLAPI_LOG_TRACE, "passwd_modify_extop", "=>\n"); @@ -647,7 +649,7 @@ parse_req_done: } dn = slapi_sdn_get_ndn(target_sdn); if (dn == NULL || *dn == '\0') { - /* Refuse the operation because they're bound anonymously */ + /* Invalid DN - refuse the operation */ errMesg = "Invalid dn."; rc = LDAP_INVALID_DN_SYNTAX; goto free_and_return; @@ -724,14 +726,19 @@ parse_req_done: ber_free(response_ber, 1); } - slapi_pblock_set(pb, SLAPI_ORIGINAL_TARGET, (void *)dn); + slapi_pblock_get(pb, SLAPI_OPERATION, &pb_op); + if (pb_op == NULL) { + slapi_log_err(SLAPI_LOG_ERR, "passwd_modify_extop", "pb_op is NULL\n"); + goto free_and_return; + } + slapi_pblock_set(pb, SLAPI_ORIGINAL_TARGET, (void *)dn); /* Now we have the DN, look for the entry */ ret = passwd_modify_getEntry(dn, &targetEntry); /* If we can't find the entry, then that's an error */ if (ret) { /* Couldn't find the entry, fail */ - errMesg = "No such Entry exists."; + errMesg = "No such entry exists."; rc = LDAP_NO_SUCH_OBJECT; goto free_and_return; } @@ -742,30 +749,18 @@ parse_req_done: leak any useful information to the client such as current password wrong, etc. */ - Operation *pb_op = NULL; - slapi_pblock_get(pb, SLAPI_OPERATION, &pb_op); - if (pb_op == NULL) { - slapi_log_err(SLAPI_LOG_ERR, "passwd_modify_extop", "pb_op is NULL\n"); - goto free_and_return; - } - operation_set_target_spec(pb_op, slapi_entry_get_sdn(targetEntry)); slapi_pblock_set(pb, SLAPI_REQUESTOR_ISROOT, &pb_op->o_isroot); - /* In order to perform the access control check , we need to select a backend (even though - * we don't actually need it otherwise). - */ - { - Slapi_Backend *be = NULL; - - be = slapi_mapping_tree_find_backend_for_sdn(slapi_entry_get_sdn(targetEntry)); - if (NULL == be) { - errMesg = "Failed to find backend for target entry"; - rc = LDAP_OPERATIONS_ERROR; - goto free_and_return; - } - slapi_pblock_set(pb, SLAPI_BACKEND, be); + /* In order to perform the access control check, we need to select a backend (even though + * we don't actually need it otherwise). */ + be = slapi_mapping_tree_find_backend_for_sdn(slapi_entry_get_sdn(targetEntry)); + if (NULL == be) { + errMesg = "Failed to find backend for target entry"; + rc = LDAP_NO_SUCH_OBJECT; + goto free_and_return; } + slapi_pblock_set(pb, SLAPI_BACKEND, be); /* Check if the pwpolicy control is present */ slapi_pblock_get(pb, SLAPI_PWPOLICY, &need_pwpolicy_ctrl); @@ -797,10 +792,7 @@ parse_req_done: /* Check if password policy allows users to change their passwords. We need to do * this here since the normal modify code doesn't perform this check for * internal operations. */ - - Connection *pb_conn; - slapi_pblock_get(pb, SLAPI_CONNECTION, &pb_conn); - if (!pb_op->o_isroot && !pb_conn->c_needpw && !pwpolicy->pw_change) { + if (!pb_op->o_isroot && !conn->c_needpw && !pwpolicy->pw_change) { if (NULL == bindSDN) { bindSDN = slapi_sdn_new_normdn_byref(bindDN); } @@ -848,6 +840,27 @@ free_and_return: slapi_log_err(SLAPI_LOG_PLUGIN, "passwd_modify_extop", "%s\n", errMesg ? errMesg : "success"); + if (dn) { + /* Log the target ndn (if we have a target ndn) */ + if (log_format != LOG_FORMAT_DEFAULT) { + /* JSON logging */ + slapd_log_pblock logpb = {0}; + slapd_log_pblock_init(&logpb, log_format, pb); + logpb.name = "passwd_modify_plugin"; + logpb.target_dn = dn; + logpb.bind_dn = bindDN; + logpb.msg = errMesg ? errMesg : "success"; + logpb.err = rc; + slapd_log_access_extop_info(&logpb); + } else { + slapi_log_access(LDAP_DEBUG_STATS, + "conn=%" PRIu64 " op=%d EXT_INFO name=\"passwd_modify_plugin\" bind_dn=\"%s\" target_dn=\"%s\" msg=\"%s\" rc=%d\n", + conn ? conn->c_connid : -1, pb_op ? pb_op->o_opid : -1, + bindDN ? bindDN : "", dn, + errMesg ? errMesg : "success", rc); + } + } + if ((rc == LDAP_REFERRAL) && (referrals)) { send_referrals_from_entry(pb, referrals); } else { diff --git a/ldap/servers/slapd/slapi-private.h b/ldap/servers/slapd/slapi-private.h index da232ae2f..e9abf8b75 100644 --- a/ldap/servers/slapd/slapi-private.h +++ b/ldap/servers/slapd/slapi-private.h @@ -1652,6 +1652,7 @@ int32_t slapd_log_access_vlv(slapd_log_pblock *logpb); int32_t slapd_log_access_entry(slapd_log_pblock *logpb); int32_t slapd_log_access_referral(slapd_log_pblock *logpb); int32_t slapd_log_access_extop(slapd_log_pblock *logpb); +int32_t slapd_log_access_extop_info(slapd_log_pblock *logpb); int32_t slapd_log_access_sort(slapd_log_pblock *logpb); int32_t slapd_log_access_tls(slapd_log_pblock *logpb); int32_t slapd_log_access_tls_client_auth(slapd_log_pblock *logpb);
0
e6e0db35842fc6612134cff5a08c4968230d1b2f
389ds/389-ds-base
Ticket 49231 - force EXTERNAL always Bug Description: Because of how our sasl code works, EXTERNAL bypasses a number of checks so is always available. Fix Description: Force EXTERNAL to the present mech list, regardless of the whitelist. https://pagure.io/389-ds-base/issue/49231 Author: wibrown Review by: mreynosd (Thanks!)
commit e6e0db35842fc6612134cff5a08c4968230d1b2f Author: William Brown <[email protected]> Date: Mon May 15 09:04:45 2017 +1000 Ticket 49231 - force EXTERNAL always Bug Description: Because of how our sasl code works, EXTERNAL bypasses a number of checks so is always available. Fix Description: Force EXTERNAL to the present mech list, regardless of the whitelist. https://pagure.io/389-ds-base/issue/49231 Author: wibrown Review by: mreynosd (Thanks!) diff --git a/dirsrvtests/tests/suites/sasl/allowed_mechs.py b/dirsrvtests/tests/suites/sasl/allowed_mechs.py index a3e385e4d..7958db4b1 100644 --- a/dirsrvtests/tests/suites/sasl/allowed_mechs.py +++ b/dirsrvtests/tests/suites/sasl/allowed_mechs.py @@ -25,12 +25,21 @@ def test_sasl_allowed_mechs(topology_st): assert('EXTERNAL' in orig_mechs) # Now edit the supported mechs. CHeck them again. - standalone.config.set('nsslapd-allowed-sasl-mechanisms', 'EXTERNAL, PLAIN') + standalone.config.set('nsslapd-allowed-sasl-mechanisms', 'PLAIN') limit_mechs = standalone.rootdse.supported_sasl() - print(limit_mechs) assert('PLAIN' in limit_mechs) + # Should always be in the allowed list, even if not set. assert('EXTERNAL' in limit_mechs) + # Should not be there! + assert('GSSAPI' not in limit_mechs) + + standalone.config.set('nsslapd-allowed-sasl-mechanisms', 'PLAIN, EXTERNAL') + + limit_mechs = standalone.rootdse.supported_sasl() + assert('PLAIN' in limit_mechs) + assert('EXTERNAL' in limit_mechs) + # Should not be there! assert('GSSAPI' not in limit_mechs) # Do a config reset diff --git a/ldap/servers/slapd/charray.c b/ldap/servers/slapd/charray.c index 6b89714ee..9056f16d2 100644 --- a/ldap/servers/slapd/charray.c +++ b/ldap/servers/slapd/charray.c @@ -272,6 +272,20 @@ charray_utf8_inlist( return( 0 ); } +/* + * Assert that some str s is in the charray, or add it. + */ +void +charray_assert_present(char ***a, char *s) +{ + int result = charray_utf8_inlist(*a, s); + /* Not in the list */ + if (result == 0) { + char *sdup = slapi_ch_strdup(s); + slapi_ch_array_add_ext(a, sdup); + } +} + int slapi_ch_array_utf8_inlist(char **a, char *s) { return charray_utf8_inlist(a,s); diff --git a/ldap/servers/slapd/saslbind.c b/ldap/servers/slapd/saslbind.c index 3c85b1c4d..fbccd73e2 100644 --- a/ldap/servers/slapd/saslbind.c +++ b/ldap/servers/slapd/saslbind.c @@ -807,6 +807,15 @@ char **ids_sasl_listmech(Slapi_PBlock *pb) ret = sup_ret; } + /* + * https://pagure.io/389-ds-base/issue/49231 + * Because of the way that SASL mechs are managed in bind.c and saslbind.c + * even if EXTERNAL was *not* in the list of allowed mechs, it was allowed + * in the bind process because it bypasses lots of our checking. As a result + * we have to always present it. + */ + charray_assert_present(&ret, "EXTERNAL"); + slapi_log_err(SLAPI_LOG_TRACE, "ids_sasl_listmech", "<=\n"); return ret; diff --git a/ldap/servers/slapd/slapi-private.h b/ldap/servers/slapd/slapi-private.h index 5b76e892b..570337564 100644 --- a/ldap/servers/slapd/slapi-private.h +++ b/ldap/servers/slapd/slapi-private.h @@ -834,6 +834,8 @@ void charray_subtract( char **a, char **b, char ***c ); char **charray_intersection(char **a, char **b); int charray_get_index(char **array, char *s); int charray_normdn_add(char ***chararray, char *dn, char *errstr); +void charray_assert_present(char ***a, char *s); + /****************************************************************************** * value array routines.
0
453d5cb1c533ea1e0c5f0056f3b54f1898f8f5e6
389ds/389-ds-base
Ticket 49024 - Fix db_dir paths Description: Wrong usage of db_dir path causes an instance restart failure when plugins that envolve that directory are enabled. Set them properly through the code. https://fedorahosted.org/389/ticket/49024 Reviewed by: nhosoi, wibrown (Thanks!)
commit 453d5cb1c533ea1e0c5f0056f3b54f1898f8f5e6 Author: Simon Pichugin <[email protected]> Date: Fri Nov 4 12:40:26 2016 +0100 Ticket 49024 - Fix db_dir paths Description: Wrong usage of db_dir path causes an instance restart failure when plugins that envolve that directory are enabled. Set them properly through the code. https://fedorahosted.org/389/ticket/49024 Reviewed by: nhosoi, wibrown (Thanks!) diff --git a/src/lib389/lib389/__init__.py b/src/lib389/lib389/__init__.py index 868c547ca..cfcc968c4 100644 --- a/src/lib389/lib389/__init__.py +++ b/src/lib389/lib389/__init__.py @@ -1408,8 +1408,8 @@ class DirSrv(SimpleLDAPObject): # # previous db (it may exists new db files not in the backup) - log.debug("restoreFS: remove subtree %s/*" % self.dbdir) - for root, dirs, files in os.walk(self.dbdir): + log.debug("restoreFS: remove subtree %s/*" % self.inst_dir) + for root, dirs, files in os.walk(self.inst_dir): for d in dirs: if d not in ("bak", "ldif"): log.debug("restoreFS: before restore remove directory" + @@ -1461,7 +1461,7 @@ class DirSrv(SimpleLDAPObject): # # Now be safe, triggers a recovery at restart # - guardian_file = os.path.join(self.dbdir, "db/guardian") + guardian_file = os.path.join(self.dbdir, "guardian") if os.path.isfile(guardian_file): try: log.debug("restoreFS: remove %s" % guardian_file) @@ -2709,9 +2709,9 @@ class DirSrv(SimpleLDAPObject): log.error("dbscan: missing required index name") return False elif '.db' in index: - indexfile = "%s/db/%s/%s" % (self.dbdir, bename, index) + indexfile = os.path.join(self.dbdir, bename, index) else: - indexfile = "%s/db/%s/%s.db" % (self.dbdir, bename, index) + indexfile = os.path.join(self.dbdir, bename, index) option = '' if 'id2entry' in index: diff --git a/src/lib389/lib389/changelog.py b/src/lib389/lib389/changelog.py index 071d9f914..2570513f3 100644 --- a/src/lib389/lib389/changelog.py +++ b/src/lib389/lib389/changelog.py @@ -45,7 +45,7 @@ class Changelog(object): """ dn = DN_CHANGELOG attribute, changelog_name = dn.split(",")[0].split("=", 1) - dirpath = os.path.join(self.conn.dbdir, dbname) + dirpath = os.path.join(self.conn.inst_dir, dbname) entry = Entry(dn) entry.update({ 'objectclass': ("top", "extensibleobject"), diff --git a/src/lib389/lib389/tools.py b/src/lib389/lib389/tools.py index 5b9f7ca10..9babf444e 100644 --- a/src/lib389/lib389/tools.py +++ b/src/lib389/lib389/tools.py @@ -370,8 +370,8 @@ class DirSrvTools(object): # # previous db (it may exists new db files not in the backup) - log.debug("instanceRestoreFS: remove subtree %s/*" % dirsrv.dbdir) - for root, dirs, files in os.walk(dirsrv.dbdir): + log.debug("instanceRestoreFS: remove subtree %s/*" % dirsrv.inst_dir) + for root, dirs, files in os.walk(dirsrv.inst_dir): for d in dirs: if d not in ("bak", "ldif"): log.debug( @@ -418,7 +418,7 @@ class DirSrvTools(object): # # Now be safe, triggers a recovery at restart # - guardian_file = os.path.join(dirsrv.dbdir, "db/guardian") + guardian_file = os.path.join(dirsrv.dbdir, "guardian") if os.path.isfile(guardian_file): try: log.debug("instanceRestoreFS: remove %s" % guardian_file)
0
7403ef0df1c09701db9966634c9a2660aed067df
389ds/389-ds-base
Issue 25 - Fix RUV __repr__ function Description: This function never worked and had the wrong parenthesis grouping https://pagure.io/lib389/issue/25 Reviewed by: firstyear(Thanks!)
commit 7403ef0df1c09701db9966634c9a2660aed067df Author: Mark Reynolds <[email protected]> Date: Mon Apr 24 16:02:37 2017 -0400 Issue 25 - Fix RUV __repr__ function Description: This function never worked and had the wrong parenthesis grouping https://pagure.io/lib389/issue/25 Reviewed by: firstyear(Thanks!) diff --git a/src/lib389/lib389/_replication.py b/src/lib389/lib389/_replication.py index e84a47a22..7d5157723 100644 --- a/src/lib389/lib389/_replication.py +++ b/src/lib389/lib389/_replication.py @@ -84,10 +84,8 @@ class CSN(object): return retstr def __repr__(self): - return time.strftime("%x %X", - (time.localtime(self.ts)) + - " seq: " + str(self.seq) + " rid: " + - str(self.rid)) + return ("%s seq: %s rid: %s" % (time.strftime("%x %X", time.localtime(self.ts)), + str(self.seq), str(self.rid))) def __str__(self): return self.__repr__()
0
2813d3d0d524488bea30412a9289e0273f049936
389ds/389-ds-base
Issue:50860 - Port Password Policy test cases from TET to python3 part2 Bug Description: CI test - Port Password Policy test cases from TET to python3 part2 Relates: https://pagure.io/389-ds-base/issue/50860 Author: aborah Reviewed by: Viktor Ashirov
commit 2813d3d0d524488bea30412a9289e0273f049936 Author: Anuj Borah <[email protected]> Date: Thu May 28 13:42:21 2020 +0530 Issue:50860 - Port Password Policy test cases from TET to python3 part2 Bug Description: CI test - Port Password Policy test cases from TET to python3 part2 Relates: https://pagure.io/389-ds-base/issue/50860 Author: aborah Reviewed by: Viktor Ashirov diff --git a/dirsrvtests/tests/suites/password/password_policy_test.py b/dirsrvtests/tests/suites/password/password_policy_test.py index aa01b5a64..59432e5b9 100644 --- a/dirsrvtests/tests/suites/password/password_policy_test.py +++ b/dirsrvtests/tests/suites/password/password_policy_test.py @@ -12,6 +12,7 @@ This test script will test password policy. import os import pytest +import time from lib389.topologies import topology_st as topo from lib389.idm.organizationalunit import OrganizationalUnits from lib389.idm.user import UserAccounts, UserAccount @@ -115,6 +116,20 @@ def change_password_with_admin(topo, user_password_new_pass_list): UserAccount(topo.standalone, f'{user},{DEFAULT_SUFFIX}').replace('userpassword', password) +def _do_transaction_for_pwp(topo, attr1, attr2): + """ + Will change pwp parameters + """ + pwp = PwPolicyManager(topo.standalone) + orl = pwp.get_pwpolicy_entry(f'uid=orla,ou=dirsec,{DEFAULT_SUFFIX}') + joe = pwp.get_pwpolicy_entry(f'uid=joe,ou=people,{DEFAULT_SUFFIX}') + people = pwp.get_pwpolicy_entry(f'ou=people,{DEFAULT_SUFFIX}') + for instance in [orl, joe, people]: + instance.replace(attr1, attr2) + for instance in [orl, joe, people]: + assert instance.get_attr_val_utf8(attr1) == attr2 + + @pytest.fixture(scope="function") def _fixture_for_password_change(request, topo): pwp = PwPolicyManager(topo.standalone) @@ -614,6 +629,287 @@ def test_password_syntax_section(topo, _policy_setup, _fixture_for_syntax_sectio ]) [email protected](scope="function") +def _fixture_for_password_history(request, topo): + pwp = PwPolicyManager(topo.standalone) + orl = pwp.get_pwpolicy_entry(f'uid=orla,ou=dirsec,{DEFAULT_SUFFIX}') + joe = pwp.get_pwpolicy_entry(f'uid=joe,ou=people,{DEFAULT_SUFFIX}') + people = pwp.get_pwpolicy_entry(f'ou=people,{DEFAULT_SUFFIX}') + change_password_with_admin(topo, [ + ('uid=orla,ou=dirsec', '000rLb1'), + ('uid=joe,ou=people', '00J0e1'), + ('uid=jack,ou=people', '00J6ck1'), + ('uid=deep,ou=others,ou=people', '00De3p1') + ]) + for instance in [orl, joe, people]: + instance.replace_many( + ('passwordhistory', 'on'), + ('passwordinhistory', '3'), + ('passwordChange', 'on')) + for instance in [orl, joe, people]: + assert instance.get_attr_val_utf8('passwordhistory') == 'on' + assert instance.get_attr_val_utf8('passwordinhistory') == '3' + assert instance.get_attr_val_utf8('passwordChange') == 'on' + + def final_step(): + for instance1 in [orl, joe, people]: + instance1.replace('passwordhistory', 'off') + change_password_with_admin(topo, [ + ('uid=orla,ou=dirsec', '000rLb1'), + ('uid=joe,ou=people', '00J0e1'), + ('uid=jack,ou=people', '00J6ck1'), + ('uid=deep,ou=others,ou=people', '00De3p1') + ]) + request.addfinalizer(final_step) + + +def test_password_history_section(topo, _policy_setup, _fixture_for_password_history): + """ Password History Section. + + :id: 51f459a0-a0ba-11ea-ade7-8c16451d917b + :setup: Standalone + :steps: + 1. Changing current password for orla,joe,jack and deep + 2. Checking that the passwordhistory attribute has been added ! + 3. Try to change the password back which should fail + 4. Change the passwords for all four test users to something new + 5. Try to change passwords back to the first password + 6. Change to a fourth password not in password history + 7. Try to change all the passwords back to the first password + 8. Change the password to one more new password as root dn + 9. Now try to change the password back to the first password + 10. Checking that password history does still containt the previous 3 passwords + 11. Add a password test for long long password (more than 490 bytes). + 12. Changing password : LONGPASSWORD goes in history + 13. Setting policy to NOT keep password histories + 14. Changing current password from *2 to *2 + 15. Try to change *2 to *1, should succeed + :expected results: + 1. Success + 2. Success + 3. Fail + 4. Success + 5. Fail + 6. Success + 7. Fail + 8. Success + 9. Success + 10. Success + 11. Success + 12. Success + 13. Success + 14. Success + 15. Success + """ + # Changing current password for orla,joe,jack and deep + change_password_with_admin(topo, [ + ('uid=orla,ou=dirsec', '000rLb2'), + ('uid=joe,ou=people', '00J0e2'), + ('uid=jack,ou=people', '00J6ck2'), + ('uid=deep,ou=others,ou=people', '00De3p2'), + ]) + time.sleep(1) + # Checking that the password history attribute has been added ! + for user, password in [ + ('uid=orla,ou=dirsec', '000rLb1'), + ('uid=joe,ou=people', '00J0e1'), + ('uid=jack,ou=people', '00J6ck1'), + ('uid=deep,ou=others,ou=people', '00De3p1'), + ]: + assert password in UserAccount(topo.standalone, + f'{user},{DEFAULT_SUFFIX}').get_attr_val_utf8("passwordhistory") + # Try to change the password back which should fail + with pytest.raises(ldap.CONSTRAINT_VIOLATION): + change_password(topo, [ + ('uid=orla,ou=dirsec', '000rLb2', '000rLb1'), + ('uid=joe,ou=people', '00J0e2', '00J0e1'), + ('uid=jack,ou=people', '00J6ck2', '00J6ck1'), + ('uid=deep,ou=others,ou=people', '00De3p2', '00De3p1'), + ]) + # Change the passwords for all four test users to something new + change_password_with_admin(topo, [ + ('uid=orla,ou=dirsec', '000rLb3'), + ('uid=joe,ou=people', '00J0e3'), + ('uid=jack,ou=people', '00J6ck3'), + ('uid=deep,ou=others,ou=people', '00De3p3') + ]) + # Try to change passwords back to the first password + time.sleep(1) + with pytest.raises(ldap.CONSTRAINT_VIOLATION): + change_password(topo, [ + ('uid=orla,ou=dirsec', '000rLb3', '000rLb1'), + ('uid=joe,ou=people', '00J0e3', '00J0e1'), + ('uid=jack,ou=people', '00J6ck3', '00J6ck1'), + ('uid=deep,ou=others,ou=people', '00De3p3', '00De3p1'), + ]) + # Change to a fourth password not in password history + change_password_with_admin(topo, [ + ('uid=orla,ou=dirsec', '000rLb4'), + ('uid=joe,ou=people', '00J0e4'), + ('uid=jack,ou=people', '00J6ck4'), + ('uid=deep,ou=others,ou=people', '00De3p4') + ]) + time.sleep(1) + # Try to change all the passwords back to the first password + with pytest.raises(ldap.CONSTRAINT_VIOLATION): + change_password(topo, [ + ('uid=orla,ou=dirsec', '000rLb4', '000rLb1'), + ('uid=joe,ou=people', '00J0e4', '00J0e1'), + ('uid=jack,ou=people', '00J6ck4', '00J6ck1'), + ('uid=deep,ou=others,ou=people', '00De3p4', '00De3p1') + ]) + # change the password to one more new password as root dn + change_password_with_admin(topo, [ + ('uid=orla,ou=dirsec', '000rLb5'), + ('uid=joe,ou=people', '00J0e5'), + ('uid=jack,ou=people', '00J6ck5'), + ('uid=deep,ou=others,ou=people', '00De3p5') + ]) + time.sleep(1) + # Now try to change the password back to the first password + change_password(topo, [ + ('uid=orla,ou=dirsec', '000rLb5', '000rLb1'), + ('uid=joe,ou=people', '00J0e5', '00J0e1'), + ('uid=jack,ou=people', '00J6ck5', '00J6ck1'), + ('uid=deep,ou=others,ou=people', '00De3p5', '00De3p1') + ]) + time.sleep(1) + # checking that password history does still containt the previous 3 passwords + for user, password3, password2, password1 in [ + ('uid=orla,ou=dirsec', '000rLb5', '000rLb4', '000rLb3'), + ('uid=joe,ou=people', '00J0e5', '00J0e4', '00J0e3'), + ('uid=jack,ou=people', '00J6ck5', '00J6ck4', '00J6ck3'), + ('uid=deep,ou=others,ou=people', '00De3p5', '00De3p4', '00De3p3') + ]: + user1 = UserAccount(topo.standalone, f'{user},{DEFAULT_SUFFIX}') + pass_list = ''.join(user1.get_attr_vals_utf8("passwordhistory")) + assert password1 in pass_list + assert password2 in pass_list + assert password3 in pass_list + # Add a password test for long long password (more than 490 bytes). + long = '01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901' \ + '23456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456' \ + '789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012' \ + '345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678' \ + '901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234' \ + '5678901234567890123456789LENGTH=510' + change_password(topo, [ + ('uid=orla,ou=dirsec', '000rLb1', long), + ('uid=joe,ou=people', '00J0e1', long), + ('uid=jack,ou=people', '00J6ck1', long), + ('uid=deep,ou=others,ou=people', '00De3p1', long) + ]) + time.sleep(1) + # Changing password : LONGPASSWORD goes in history + change_password(topo, [ + ('uid=orla,ou=dirsec', long, '000rLb2'), + ('uid=joe,ou=people', long, '00J0e2'), + ('uid=jack,ou=people', long, '00J6ck2'), + ('uid=deep,ou=others,ou=people', long, '00De3p2') + ]) + time.sleep(1) + for user, password in [ + ('uid=orla,ou=dirsec', '000rLb2'), + ('uid=joe,ou=people', '00J0e2'), + ('uid=jack,ou=people', '00J6ck2'), + ('uid=deep,ou=others,ou=people', '00De3p2') + ]: + real_user = UserAccount(topo.standalone, f'{user},{DEFAULT_SUFFIX}') + conn = real_user.bind(password) + assert long in ''.join(UserAccount(conn, + f'{user},{DEFAULT_SUFFIX}').get_attr_vals_utf8("passwordhistory")) + # Setting policy to NOT keep password histories + _do_transaction_for_pwp(topo, 'passwordhistory', 'off') + time.sleep(1) + # Changing current password from *2 to *2 + change_password(topo, [ + ('uid=orla,ou=dirsec', '000rLb2', '000rLb2'), + ('uid=joe,ou=people', '00J0e2', '00J0e2'), + ('uid=jack,ou=people', '00J6ck2', '00J6ck2'), + ('uid=deep,ou=others,ou=people', '00De3p2', '00De3p2') + ]) + # Try to change *2 to *1, should succeed + change_password(topo, [ + ('uid=orla,ou=dirsec', '000rLb2', '000rLb1'), + ('uid=joe,ou=people', '00J0e2', '00J0e1'), + ('uid=jack,ou=people', '00J6ck2', '00J6ck1'), + ('uid=deep,ou=others,ou=people', '00De3p2', '00De3p1') + ]) + + [email protected](scope="function") +def _fixture_for_password_min_age(request, topo): + pwp = PwPolicyManager(topo.standalone) + orl = pwp.get_pwpolicy_entry(f'uid=orla,ou=dirsec,{DEFAULT_SUFFIX}') + joe = pwp.get_pwpolicy_entry(f'uid=joe,ou=people,{DEFAULT_SUFFIX}') + people = pwp.get_pwpolicy_entry(f'ou=people,{DEFAULT_SUFFIX}') + change_password_with_admin(topo, [ + ('uid=orla,ou=dirsec', '000rLb1'), + ('uid=joe,ou=people', '00J0e1'), + ('uid=jack,ou=people', '00J6ck1'), + ('uid=deep,ou=others,ou=people', '00De3p1') + ]) + for pwp1 in [orl, joe, people]: + assert pwp1.get_attr_val_utf8('passwordminage') == '0' + pwp1.replace_many( + ('passwordminage', '10'), + ('passwordChange', 'on')) + + def final_step(): + for pwp2 in [orl, joe, people]: + pwp2.replace('passwordminage', '0') + request.addfinalizer(final_step) + + +def test_password_minimum_age_section(topo, _policy_setup, _fixture_for_password_min_age): + """ Password History Section. + + :id: 470f5b2a-a0ba-11ea-ab2d-8c16451d917b + :setup: Standalone + :steps: + 1. Searching for password minimum age, should be 0 per defaults set + 2. Change current password from *1 to *2 + 3. Wait 5 secs and try to change again. Should fail. + 4. Wait more time to complete password min age + 5. Now user can change password + :expected results: + 1. Success + 2. Success + 3. Fail + 4. Success + 5. Success + """ + # Change current password from *1 to *2 + change_password(topo, [ + ('uid=orla,ou=dirsec', '000rLb1', '000rLb2'), + ('uid=joe,ou=people', '00J0e1', '00J0e2'), + ('uid=jack,ou=people', '00J6ck1', '00J6ck2'), + ('uid=deep,ou=others,ou=people', '00De3p1', '00De3p2') + ]) + # Wait 5 secs and try to change again. Should fail. + count = 0 + while count < 8: + with pytest.raises(ldap.CONSTRAINT_VIOLATION): + change_password(topo, [ + ('uid=orla,ou=dirsec', '000rLb2', '000rLb1'), + ('uid=joe,ou=people', '00J0e2', '00J0e1'), + ('uid=jack,ou=people', '00J6ck2', '00J6ck1'), + ('uid=deep,ou=others,ou=people', '00De3p2', '00De3p1') + ]) + time.sleep(1) + count += 1 + # Wait more time to complete password min age + for _ in range(3): + time.sleep(1) + # Now user can change password + change_password(topo, [ + ('uid=orla,ou=dirsec', '000rLb2', '000rLb1'), + ('uid=joe,ou=people', '00J0e2', '00J0e1'), + ('uid=jack,ou=people', '00J6ck2', '00J6ck1'), + ('uid=deep,ou=others,ou=people', '00De3p2', '00De3p1') + ]) + + if __name__ == "__main__": CURRENT_FILE = os.path.realpath(__file__) pytest.main("-s -v %s" % CURRENT_FILE) \ No newline at end of file
0
3fe4b5b0a6d154930b005701cd74ff9c6d8415b6
389ds/389-ds-base
Ticket 50028 - Revise ds-replcheck usage Description: Revised the tools usage to be cleaner and more intuitive. Added a "-y" option to use a password file. Added a "state" function to just return an RUV comparison Moved all the process status messages to only be displayed in verbose mode. https://pagure.io/389-ds-base/issue/50028 Reviewed by: spichugi(Thanks!)
commit 3fe4b5b0a6d154930b005701cd74ff9c6d8415b6 Author: Mark Reynolds <[email protected]> Date: Tue Nov 27 11:55:07 2018 -0500 Ticket 50028 - Revise ds-replcheck usage Description: Revised the tools usage to be cleaner and more intuitive. Added a "-y" option to use a password file. Added a "state" function to just return an RUV comparison Moved all the process status messages to only be displayed in verbose mode. https://pagure.io/389-ds-base/issue/50028 Reviewed by: spichugi(Thanks!) diff --git a/dirsrvtests/tests/suites/ds_tools/replcheck_test.py b/dirsrvtests/tests/suites/ds_tools/replcheck_test.py index 32d1d9ba2..27b8c317c 100644 --- a/dirsrvtests/tests/suites/ds_tools/replcheck_test.py +++ b/dirsrvtests/tests/suites/ds_tools/replcheck_test.py @@ -125,24 +125,48 @@ def replcheck_cmd_list(topo_tls_ldapi): inst.start() ds_replcheck_path = os.path.join(m1.ds_paths.bin_dir, 'ds-replcheck') - replcheck_cmd = [[ds_replcheck_path, '-b', DEFAULT_SUFFIX, '-D', DN_DM, '-w', PW_DM, '-l', '1', - '-m', 'ldap://{}:{}'.format(m1.host, m1.port), '--conflict', + + replcheck_cmd = [[ds_replcheck_path, 'online', '-b', DEFAULT_SUFFIX, '-D', DN_DM, '-w', PW_DM, '-l', '1', + '-m', 'ldap://{}:{}'.format(m1.host, m1.port), '--conflicts', '-r', 'ldap://{}:{}'.format(m2.host, m2.port)], - [ds_replcheck_path, '-b', DEFAULT_SUFFIX, '-D', DN_DM, '-w', PW_DM, '-l', '1', - '-m', 'ldaps://{}:{}'.format(m1.host, m1.sslport), '--conflict', + [ds_replcheck_path, 'online', '-b', DEFAULT_SUFFIX, '-D', DN_DM, '-w', PW_DM, '-l', '1', + '-m', 'ldaps://{}:{}'.format(m1.host, m1.sslport), '--conflicts', '-r', 'ldaps://{}:{}'.format(m2.host, m2.sslport)], - [ds_replcheck_path, '-b', DEFAULT_SUFFIX, '-D', DN_DM, '-w', PW_DM, '-l', '1', + [ds_replcheck_path, 'online', '-b', DEFAULT_SUFFIX, '-D', DN_DM, '-w', PW_DM, '-l', '1', '-m', 'ldap://{}:{}'.format(m1.host, m1.port), '-Z', m1.get_ssca_dir(), - '-r', 'ldap://{}:{}'.format(m2.host, m2.port), '--conflict'], - [ds_replcheck_path, '-b', DEFAULT_SUFFIX, '-D', DN_DM, '-w', PW_DM, '-l', '1', + '-r', 'ldap://{}:{}'.format(m2.host, m2.port), '--conflicts'], + [ds_replcheck_path, 'online', '-b', DEFAULT_SUFFIX, '-D', DN_DM, '-w', PW_DM, '-l', '1', '-m', 'ldapi://%2fvar%2frun%2fslapd-{}.socket'.format(m1.serverid), '--conflict', '-r', 'ldapi://%2fvar%2frun%2fslapd-{}.socket'.format(m2.serverid)], - [ds_replcheck_path, '-b', DEFAULT_SUFFIX, '--conflict', - '-M', '/tmp/export_{}.ldif'.format(m1.serverid), - '-R', '/tmp/export_{}.ldif'.format(m2.serverid)]] + [ds_replcheck_path, 'offline', '-b', DEFAULT_SUFFIX, '--conflicts', '--rid', '1', + '-m', '/tmp/export_{}.ldif'.format(m1.serverid), + '-r', '/tmp/export_{}.ldif'.format(m2.serverid)]] return replcheck_cmd +def test_state(topo_tls_ldapi): + """Check "state" report + + :id: 1cc6b28b-8a42-45fb-ab50-9552db0ac178 + :setup: Two master replication + :steps: + 1. Get the replication state value + 2. The state value is as expected + :expectedresults: + 1. It should be successful + 2. It should be successful + """ + m1 = topo_tls_ldapi.ms["master1"] + m2 = topo_tls_ldapi.ms["master2"] + ds_replcheck_path = os.path.join(m1.ds_paths.bin_dir, 'ds-replcheck') + + tool_cmd = [ds_replcheck_path, 'state', '-b', DEFAULT_SUFFIX, '-D', DN_DM, '-w', PW_DM, + '-m', 'ldaps://{}:{}'.format(m1.host, m1.sslport), + '-r', 'ldaps://{}:{}'.format(m2.host, m2.sslport)] + result = subprocess.check_output(tool_cmd, encoding='utf-8') + assert (result.rstrip() == "Replication State: Master and Replica are in perfect synchronization") + + def test_check_ruv(topo_tls_ldapi): """Check that the report has RUV diff --git a/ldap/admin/src/scripts/ds-replcheck b/ldap/admin/src/scripts/ds-replcheck index de4458023..72527aaa6 100755 --- a/ldap/admin/src/scripts/ds-replcheck +++ b/ldap/admin/src/scripts/ds-replcheck @@ -8,6 +8,7 @@ # See LICENSE for details. # --- END COPYRIGHT BLOCK --- # +# PYTHON_ARGCOMPLETE_OK import os import sys @@ -15,14 +16,17 @@ import re import time import ldap import ldapurl -import argparse +import argparse, argcomplete import getpass +import signal from ldif import LDIFRecordList from ldap.ldapobject import SimpleLDAPObject from ldap.cidict import cidict from ldap.controls import SimplePagedResultsControl +from lib389._entry import Entry +from lib389.utils import ensure_str, ensure_list_str, ensure_int -VERSION = "1.4" +VERSION = "2.0" RUV_FILTER = '(&(nsuniqueid=ffffffff-ffffffff-ffffffff-ffffffff)(objectclass=nstombstone))' LDAP = 'ldap' LDAPS = 'ldaps' @@ -34,28 +38,12 @@ mdcsn_pattern = re.compile(';mdcsn-([A-Fa-f0-9]+)') adcsn_pattern = re.compile(';adcsn-([A-Fa-f0-9]+)') -class Entry(object): - ''' This is a stripped down version of Entry from python-lib389. - Once python-lib389 is released on RHEL this class will go away. - ''' - - def __init__(self, entrydata): - if entrydata: - self.dn = entrydata[0] - self.data = cidict(entrydata[1]) - - def __getitem__(self, name): - return self.__getattr__(name) - - def __getattr__(self, name): - if name == 'dn' or name == 'data': - return self.__dict__.get(name, None) - return self.getValue(name) - - def get_entry(entries, dn): - ''' Loop over a list of enties looking for a matching dn - ''' + """Loop over a list of enties looking for a matching dn + :param entries - A List of LDAP entries + :param dn - a DN used to find an entry from the list of entries + :return - None or a matching LDAP entry + """ for entry in entries: if entry.dn == dn: return entry @@ -63,20 +51,42 @@ def get_entry(entries, dn): def remove_entry(rentries, dn): - ''' Remove an entry from the list of entries - ''' + """Remove an entry from the list of entries + :param rentries - A List of LDAP entries + :param dn - a DN used to find an entry to delete from the list of entries + """ for entry in rentries: if entry.dn == dn: rentries.remove(entry) break +def get_ruv_time(ruv, rid): + """Take a RUV element (nsds50ruv attribute) and extract the timestamp from maxcsn + :param ruv - A lsit of RUV elements + :param rid - The rid of the master to extractthe maxcsn time from + :return: The time in seconds of the maxcsn, or 0 if there is no maxcsn, or -1 if + the rid was not found + """ + for ruve in ruv: + if ruve.startswith("{{replica {} ".format(rid)): + parts = ruve.split() + if len(parts) < 5: + # No maxcsn + return 0 + + return int(parts[4][:8], 16) + + # Did not find RID in RUV + return -1 + + def extract_time(stateinfo): - ''' Take the nscpEntryWSI(state info) attribute and get the most recent timestamp from + """Take the nscpEntryWSI(state info) attribute and get the most recent timestamp from one of the csns (vucsn, vdcsn, mdcsn, adcsn) - - Return the timestamp in decimal - ''' + :param stateinfo - The nscpEntryWSI attribute value + :return - the timestamp in decimal + """ timestamp = 0 for pattern in [vucsn_pattern, vdcsn_pattern, mdcsn_pattern, adcsn_pattern]: csntime = pattern.search(stateinfo) @@ -90,8 +100,10 @@ def extract_time(stateinfo): def convert_timestamp(timestamp): - ''' Convert createtimestamp to ctime: 20170405184656Z ----> Wed Apr 5 19:46:56 2017 - ''' + """Convert createtimestamp to ctime: 20170405184656Z ----> Wed Apr 5 19:46:56 2017 + :param timestamp - A timestamp from the server + :return - the ctime of the timestamp + """ time_tuple = (int(timestamp[:4]), int(timestamp[4:6]), int(timestamp[6:8]), int(timestamp[8:10]), int(timestamp[10:12]), int(timestamp[12:14]), 0, 0, 0) @@ -100,8 +112,11 @@ def convert_timestamp(timestamp): def convert_entries(entries): - '''For online report. Convert and normalize the ldap entries. Take note of - conflicts and tombstones ''' + """For online report. Convert and normalize the ldap entries. Take note of + conflicts and tombstones + :param entries - List of LDAP Entries + :return - A Dict containing the all the entries' information + """ new_entries = [] conflict_entries = [] glue_entries = [] @@ -125,8 +140,15 @@ def convert_entries(entries): it must be skipped ''' continue - if ('nsds5replconflict' in new_entry.data and 'nsTombstone' not in new_entry.data['objectclass'] and - 'nstombstone' not in new_entry.data['objectclass']): + + # lowercase all the objectclass values (easier for tombstone checking) + oc_vals = new_entry.data['objectclass'] + new_oc_vals = [] + for val in oc_vals: + new_oc_vals.append(val.lower()) + new_entry.data['objectclass'] = new_oc_vals + + if ('nsds5replconflict' in new_entry.data and 'nstombstone' not in new_entry.data['objectclass']): # This is a conflict entry that is NOT a tombstone entry (should this be reconsidered?) conflict_entries.append(new_entry) if 'glue' in new_entry.data['objectclass']: @@ -150,12 +172,13 @@ def convert_entries(entries): def report_conflict(entry, attr, opts): - ''' Check the createtimestamp/modifytimestamp (which ever is larger), + """Check the createtimestamp/modifytimestamp (which ever is larger), and make sure its past the ignore time. - - return True - if the conflict should be reported - return False - if it should be ignored - ''' + :param entry - an LDAP Entry + :param attr - the attribute to check + :return - True - if the conflict should be reported + False - if it should be ignored + """ if opts['lag'] == 0: return True @@ -172,8 +195,10 @@ def report_conflict(entry, attr, opts): def format_diff(diff): - ''' Take the diff map and format it for friendly output - ''' + """Take the diff map and format it for friendly output + :param diff - A Dict containing missing/different attribute values + :return - a text blog used by the report to display info + """ diff_report = "%s\n" % (diff['dn']) diff_report += ("-" * len(diff['dn'])) + "\n" for missing in diff['missing']: @@ -184,9 +209,36 @@ def format_diff(diff): return diff_report +def get_ruv_state(opts): + """Calculate replication state + :param opts - all the script options + :return - A text description of the replicaton state + """ + mtime = get_ruv_time(opts['master_ruv'], opts['rid']) + rtime = get_ruv_time(opts['replica_ruv'], opts['rid']) + if mtime == -1: + repl_state = "Replication State: Replica ID ({}) not found in Master's RUV".format(opts['rid']) + elif rtime == -1: + repl_state = "Replication State: Replica ID ({}) not found in Replica's RUV (not initialized?)".format(opts['rid']) + elif mtime == 0: + repl_state = "Replication State: Master has not seen any updates" + elif rtime == 0: + repl_state = "Replication State: Replica has not seen any changes from the Master" + elif mtime > rtime: + repl_state = "Replication State: Replica is behind Master by: {} seconds".format(mtime - rtime) + elif mtime < rtime: + repl_state = "Replication State: Replica is ahead of Master by: {} seconds".format(rtime - mtime) + else: + repl_state = "Replication State: Master and Replica are in perfect synchronization" + + return repl_state + + def get_ruv_report(opts): - '''Print a friendly RUV report - ''' + """Print a friendly RUV report + :param opts - all the script options + :return - A text blob to display in the report + """ opts['master_ruv'].sort() opts['replica_ruv'].sort() @@ -196,12 +248,18 @@ def get_ruv_report(opts): report += "\nReplica RUV:\n" for element in opts['replica_ruv']: report += " %s\n" % (element) + + report += "\n" + get_ruv_state(opts) + "\n" report += "\n\n" return report def remove_attr_state_info(attr): + """Remove state info from the entry + :param attr - the attribute to strip + :return - a cleaned version of the attributre + """ state_attr = None idx = attr.find(';') if idx > 0: @@ -214,9 +272,14 @@ def remove_attr_state_info(attr): return attr.lower(), state_attr def add_attr_entry(entry, val, attr, state_attr): - ''' Offline mode (ldif comparision) Add the attr to the entry, and if there + """Offline mode (ldif comparision) Add the attr to the entry, and if there is state info add nscpentrywsi attr - we need consistency with online mode - to make code simpler ''' + to make code simpler + :param entry - A LDAP entry + :param val - The attribute value + :param attr - The attribute + :param state_attr - The attribute's state information + """ if attr is not None: if attr in entry: entry[attr].append(val) @@ -237,11 +300,14 @@ def add_attr_entry(entry, val, attr, state_attr): # Offline mode helper functions # def ldif_search(LDIF, dn): - ''' Offline mode - Search ldif for a single DN. We need to factor in that + """Offline mode - Search ldif for a single DN. We need to factor in that DN's and attribute values can wrap lines and are identified by a leading white space. So we can't fully process an attribute until we get to the next attribute. - ''' + :param LDIF - The LDIF file's File Handle + :dn - The DN of the entry to search for + :return - An LDAP entry + """ result = {} data = {} found_conflict = False @@ -385,19 +451,23 @@ def ldif_search(LDIF, dn): result['glue'] = None if found_conflict and found_subentry and found_tombstone is False: result['entry'] = None - result['conflict'] = Entry([dn, data]) + result['conflict'] = Entry((dn, data)) if found_glue: result['glue'] = result['conflict'] elif found: result['conflict'] = None - result['entry'] = Entry([dn, data]) + result['entry'] = Entry((dn, data)) return result def get_dns(LDIF, filename, opts): - ''' Get all the DN's from an LDIF file - ''' + """Get all the DN's from an LDIF file + :param LDIF - The LDIF file File handle + :param filename - The LDIF file name + :param opts - A Dict of the scripts options + :return - List of DN's + """ dns = [] found = False found_ruv = False @@ -431,8 +501,11 @@ def get_dns(LDIF, filename, opts): def get_ldif_ruv(LDIF, opts): - ''' Search the LDIF and get the ruv entry - ''' + """Search the LDIF and get the ruv entry + :param LDIF - The LDIF file File handle + :param opts - A Dict of the scripts options + :return a list of RUV elements + """ LDIF.seek(0) result = ldif_search(LDIF, opts['ruv_dn']) LDIF.seek(0) # Reset cursor @@ -440,8 +513,12 @@ def get_ldif_ruv(LDIF, opts): def cmp_entry(mentry, rentry, opts): - ''' Compare the two entries, and return a "diff map" - ''' + """Compare the two entries, and return a "diff map" + :param mentry - A Master entry + :param rentry - A Replica entry + :param opts - A Dict of the scripts options + :return - A Dict of the differences in the entry, or None + """ diff = {} diff['dn'] = mentry['dn'] diff['missing'] = [] @@ -561,8 +638,10 @@ def cmp_entry(mentry, rentry, opts): def do_offline_report(opts, output_file=None): - ''' Check for inconsistencies between two ldifs - ''' + """Check for inconsistencies between two ldifs + :param opts - A Dict of the scripts options + :param output_file - A file handle to write the report to + """ missing_report = "" diff_report = [] final_report = "" @@ -588,7 +667,8 @@ def do_offline_report(opts, output_file=None): # Verify LDIF Files try: - print("Validating Master ldif file ({})...".format(opts['mldif'])) + if opts['verbose']: + print("Validating Master ldif file ({})...".format(opts['mldif'])) LDIFRecordList(MLDIF).parse() except ValueError: print('Master LDIF file in invalid, aborting...') @@ -596,7 +676,8 @@ def do_offline_report(opts, output_file=None): RLDIF.close() return None try: - print("Validating Replica ldif file ({})...".format(opts['rldif'])) + if opts['verbose']: + print("Validating Replica ldif file ({})...".format(opts['rldif'])) LDIFRecordList(RLDIF).parse() except ValueError: print('Replica LDIF file is invalid, aborting...') @@ -605,7 +686,8 @@ def do_offline_report(opts, output_file=None): return None # Get all the dn's, and entry counts - print ("Gathering all the DN's...") + if opts['verbose']: + print ("Gathering all the DN's...") master_dns = get_dns(MLDIF, opts['mldif'], opts) replica_dns = get_dns(RLDIF, opts['rldif'], opts) if master_dns is None or replica_dns is None: @@ -617,7 +699,8 @@ def do_offline_report(opts, output_file=None): r_count = len(replica_dns) # Get DB RUV - print ("Gathering the database RUV's...") + if opts['verbose']: + print ("Gathering the database RUV's...") opts['master_ruv'] = get_ldif_ruv(MLDIF, opts) opts['replica_ruv'] = get_ldif_ruv(RLDIF, opts) @@ -629,7 +712,8 @@ def do_offline_report(opts, output_file=None): because if the entry exists in both LDIF's then we already checked or diffs while processing the master dn's. """ - print ("Comparing Master to Replica...") + if opts['verbose']: + print ("Comparing Master to Replica...") missing = False for dn in master_dns: mresult = ldif_search(MLDIF, dn) @@ -646,9 +730,11 @@ def do_offline_report(opts, output_file=None): if mresult['tombstone']: mtombstones += 1 - # continue if rresult['tombstone']: rtombstones += 1 + if mresult['tombstone'] or rresult['tombstone']: + # skip over tombstones + continue if mresult['conflict'] is not None or rresult['conflict'] is not None: # If either entry is a conflict we still process it here @@ -689,7 +775,8 @@ def do_offline_report(opts, output_file=None): diff checking, so its only missing entries we are worried about. Count the remaining conflict & tombstone entries as well. """ - print ("Comparing Replica to Master...") + if opts['verbose']: + print ("Comparing Replica to Master...") MLDIF.seek(0) RLDIF.seek(0) missing = False @@ -698,7 +785,7 @@ def do_offline_report(opts, output_file=None): mresult = ldif_search(MLDIF, dn) if rresult['tombstone']: rtombstones += 1 - # continue + continue if rresult['conflict'] is not None: rconflicts.append(rresult['conflict']) @@ -722,7 +809,8 @@ def do_offline_report(opts, output_file=None): MLDIF.close() RLDIF.close() - print ("Preparing report...") + if opts['verbose']: + print("Preparing report...") # Build final report final_report = ('=' * 80 + '\n') @@ -742,7 +830,7 @@ def do_offline_report(opts, output_file=None): final_report += ('Master: %d\n' % (mtombstones)) final_report += ('Replica: %d\n' % (rtombstones)) - final_report += get_conflict_report(mconflicts, rconflicts, opts['conflicts'], format_conflicts=True) + final_report += get_conflict_report(mconflicts, rconflicts, opts['conflicts']) if missing_report != "": final_report += ('\nMissing Entries\n') final_report += ('=====================================================\n\n') @@ -764,8 +852,15 @@ def do_offline_report(opts, output_file=None): def check_for_diffs(mentries, mglue, rentries, rglue, report, opts): - ''' Online mode only - Check for diffs, return the updated report - ''' + """Online mode only - Check for diffs, return the updated report + :param mentries - Master entries + :param mglue - Master glue entries + :param rentries - Replica entries + :param rglue - Replica glue entries + :param report - A Dict of the entire report + :param opts - A Dict of the scripts options + :return - updated "report" + """ diff_report = [] m_missing = [] r_missing = [] @@ -777,6 +872,9 @@ def check_for_diffs(mentries, mglue, rentries, rglue, report, opts): rentries += report['m_missing'] for mentry in mentries: + if 'nstombstone' in mentry.data['objectclass']: + # Ignore tombstones + continue rentry = get_entry(rentries, mentry.dn) if rentry: if 'nsTombstone' not in rentry.data['objectclass'] and 'nstombstone' not in rentry.data['objectclass']: @@ -796,6 +894,9 @@ def check_for_diffs(mentries, mglue, rentries, rglue, report, opts): for rentry in rentries: # We should not have any entries if we are sync + if 'nstombstone' in rentry.data['objectclass']: + # Ignore tombstones + continue mentry = get_entry(mglue, rentry.dn) if mentry is None: m_missing.append(rentry) @@ -810,34 +911,41 @@ def check_for_diffs(mentries, mglue, rentries, rglue, report, opts): return report def validate_suffix(ldapnode, suffix, hostname): - # Validate suffix exists - try: - master_basesuffix = ldapnode.search_s(suffix, ldap.SCOPE_BASE ) - except ldap.NO_SUCH_OBJECT: - print("Error: Failed to validate suffix in {}. {} does not exist.".format(hostname, suffix)) - return False - except ldap.LDAPError as e: - print("Error: failed to validate suffix in {} ({}). ".format(hostname, str(e))) - return False - - # Check suffix is replicated - try: - replica_filter = "(&(objectclass=nsds5replica)(nsDS5ReplicaRoot=%s))" % suffix - master_replica = ldapnode.search_s("cn=config",ldap.SCOPE_SUBTREE,replica_filter) - if (len(master_replica) != 1): - print("Error: Failed to validate suffix in {}. {} is not replicated.".format(hostname, suffix)) + """Validate that the suffix exists + :param ldapnode - The LDAP object + :param suffix - The suffix to validate + :param hostname - The hostname of the instance + :return - True if suffix exists, otherwise False + """ + try: + master_basesuffix = ldapnode.search_s(suffix, ldap.SCOPE_BASE ) + except ldap.NO_SUCH_OBJECT: + print("Error: Failed to validate suffix in {}. {} does not exist.".format(hostname, suffix)) + return False + except ldap.LDAPError as e: + print("Error: failed to validate suffix in {} ({}). ".format(hostname, str(e))) + return False + + # Check suffix is replicated + try: + replica_filter = "(&(objectclass=nsds5replica)(nsDS5ReplicaRoot=%s))" % suffix + master_replica = ldapnode.search_s("cn=config",ldap.SCOPE_SUBTREE,replica_filter) + if (len(master_replica) != 1): + print("Error: Failed to validate suffix in {}. {} is not replicated.".format(hostname, suffix)) + return False + except ldap.LDAPError as e: + print("Error: failed to validate suffix in {} ({}). ".format(hostname, str(e))) return False - except ldap.LDAPError as e: - print("Error: failed to validate suffix in {} ({}). ".format(hostname, str(e))) - return False - return True + return True def connect_to_replicas(opts): - ''' Start the paged results searches - ''' - print('Connecting to servers...') + """Start the paged results searches + :param opts - A Dict of the scripts options + """ + if opts['verbose']: + print('Connecting to servers...') if opts['mprotocol'].lower() == 'ldapi': muri = "%s://%s" % (opts['mprotocol'], opts['mhost'].replace("/", "%2f")) @@ -888,65 +996,85 @@ def connect_to_replicas(opts): master.simple_bind_s(opts['binddn'], opts['bindpw']) except ldap.SERVER_DOWN as e: print("Cannot connect to %r" % muri) - exit(1) + sys.exit(1) except ldap.LDAPError as e: print("Error: Failed to authenticate to Master: ({}). " "Please check your credentials and LDAP urls are correct.".format(str(e))) - exit(1) + sys.exit(1) # Open connection to replica try: replica.simple_bind_s(opts['binddn'], opts['bindpw']) except ldap.SERVER_DOWN as e: print("Cannot connect to %r" % ruri) - exit(1) + sys.exit(1) except ldap.LDAPError as e: print("Error: Failed to authenticate to Replica: ({}). " "Please check your credentials and LDAP urls are correct.".format(str(e))) - exit(1) + sys.exit(1) # Validate suffix - print ("Validating suffix ...") + if opts['verbose']: + print ("Validating suffix ...") if not validate_suffix(master, opts['suffix'], opts['mhost']): - exit(1) + sys.exit(1) if not validate_suffix(replica,opts['suffix'], opts['rhost']): - exit(1) + sys.exit(1) # Get the RUVs - print ("Gathering Master's RUV...") + if opts['verbose']: + print ("Gathering Master's RUV...") try: master_ruv = master.search_s(opts['suffix'], ldap.SCOPE_SUBTREE, RUV_FILTER, ['nsds50ruv']) if len(master_ruv) > 0: - opts['master_ruv'] = master_ruv[0][1]['nsds50ruv'] + opts['master_ruv'] = ensure_list_str(master_ruv[0][1]['nsds50ruv']) else: print("Error: Master does not have an RUV entry") - exit(1) + sys.exit(1) except ldap.LDAPError as e: print("Error: Failed to get Master RUV entry: {}".format(str(e))) - exit(1) + sys.exit(1) - print ("Gathering Replica's RUV...") + if opts['verbose']: + print ("Gathering Replica's RUV...") try: replica_ruv = replica.search_s(opts['suffix'], ldap.SCOPE_SUBTREE, RUV_FILTER, ['nsds50ruv']) if len(replica_ruv) > 0: - opts['replica_ruv'] = replica_ruv[0][1]['nsds50ruv'] + opts['replica_ruv'] = ensure_list_str(replica_ruv[0][1]['nsds50ruv']) else: print("Error: Replica does not have an RUV entry") - exit(1) - + sys.exit(1) except ldap.LDAPError as e: print("Error: Failed to get Replica RUV entry: {}".format(str(e))) - exit(1) + sys.exit(1) + + # Get the master RID + if opts['verbose']: + print("Getting Master's replica ID") + try: + search_filter = "(&(objectclass=nsds5Replica)(nsDS5ReplicaRoot={})(nsDS5ReplicaId=*))".format(opts['suffix']) + replica_entry = master.search_s("cn=config", ldap.SCOPE_SUBTREE, search_filter) + if len(replica_entry) > 0: + opts['rid'] = ensure_int(replica_entry[0][1]['nsDS5ReplicaId'][0]) + else: + opts['rid'] = 65535 + except ldap.LDAPError as e: + print("Error: Failed to get Replica entry: {}".format(str(e))) + sys.exit(1) return (master, replica, opts) def print_online_report(report, opts, output_file): - ''' Print the online report - ''' + """Print the online report + :param report - The report Dict + :param opts - A Dict of the scripts options + :output_file - The output file handle to write the report to + """ - print ('Preparing final report...') + if opts['verbose']: + print ('Preparing final report...') m_missing = len(report['m_missing']) r_missing = len(report['r_missing']) final_report = ('=' * 80 + '\n') @@ -1009,10 +1137,10 @@ def print_online_report(report, opts, output_file): def remove_state_info(entry): - ''' Remove the state info for the attributes used in the conflict report - ''' + """Remove the state info for the attributes used in the conflict report + :param entry: A LDAP Entry + """ attrs = ['objectclass', 'nsds5replconflict', 'createtimestamp' , 'modifytimestamp'] - # attrs = ['createtimestamp'] for key, val in list(entry.data.items()): for attr in attrs: if key.lower().startswith(attr): @@ -1020,9 +1148,13 @@ def remove_state_info(entry): del entry.data[key] -def get_conflict_report(mentries, rentries, verbose, format_conflicts=False): - ''' Gather the conflict entry dn's for each replica - ''' +def get_conflict_report(mentries, rentries, verbose): + """Gather the conflict entry dn's for each replica + :param mentries - Master entries + :param rentries - Replica entries + :param verbose - verbose logging + :return - A text blob to dispaly in the report + """ m_conflicts = [] r_conflicts = [] @@ -1070,8 +1202,10 @@ def get_conflict_report(mentries, rentries, verbose, format_conflicts=False): def do_online_report(opts, output_file=None): - ''' Check for differences between two replicas - ''' + """Check for differences between two replicas + :param opts - A Dict of the scripts options + :param output_file - The outfile handle + """ m_done = False r_done = False done = False @@ -1089,7 +1223,8 @@ def do_online_report(opts, output_file=None): # Fire off paged searches on Master and Replica master, replica, opts = connect_to_replicas(opts) - print ('Start searching and comparing...') + if opts['verbose']: + print('Start searching and comparing...') paged_ctrl = SimplePagedResultsControl(True, size=opts['pagesize'], cookie='') controls = [paged_ctrl] req_pr_ctrl = controls[0] @@ -1100,7 +1235,7 @@ def do_online_report(opts, output_file=None): serverctrls=controls) except ldap.LDAPError as e: print("Error: Failed to get Master entries: %s", str(e)) - exit(1) + sys.exit(1) try: replica_msgid = replica.search_ext(opts['suffix'], ldap.SCOPE_SUBTREE, "(|(objectclass=*)(objectclass=ldapsubentry)(objectclass=nstombstone))", @@ -1108,7 +1243,7 @@ def do_online_report(opts, output_file=None): serverctrls=controls) except ldap.LDAPError as e: print("Error: Failed to get Replica entries: %s", str(e)) - exit(1) + sys.exit(1) # Read the results and start comparing while not m_done or not r_done: @@ -1189,111 +1324,68 @@ def do_online_report(opts, output_file=None): replica.unbind_s() -def main(): - desc = ("""Replication Comparison Tool (v""" + VERSION + """). This script """ + - """can be used to compare two replicas to see if they are in sync.""") +def init_online_params(args): + """Take the args and build up the opts dictionary + :param args - The argparse args + :return opts - Return a dictionary of all the script settings + """ + opts = {} - parser = argparse.ArgumentParser(description=desc) - parser.add_argument('-v', '--verbose', help='Verbose output', action='store_true', default=False, dest='verbose') - parser.add_argument('-o', '--outfile', help='The output file', dest='file', default=None) - parser.add_argument('-D', '--binddn', help='The Bind DN', dest='binddn', default=None) - parser.add_argument('-w', '--bindpw', help='The Bind password', dest='bindpw', default=None) - parser.add_argument('-W', '--prompt', help='Prompt for the bind password', action='store_true', dest='prompt', default=False) - parser.add_argument('-m', '--master_url', help='The LDAP URL for the Master server (REQUIRED)', - dest='murl', default=None) - parser.add_argument('-r', '--replica_url', help='The LDAP URL for the Replica server (REQUIRED)', - dest='rurl', default=None) - parser.add_argument('-b', '--basedn', help='Replicated suffix (REQUIRED)', dest='suffix', default=None) - parser.add_argument('-l', '--lagtime', help='The amount of time to ignore inconsistencies (default 300 seconds)', - dest='lag', default='300') - parser.add_argument('-c', '--conflicts', help='Display verbose conflict information', action='store_true', - dest='conflicts', default=False) - parser.add_argument('-Z', '--certdir', help='The certificate database directory for secure connections', - dest='certdir', default=None) - parser.add_argument('-i', '--ignore', help='Comma separated list of attributes to ignore', - dest='ignore', default=None) - parser.add_argument('-p', '--pagesize', help='The paged result grouping size (default 500 entries)', - dest='pagesize', default=500) - # Offline mode - parser.add_argument('-M', '--mldif', help='Master LDIF file (offline mode)', - dest='mldif', default=None) - parser.add_argument('-R', '--rldif', help='Replica LDIF file (offline mode)', - dest='rldif', default=None) + # Make sure the URLs are different + if args.murl == args.rurl: + print("Master and Replica LDAP URLs are the same, they must be different") + sys.exit(1) - # Process the options - args = parser.parse_args() - opts = {} + # Parse Master url + if not ldapurl.isLDAPUrl(args.murl): + print("Master LDAP URL is invalid") + sys.exit(1) + murl = ldapurl.LDAPUrl(args.murl) + if murl.urlscheme in VALID_PROTOCOLS: + opts['mprotocol'] = murl.urlscheme + else: + print('Unsupported ldap url protocol (%s) for Master, please use "ldaps" or "ldap"' % + murl.urlscheme) + sys.exit(1) - # Check for required options - if ((args.mldif is not None and args.rldif is None) or - (args.mldif is None and args.rldif is not None)): - print("\n-------> Missing required options for offline mode!\n") - parser.print_help() - exit(1) - elif (args.mldif is None and - (args.suffix is None or - args.binddn is None or - (args.bindpw is None and args.prompt is False) or - args.murl is None or - args.rurl is None)): - print("\n-------> Missing required options for online mode!\n") - parser.print_help() - exit(1) - - # Parse the ldap URLs - if args.murl is not None and args.rurl is not None: - # Make sure the URLs are different - if args.murl == args.rurl: - print("Master and Replica LDAP URLs are the same, they must be different") - exit(1) - - # Parse Master url - if not ldapurl.isLDAPUrl(args.murl): - print("Master LDAP URL is invalid") - exit(1) - murl = ldapurl.LDAPUrl(args.murl) - if murl.urlscheme in VALID_PROTOCOLS: - opts['mprotocol'] = murl.urlscheme - else: - print('Unsupported ldap url protocol (%s) for Master, please use "ldaps" or "ldap"' % - murl.urlscheme) - parts = murl.hostport.split(':') - if len(parts) == 0: - # ldap:/// - opts['mhost'] = 'localhost' - opts['mport'] = '389' - if len(parts) == 1: - # ldap://host/ - opts['mhost'] = parts[0] - opts['mport'] = '389' - else: - # ldap://host:port/ - opts['mhost'] = parts[0] - opts['mport'] = parts[1] - - # Parse Replica url - if not ldapurl.isLDAPUrl(args.rurl): - print("Replica LDAP URL is invalid") - exit(1) - rurl = ldapurl.LDAPUrl(args.rurl) - if rurl.urlscheme in VALID_PROTOCOLS: - opts['rprotocol'] = rurl.urlscheme - else: - print('Unsupported ldap url protocol (%s) for Replica, please use "ldaps" or "ldap"' % - murl.urlscheme) - parts = rurl.hostport.split(':') - if len(parts) == 0: - # ldap:/// - opts['rhost'] = 'localhost' - opts['rport'] = '389' - elif len(parts) == 1: - # ldap://host/ - opts['rhost'] = parts[0] - opts['rport'] = '389' - else: - # ldap://host:port/ - opts['rhost'] = parts[0] - opts['rport'] = parts[1] + parts = murl.hostport.split(':') + if len(parts) == 0: + # ldap:/// + opts['mhost'] = 'localhost' + opts['mport'] = '389' + if len(parts) == 1: + # ldap://host/ + opts['mhost'] = parts[0] + opts['mport'] = '389' + else: + # ldap://host:port/ + opts['mhost'] = parts[0] + opts['mport'] = parts[1] + + # Parse Replica url + if not ldapurl.isLDAPUrl(args.rurl): + print("Replica LDAP URL is invalid") + sys.exit(1) + rurl = ldapurl.LDAPUrl(args.rurl) + if rurl.urlscheme in VALID_PROTOCOLS: + opts['rprotocol'] = rurl.urlscheme + else: + print('Unsupported ldap url protocol (%s) for Replica, please use "ldaps" or "ldap"' % + murl.urlscheme) + sys.exit(1) + parts = rurl.hostport.split(':') + if len(parts) == 0: + # ldap:/// + opts['rhost'] = 'localhost' + opts['rport'] = '389' + elif len(parts) == 1: + # ldap://host/ + opts['rhost'] = parts[0] + opts['rport'] = '389' + else: + # ldap://host:port/ + opts['rhost'] = parts[0] + opts['rport'] = parts[1] # Validate certdir opts['certdir'] = None @@ -1302,26 +1394,97 @@ def main(): opts['certdir'] = args.certdir else: print("certificate directory ({}) does not exist or is not a directory".format(args.certdir)) - exit(1) + sys.exit(1) # Initialize the options opts['binddn'] = args.binddn opts['bindpw'] = args.bindpw opts['suffix'] = args.suffix + opts['verbose'] = args.verbose + + # Get the password from a file or by prompting + if args.pass_file: + # Read password from file + try: + with open(args.pass_file, "r") as f: + opts['bindpw'] = f.readline().rstrip() + f.close() + except EnvironmentError as e: + print("Failed to open password file: " + str(e)) + sys.exit(1) + elif args.prompt or args.bindpw is None: + # prompt for password + opts['bindpw'] = getpass.getpass('Enter password: ') + + return opts + + +def online_report(args): + """Prepare to do the online report + :param args - The argparse args + """ + + opts = init_online_params(args) + + opts['starttime'] = int(time.time()) + opts['pagesize'] = int(args.pagesize) + opts['conflicts'] = args.conflicts + opts['ignore'] = ['createtimestamp', 'nscpentrywsi'] + if args.ignore: + opts['ignore'] = opts['ignore'] + args.ignore.split(',') + opts['lag'] = int(args.lag) + + OUTPUT_FILE = None + if args.file: + # Write report to the file + try: + OUTPUT_FILE = open(args.file, "w") + except IOError: + print("Can't open file: " + args.file) + sys.exit(1) + + if opts['verbose']: + print("Performing online report...") + do_online_report(opts, OUTPUT_FILE) + + # Done, cleanup + if OUTPUT_FILE is not None: + if opts['verbose']: + print('Finished writing report to "%s"' % (args.file)) + OUTPUT_FILE.close() + + +def offline_report(args): + """Prepare to do an offline report + :param args - The argparse args + """ + + opts = {} + + # Initialize the options + opts['rid'] = args.rid + opts['suffix'] = args.suffix opts['starttime'] = int(time.time()) opts['verbose'] = args.verbose opts['mldif'] = args.mldif opts['rldif'] = args.rldif - opts['pagesize'] = int(args.pagesize) opts['conflicts'] = args.conflicts + opts['lag'] = 0 opts['ignore'] = ['createtimestamp', 'nscpentrywsi'] if args.ignore: opts['ignore'] = opts['ignore'] + args.ignore.split(',') - if args.mldif: - # We're offline - "lag" only applies to online mode - opts['lag'] = 0 - else: - opts['lag'] = int(args.lag) + + # Validate LDIF files, must exist and not be empty + for ldif_dir in [opts['mldif'], opts['rldif']]: + if not os.path.exists(ldif_dir): + print ("LDIF file ({}) does not exist".format(ldif_dir)) + sys.exit(1) + if os.path.getsize(ldif_dir) == 0: + print ("LDIF file ({}) is empty".format(ldif_dir)) + sys.exit(1) + if opts['mldif'] == opts['rldif']: + print("The Master and Replica LDIF files must be different") + sys.exit(1) OUTPUT_FILE = None if args.file: @@ -1330,34 +1493,114 @@ def main(): OUTPUT_FILE = open(args.file, "w") except IOError: print("Can't open file: " + args.file) - exit(1) - - if args.prompt: - opts['bindpw'] = getpass.getpass('Enter password:') - - if opts['mldif'] is not None and opts['rldif'] is not None: - print ("Performing offline report...") - - # Validate LDIF files, must exist and not be empty - for ldif_dir in [opts['mldif'], opts['rldif']]: - if not os.path.exists(ldif_dir): - print ("LDIF file ({}) does not exist".format(ldif_dir)) - exit(1) - if os.path.getsize(ldif_dir) == 0: - print ("LDIF file ({}) is empty".format(ldif_dir)) - exit(1) - if opts['mldif'] == opts['rldif']: - print("The Master and Replica LDIF files must be different") - exit(1) - do_offline_report(opts, OUTPUT_FILE) - else: - print ("Performing online report...") - do_online_report(opts, OUTPUT_FILE) + sys.exit(1) + if opts['verbose']: + print("Performing offline report...") + do_offline_report(opts, OUTPUT_FILE) + + # Done, cleanup if OUTPUT_FILE is not None: - print('Finished writing report to "%s"' % (args.file)) + if opts['verbose']: + print('Finished writing report to "%s"' % (args.file)) OUTPUT_FILE.close() +def get_state(args): + """Just do the RUV comparision + """ + opts = init_online_params(args) + master, replica, opts = connect_to_replicas(opts) + print(get_ruv_state(opts)) + + +# handle a control-c gracefully +def signal_handler(signal, frame): + print('\n\nExiting...') + sys.exit(0) + + +def main(): + desc = ("""Replication Comparison Tool (v""" + VERSION + """). This script """ + + """can be used to compare two replicas to see if they are in sync.""") + + parser = argparse.ArgumentParser(description=desc, allow_abbrev=True) + parser.add_argument('-v', '--verbose', help='Verbose output', action='store_true', default=False, dest='verbose') + + subparsers = parser.add_subparsers(help="resources to act upon") + + # Get state + state_parser = subparsers.add_parser('state', help="Get the current replicaton state between two replicas") + state_parser.set_defaults(func=get_state) + state_parser.add_argument('-m', '--master-url', help='The LDAP URL for the Master server', + dest='murl', default=None, required=True) + state_parser.add_argument('-r', '--replica-url', help='The LDAP URL for the Replica server', + dest='rurl', required=True, default=None) + state_parser.add_argument('-b', '--suffix', help='Replicated suffix', dest='suffix', required=True) + state_parser.add_argument('-D', '--bind-dn', help='The Bind DN', required=True, dest='binddn', default=None) + state_parser.add_argument('-w', '--bind-pw', help='The Bind password', dest='bindpw', default=None) + state_parser.add_argument('-W', '--prompt', help='Prompt for the bind DN password', action='store_true', dest='prompt', default=False) + state_parser.add_argument('-y', '--pass-file', help='A text file containing the clear text password for the bind dn', dest='pass_file', default=None) + state_parser.add_argument('-Z', '--cert-dir', help='The certificate database directory for secure connections', + dest='certdir', default=None) + + # Online mode + online_parser = subparsers.add_parser('online', help="Compare two online replicas for differences") + online_parser.set_defaults(func=online_report) + online_parser.add_argument('-m', '--master-url', help='The LDAP URL for the Master server (REQUIRED)', + dest='murl', default=None, required=True) + online_parser.add_argument('-r', '--replica-url', help='The LDAP URL for the Replica server (REQUIRED)', + dest='rurl', required=True, default=None) + online_parser.add_argument('-b', '--suffix', help='Replicated suffix', dest='suffix', required=True) + online_parser.add_argument('-D', '--bind-dn', help='The Bind DN', required=True, dest='binddn', default=None) + online_parser.add_argument('-w', '--bind-pw', help='The Bind password', dest='bindpw', default=None) + online_parser.add_argument('-W', '--prompt', help='Prompt for the bind DN password', action='store_true', dest='prompt', default=False) + online_parser.add_argument('-y', '--pass-file', help='A text file contained the clear text password for the bind dn', dest='pass_file', default=None) + online_parser.add_argument('-l', '--lag-time', help='The amount of time to ignore inconsistencies (default 300 seconds)', + dest='lag', default='300') + online_parser.add_argument('-c', '--conflicts', help='Display verbose conflict information', action='store_true', + dest='conflicts', default=False) + online_parser.add_argument('-Z', '--cert-dir', help='The certificate database directory for secure connections', + dest='certdir', default=None) + online_parser.add_argument('-i', '--ignore', help='Comma separated list of attributes to ignore', + dest='ignore', default=None) + online_parser.add_argument('-p', '--page-size', help='The paged-search result grouping size (default 500 entries)', + dest='pagesize', default=500) + online_parser.add_argument('-o', '--out-file', help='The output file', dest='file', default=None) + + # Offline LDIF mode + offline_parser = subparsers.add_parser('offline', help="Compare two replication LDIF files for differences (LDIF file generated by 'db2ldif -r')") + offline_parser.set_defaults(func=offline_report) + offline_parser.add_argument('-m', '--master-ldif', help='Master LDIF file', + dest='mldif', default=None, required=True) + offline_parser.add_argument('-r', '--replica-ldif', help='Replica LDIF file', + dest='rldif', default=None, required=True) + offline_parser.add_argument('--rid', dest='rid', default=None, required=True, + help='The Replica Identifer (rid) for the "Master" server') + offline_parser.add_argument('-b', '--suffix', help='Replicated suffix', dest='suffix', required=True) + offline_parser.add_argument('-c', '--conflicts', help='Display verbose conflict information', action='store_true', + dest='conflicts', default=False) + offline_parser.add_argument('-i', '--ignore', help='Comma separated list of attributes to ignore', + dest='ignore', default=None) + offline_parser.add_argument('-o', '--out-file', help='The output file', dest='file', default=None) + + + # Process the options + argcomplete.autocomplete(parser) + + args = parser.parse_args() + + if not hasattr(args, 'func'): + print("No action provided, here is some --help.") + parser.print_help() + sys.exit(1) + + # Control C handler + signal.signal(signal.SIGINT, signal_handler) + + # Do it! + args.func(args) + + if __name__ == '__main__': main() diff --git a/man/man1/ds-replcheck.1 b/man/man1/ds-replcheck.1 index e60438c70..329b9f77e 100644 --- a/man/man1/ds-replcheck.1 +++ b/man/man1/ds-replcheck.1 @@ -1,93 +1,163 @@ -.\" Hey, EMACS: -*- nroff -*- -.\" First parameter, NAME, should be all caps -.\" Second parameter, SECTION, should be 1-8, maybe w/ subsection -.\" other parameters are allowed: see man(7), man(1) -.TH DS-REPLCHECK 1 "Feb 14, 2018" -.\" Please adjust this date whenever revising the manpage. -.\" -.\" Some roff macros, for reference: -.\" .nh disable hyphenation -.\" .hy enable hyphenation -.\" .ad l left justify -.\" .ad b justify to both left and right margins -.\" .nf disable filling -.\" .fi enable filling -.\" .br insert line break -.\" .sp <n> insert n+1 empty lines -.\" for manpage-specific macros, see man(7) -.SH NAME -ds-replcheck - Performs replication synchronization report between two replicas - +.TH DS-REPLCHECK 1 "Nov 26, 2018" +.SH NAME +ds-replcheck .SH SYNOPSIS -ds-replcheck [-h] [-o FILE] [-D BINDDN] [[-w BINDPW] [-W]] [-m MURL] - [-r RURL] [-b SUFFIX] [-l LAG] [-Z CERTDIR] - [-i IGNORE] [-p PAGESIZE] [-M MLDIF] [-R RLDIF] - +.B ds-replcheck +[-h] [-v] {online,offline,state} ... .SH DESCRIPTION -ds-replcheck has two operating modes: offline - which compares two LDIF files (generated by db2ldif -r), and online mode - which queries each server to gather the entries for comparisions. The tool reports on missing entries, entry inconsistencies, tombstones, conflict entries, database RUVs, and entry counts. - +Replication Comparison Tool (v2.0). This script can be used to compare two +.br +replicas to see if they are in sync. .SH OPTIONS +.SS +\fBSub-commands\fR +.TP +\fBds-replcheck\fR \fI\,online\/\fR +Compare two online replicas for differences +.TP +\fBds-replcheck\fR \fI\,offline\/\fR +Compare two replication LDIF files for differences (LDIF file generated by 'db2ldif -r') +.TP +\fBds-replcheck\fR \fI\,state\/\fR +Get the general state of replication between two replicas -A summary of options is included below: +.SH OPTIONS 'ds-replcheck state' +usage: ds-replcheck online [-h] -m MURL -r RURL -b SUFFIX -D BINDDN + [-w BINDPW] [-W] [-y PASS_FILE] [-Z CERTDIR] .TP -.B \fB\-h\fR -.br -Display usage +\fB\-m\fR \fI\,MURL\/\fR, \fB\-\-master\-url\fR \fI\,MURL\/\fR +The LDAP URL for the Master server + .TP -.B \fB\-D\fR \fIRoot DN\fR -The Directory Manager DN, or root DN.a (online mode) +\fB\-r\fR \fI\,RURL\/\fR, \fB\-\-replica\-url\fR \fI\,RURL\/\fR +The LDAP URL for the Replica server + .TP -.B \fB\-w\fR \fIPASSWORD\fR -The Directory Manager password (online mode) +\fB\-b\fR \fI\,SUFFIX\/\fR, \fB\-\-suffix\fR \fI\,SUFFIX\/\fR +Replicated suffix + .TP -.B \fB\-W\fR -.br -Prompt for the Directory Manager password (online mode) +\fB\-D\fR \fI\,BINDDN\/\fR, \fB\-\-bind\-dn\fR \fI\,BINDDN\/\fR +The Bind DN + +.TP +\fB\-w\fR \fI\,BINDPW\/\fR, \fB\-\-bind\-pw\fR \fI\,BINDPW\/\fR +The Bind password + .TP -.B \fB\-m\fR \fILDAP_URL\fR -The LDAP Url for the first replica (online mode) +\fB\-W\fR, \fB\-\-prompt\fR +Prompt for the bind DN password + .TP -.B \fB\-r\fR \fILDAP URL\fR -The LDAP Url for the second replica (online mode) +\fB\-y\fR \fI\,PASS_FILE\/\fR, \fB\-\-pass\-file\fR \fI\,PASS_FILE\/\fR +A text file containing the clear text password for the bind dn + .TP -.B \fB\-b\fR \fISUFFIX\fR -The replication suffix. (online & offline) +\fB\-Z\fR \fI\,CERTDIR\/\fR, \fB\-\-cert\-dir\fR \fI\,CERTDIR\/\fR +The certificate database directory for secure connections + + +.SH OPTIONS 'ds-replcheck online' +usage: ds-replcheck online [-h] -m MURL -r RURL --rid RID -b SUFFIX -D BINDDN + [-w BINDPW] [-W] [-y PASS_FILE] [-l LAG] [-c] + [-Z CERTDIR] [-i IGNORE] [-p PAGESIZE] [-o FILE] + + .TP -.B \fB\-l\fR \fILag time\fR -If an inconsistency is detected, and it is within this lag allowance it will *NOT* be reported. (online mode) +\fB\-m\fR \fI\,MURL\/\fR, \fB\-\-master\-url\fR \fI\,MURL\/\fR +The LDAP URL for the Master server + .TP -.B \fB\-Z\fR \fICERT DIR\fR -The directory containing a certificate database for StartTLS/SSL connections. (online mode) +\fB\-r\fR \fI\,RURL\/\fR, \fB\-\-replica\-url\fR \fI\,RURL\/\fR +The LDAP URL for the Replica server + .TP -.B \fB\-i\fR \fIIGNORE LIST\fR -Comma separated list of attributes to ignore in the report (online & offline) +\fB\-b\fR \fI\,SUFFIX\/\fR, \fB\-\-suffix\fR \fI\,SUFFIX\/\fR +Replicated suffix + .TP -.B \fB\-c\fR -.br +\fB\-D\fR \fI\,BINDDN\/\fR, \fB\-\-bind\-dn\fR \fI\,BINDDN\/\fR +The Bind DN + +.TP +\fB\-w\fR \fI\,BINDPW\/\fR, \fB\-\-bind\-pw\fR \fI\,BINDPW\/\fR +The Bind password + +.TP +\fB\-W\fR, \fB\-\-prompt\fR +Prompt for the bind DN password + +.TP +\fB\-y\fR \fI\,PASS_FILE\/\fR, \fB\-\-pass\-file\fR \fI\,PASS_FILE\/\fR +A text file containing the clear text password for the bind dn + +.TP +\fB\-l\fR \fI\,LAG\/\fR, \fB\-\-lag\-time\fR \fI\,LAG\/\fR +The amount of time to ignore inconsistencies (default 300 seconds) + +.TP +\fB\-c\fR, \fB\-\-conflicts\fR Display verbose conflict entry information + .TP -.B \fB\-M\fR \fILDIF FILE\fR -The LDIF file for the first replica (offline mode) +\fB\-Z\fR \fI\,CERTDIR\/\fR, \fB\-\-cert\-dir\fR \fI\,CERTDIR\/\fR +The certificate database directory for secure connections + .TP -.B \fB\-R\fR \fILDIF FILE\fR -The LDIF file for the second replica (offline mode) +\fB\-i\fR \fI\,IGNORE\/\fR, \fB\-\-ignore\fR \fI\,IGNORE\/\fR +Comma separated list of attributes to ignore + .TP -.B \fB\-p\fR \fIPAGE SIZE\fR -The page size used for the paged result searches that the tool performs. The default is 500. (online mode) +\fB\-p\fR \fI\,PAGESIZE\/\fR, \fB\-\-page\-size\fR \fI\,PAGESIZE\/\fR +The paged\-search result grouping size (default 500 entries) + .TP -.B \fB\-o\fR \fIOUTPUT FILE\fR -The file to write the report to. (online and offline) +\fB\-o\fR \fI\,FILE\/\fR, \fB\-\-out\-file\fR \fI\,FILE\/\fR +The output file + +.SH OPTIONS 'ds-replcheck offline' +usage: ds-replcheck offline [-h] -m MLDIF -r RLDIF --rid RID -b SUFFIX [-c] + [-i IGNORE] [-o FILE] -.SH EXAMPLE -ds-replcheck -D "cn=directory manager" -w PASSWORD -m ldap://myhost.domain.com:389 -r ldap://otherhost.domain.com:389 -b "dc=example,dc=com" -Z /etc/dirsrv/slapd-myinstance -ds-replcheck -b dc=example,dc=com -M /tmp/replicaA.ldif -R /tmp/replicaB.ldif +.TP +\fB\-m\fR \fI\,MLDIF\/\fR, \fB\-\-master\-ldif\fR \fI\,MLDIF\/\fR +Master LDIF file + +.TP +\fB\-r\fR \fI\,RLDIF\/\fR, \fB\-\-replica\-ldif\fR \fI\,RLDIF\/\fR +Replica LDIF file + +.TP +\fB\-\-rid\fR \fI\,RID\/\fR +The Replica Identifier (rid) for the "Master" server + +.TP +\fB\-b\fR \fI\,SUFFIX\/\fR, \fB\-\-suffix\fR \fI\,SUFFIX\/\fR +Replicated suffix + +.TP +\fB\-c\fR, \fB\-\-conflicts\fR +Display verbose conflict entry information + +.TP +\fB\-i\fR \fI\,IGNORE\/\fR, \fB\-\-ignore\fR \fI\,IGNORE\/\fR +Comma separated list of attributes to ignore + +.TP +\fB\-o\fR \fI\,FILE\/\fR, \fB\-\-out\-file\fR \fI\,FILE\/\fR +The output file + +.TP +\fB\-v\fR, \fB\-\-verbose\fR +Verbose output .SH AUTHOR ds-replcheck was written by the 389 Project. + .SH "REPORTING BUGS" Report bugs to https://pagure.io/389-ds-base/new_issue + .SH COPYRIGHT Copyright \(co 2018 Red Hat, Inc. -
0
324eb761dfa4d3879af7f848ba3ac53e090155a1
389ds/389-ds-base
Coverity fix -- 13164: Logically dead code Bug description: commit 1cbd6d84dd0871af4955ebf93693e8b4331ab07e for Ticket 47325 - Crash at shutdown on a replica agreement introduced '13164: Logically dead code'. Fix description: Since bind_timeout never be NULL, no need to do NULL check. Eliminated the dead code. https://fedorahosted.org/389/ticket/47325
commit 324eb761dfa4d3879af7f848ba3ac53e090155a1 Author: Noriko Hosoi <[email protected]> Date: Tue Apr 30 18:09:34 2013 -0700 Coverity fix -- 13164: Logically dead code Bug description: commit 1cbd6d84dd0871af4955ebf93693e8b4331ab07e for Ticket 47325 - Crash at shutdown on a replica agreement introduced '13164: Logically dead code'. Fix description: Since bind_timeout never be NULL, no need to do NULL check. Eliminated the dead code. https://fedorahosted.org/389/ticket/47325 diff --git a/ldap/servers/slapd/ldaputil.c b/ldap/servers/slapd/ldaputil.c index c0c4511b2..f7535705c 100644 --- a/ldap/servers/slapd/ldaputil.c +++ b/ldap/servers/slapd/ldaputil.c @@ -1156,8 +1156,7 @@ slapi_ldap_bind( slapi_log_error(SLAPI_LOG_FATAL, "slapi_ldap_bind", "Error: timeout after [%ld.%ld] seconds reading " "bind response for [%s] authentication mechanism [%s]\n", - bind_timeout ? bind_timeout->tv_sec : 0, - bind_timeout ? bind_timeout->tv_usec : 0, + bind_timeout->tv_sec, bind_timeout->tv_usec, bindid ? bindid : "(anon)", mech ? mech : "SIMPLE"); goto done;
0
00672ce8af7c3af0e2120a97da09f1f64a18faf3
389ds/389-ds-base
Fix various bad memory free bugs
commit 00672ce8af7c3af0e2120a97da09f1f64a18faf3 Author: David Boreham <[email protected]> Date: Wed May 4 23:53:19 2005 +0000 Fix various bad memory free bugs diff --git a/ldap/servers/ntds/netman/Makefile b/ldap/servers/ntds/netman/Makefile index 2ce694218..e80862697 100644 --- a/ldap/servers/ntds/netman/Makefile +++ b/ldap/servers/ntds/netman/Makefile @@ -76,10 +76,10 @@ $(JAVA_DEST_DIR)/ntds/jnetman.jar: $(OBJDEST)/jnetman_wrap.cxx $(OBJDEST)/jnetman.dll: $(OBJDEST)/netman.obj $(OBJDEST)/jnetman_wrap.obj $(LINK_DLL) /out:$(OBJDEST)/jnetman.dll $(EXTRA_LIBS) netapi32.lib $(OBJDEST)/netman.obj $(OBJDEST)/jnetman_wrap.obj -$(OBJDEST)/netman.obj: +$(OBJDEST)/netman.obj: netman.cpp netman.h $(CC) -c netman.cpp $(CFLAGS) $(MCC_INCLUDE) -Fo$(OBJDEST)/ $(CBSCFLAGS) -$(OBJDEST)/jnetman_wrap.obj: +$(OBJDEST)/jnetman_wrap.obj: $(OBJDEST)/jnetman_wrap.cxx $(CC) -c $(OBJDEST)/jnetman_wrap.cxx $(CFLAGS) $(MCC_INCLUDE) -Fo$(OBJDEST)/ $(CBSCFLAGS) /I$(JAVA_HOME)/include /I$(JAVA_HOME)/include/win32 /I. veryclean: clean diff --git a/ldap/servers/ntds/netman/netman.cpp b/ldap/servers/ntds/netman/netman.cpp index 885c3da73..5d9447b9e 100644 --- a/ldap/servers/ntds/netman/netman.cpp +++ b/ldap/servers/ntds/netman/netman.cpp @@ -71,36 +71,36 @@ unsigned short* UTF8ToUTF16(char* inString) } // **************************************************************** -// SIDToHexStr +// BinToHexStr // **************************************************************** -int SIDToHexStr(char* sid, unsigned long sidLen, char** hexStr) +int BinToHexStr(char* bin, unsigned long binLen, char** hexStr) { - int hexStrLen = sidLen * 2 + 1; + int hexStrLen = binLen * 2 + 1; *hexStr = (char*)calloc(hexStrLen, sizeof(char)); - for(unsigned long i = 0; i < sidLen; i++) + for(unsigned long i = 0; i < binLen; i++) { - sprintf(&(*hexStr)[i * 2], "%02X", (unsigned char)sid[i]); + sprintf(&(*hexStr)[i * 2], "%02X", (unsigned char)bin[i]); } return 0; } // **************************************************************** -// HexStrToSID +// HexStrToBin // **************************************************************** -int HexStrToSID(char* hexStr, char** sid, unsigned long* sidLen) +int HexStrToBin(char* hexStr, char** bin, unsigned long* binLen) { int temp; - *sidLen = strlen(hexStr) / 2; + *binLen = strlen(hexStr) / 2; - *sid = (char*)malloc(*sidLen); + *bin = (char*)malloc(*binLen); - for(unsigned long i = 0; i < *sidLen; i++) + for(unsigned long i = 0; i < *binLen; i++) { sscanf(&hexStr[i * 2], "%02X", &temp); - (*sid)[i] = (unsigned char)temp; + (*bin)[i] = (unsigned char)temp; } return 0; @@ -200,7 +200,7 @@ int GetSIDHexStrByAccountName(char* accountName, char** sidHexStr) } - SIDToHexStr(sid, sidLen, sidHexStr); + BinToHexStr(sid, sidLen, sidHexStr); return result; } @@ -219,7 +219,7 @@ int GetAccountNameBySIDHexStr(char* sidHexStr, char** accountName) unsigned long accountNameLen = 0; - HexStrToSID(sidHexStr, &sid, &sidLen); + HexStrToBin(sidHexStr, &sid, &sidLen); if(LookupAccountSid(NULL, sid, NULL, &accountNameLen, NULL, &domainLen, &testType) == 0) { @@ -292,7 +292,7 @@ void NTUser::NewUser(char* username) userInfo = NULL; } - userInfo = (USER_INFO_3*)malloc(sizeof(USER_INFO_3)); + NetApiBufferAllocate(sizeof(USER_INFO_3),(LPVOID*)&userInfo); memset(userInfo, 0, sizeof(USER_INFO_3)); userInfo->usri3_name = UTF8ToUTF16(username); @@ -746,7 +746,7 @@ char* NTUser::GetLogonHours() if(userInfo != NULL) { - result = (char*)userInfo->usri3_logon_hours; + BinToHexStr((char*)userInfo->usri3_logon_hours, 21, &result); } return result; @@ -758,10 +758,13 @@ char* NTUser::GetLogonHours() int NTUser::SetLogonHours(char* logonHours) { int result = 0; + char* binValue; + unsigned long binLen = 0; if(userInfo != NULL) { - userInfo->usri3_logon_hours = (unsigned char*)logonHours; + HexStrToBin(logonHours, &binValue, &binLen); + userInfo->usri3_logon_hours = (unsigned char*)binValue; } else { @@ -1215,6 +1218,8 @@ char* NTUser::NextLocalGroupName() // **************************************************************** NTUserList::NTUserList() { + entriesRead = 0; + totalEntries = 0; bufptr = NULL; currentEntry = 0; resumeHandle = 0; @@ -1287,6 +1292,10 @@ char* NTUserList::nextUsername() NTGroup::NTGroup() { groupInfo = NULL; + usersInfo = NULL; + currentUserEntry = 0; + userEntriesRead = 0; + userEntriesTotal = 0; } // **************************************************************** @@ -1299,6 +1308,11 @@ NTGroup::~NTGroup() NetApiBufferFree(groupInfo); groupInfo = NULL; } + if(usersInfo != NULL) + { + NetApiBufferFree(usersInfo); + usersInfo = NULL; + } } // **************************************************************** @@ -1312,7 +1326,7 @@ void NTGroup::NewGroup(char* groupName) groupInfo = NULL; } - groupInfo = (GROUP_INFO_2*)malloc(sizeof(GROUP_INFO_2)); + NetApiBufferAllocate(sizeof(GROUP_INFO_2),(LPVOID*)&groupInfo); memset(groupInfo, 0, sizeof(GROUP_INFO_2)); groupInfo->grpi2_name = UTF8ToUTF16(groupName); } @@ -1576,6 +1590,8 @@ char* NTGroup::NextUserName() // **************************************************************** NTGroupList::NTGroupList() { + entriesRead = 0; + totalEntries = 0; bufptr = NULL; currentEntry = 0; resumeHandle = 0; @@ -1648,6 +1664,10 @@ char* NTGroupList::nextGroupName() NTLocalGroup::NTLocalGroup() { localGroupInfo = NULL; + usersInfo = NULL; + currentUserEntry = 0; + userEntriesRead = 0; + userEntriesTotal = 0; } // **************************************************************** @@ -1660,6 +1680,11 @@ NTLocalGroup::~NTLocalGroup() NetApiBufferFree(localGroupInfo); localGroupInfo = NULL; } + if(usersInfo != NULL) + { + NetApiBufferFree(usersInfo); + usersInfo = NULL; + } } // **************************************************************** @@ -1673,7 +1698,7 @@ void NTLocalGroup::NewLocalGroup(char* localGroupName) localGroupInfo = NULL; } - localGroupInfo = (LOCALGROUP_INFO_1*)malloc(sizeof(LOCALGROUP_INFO_1)); + NetApiBufferAllocate(sizeof(LOCALGROUP_INFO_1),(LPVOID*)&localGroupInfo); memset(localGroupInfo, 0, sizeof(LOCALGROUP_INFO_1)); localGroupInfo->lgrpi1_name = UTF8ToUTF16(localGroupName); } @@ -1947,6 +1972,8 @@ char* NTLocalGroup::NextUserName() // **************************************************************** NTLocalGroupList::NTLocalGroupList() { + entriesRead = 0; + totalEntries = 0; bufptr = NULL; currentEntry = 0; resumeHandle = 0;
0
59ae6fe07d5edc58a5b07ce5bd961b9714157089
389ds/389-ds-base
openldap ldapsearch returns empty line at end of LDIF output The script was looking for 1 and only 1 line returned by the ldapsearch to see if the given entry is a role. openldap ldapsearch returns an empty line as the last line. So just change the check to look for 1 or more lines.
commit 59ae6fe07d5edc58a5b07ce5bd961b9714157089 Author: Rich Megginson <[email protected]> Date: Wed Aug 18 11:07:47 2010 -0600 openldap ldapsearch returns empty line at end of LDIF output The script was looking for 1 and only 1 line returned by the ldapsearch to see if the given entry is a role. openldap ldapsearch returns an empty line as the last line. So just change the check to look for 1 or more lines. diff --git a/ldap/admin/src/scripts/template-ns-accountstatus.pl.in b/ldap/admin/src/scripts/template-ns-accountstatus.pl.in index ba6a491a1..2712d0965 100644 --- a/ldap/admin/src/scripts/template-ns-accountstatus.pl.in +++ b/ldap/admin/src/scripts/template-ns-accountstatus.pl.in @@ -505,7 +505,7 @@ if ( $retCode2 != 0 ) exit $retCode2; } -if ( $nbLineRole == 1 ) +if ( $nbLineRole > 0 ) { debug("Groups of users\n"); $role=1; diff --git a/ldap/admin/src/scripts/template-ns-activate.pl.in b/ldap/admin/src/scripts/template-ns-activate.pl.in index ba6a491a1..2712d0965 100644 --- a/ldap/admin/src/scripts/template-ns-activate.pl.in +++ b/ldap/admin/src/scripts/template-ns-activate.pl.in @@ -505,7 +505,7 @@ if ( $retCode2 != 0 ) exit $retCode2; } -if ( $nbLineRole == 1 ) +if ( $nbLineRole > 0 ) { debug("Groups of users\n"); $role=1; diff --git a/ldap/admin/src/scripts/template-ns-inactivate.pl.in b/ldap/admin/src/scripts/template-ns-inactivate.pl.in index ba6a491a1..2712d0965 100644 --- a/ldap/admin/src/scripts/template-ns-inactivate.pl.in +++ b/ldap/admin/src/scripts/template-ns-inactivate.pl.in @@ -505,7 +505,7 @@ if ( $retCode2 != 0 ) exit $retCode2; } -if ( $nbLineRole == 1 ) +if ( $nbLineRole > 0 ) { debug("Groups of users\n"); $role=1;
0
11a5b1e412cb77a752366e352cb9d203c52b108e
389ds/389-ds-base
Ticket 48414 - cleanAllRUV should clean the agreement RUV Bug Description: After running cleanAllRUV the RUV attributes in the replication agreements are not updated until the server is restarted. This can cause confusion about the success of the task. Fix Description: At the end of the task, stop the agreement, clean it, and start it back up. https://fedorahosted.org/389/ticket/48414 Reviewed by: nhosoi(Thanks!)
commit 11a5b1e412cb77a752366e352cb9d203c52b108e Author: Mark Reynolds <[email protected]> Date: Tue Sep 6 10:39:46 2016 -0400 Ticket 48414 - cleanAllRUV should clean the agreement RUV Bug Description: After running cleanAllRUV the RUV attributes in the replication agreements are not updated until the server is restarted. This can cause confusion about the success of the task. Fix Description: At the end of the task, stop the agreement, clean it, and start it back up. https://fedorahosted.org/389/ticket/48414 Reviewed by: nhosoi(Thanks!) diff --git a/ldap/servers/plugins/replication/repl5_replica_config.c b/ldap/servers/plugins/replication/repl5_replica_config.c index 25adacd95..bbaf57411 100644 --- a/ldap/servers/plugins/replication/repl5_replica_config.c +++ b/ldap/servers/plugins/replication/repl5_replica_config.c @@ -83,6 +83,7 @@ static multimaster_mtnode_extension * _replica_config_get_mtnode_ext (const Slap static void replica_cleanall_ruv_destructor(Slapi_Task *task); static void replica_cleanall_ruv_abort_destructor(Slapi_Task *task); static void remove_keep_alive_entry(Slapi_Task *task, ReplicaId rid, const char *repl_root); +static void clean_agmts(cleanruv_data *data); /* * Note: internal add/modify/delete operations should not be run while @@ -1987,13 +1988,15 @@ done: * Delete the cleaned rid config. * Make sure all the replicas have been "pre_cleaned" * Remove the keep alive entry if present + * Clean the agreements' RUV * Remove the rid from the internal clean list */ delete_cleaned_rid_config(data); check_replicas_are_done_cleaning(data); remove_keep_alive_entry(data->task, data->rid, data->repl_root); - cleanruv_log(data->task, data->rid, CLEANALLRUV_ID, "Successfully cleaned rid(%d).", data->rid); + clean_agmts(data); remove_cleaned_rid(data->rid); + cleanruv_log(data->task, data->rid, CLEANALLRUV_ID, "Successfully cleaned rid(%d).", data->rid); } else { /* * Shutdown or abort @@ -2026,6 +2029,34 @@ done: slapi_ch_free((void **)&data); } +/* + * Clean the RUV attributes from all the agreements + */ +static void +clean_agmts(cleanruv_data *data) +{ + Object *agmt_obj = NULL; + Repl_Agmt *agmt = NULL; + + agmt_obj = agmtlist_get_first_agreement_for_replica (data->replica); + if(agmt_obj == NULL){ + return; + } + while (agmt_obj && !slapi_is_shutting_down()){ + agmt = (Repl_Agmt*)object_get_data (agmt_obj); + if(!agmt_is_enabled(agmt) || get_agmt_agreement_type(agmt) == REPLICA_TYPE_WINDOWS){ + agmt_obj = agmtlist_get_next_agreement_for_replica (data->replica, agmt_obj); + continue; + } + cleanruv_log(data->task, data->rid, CLEANALLRUV_ID, "Cleaning agmt..."); + agmt_stop(agmt); + agmt_update_consumer_ruv(agmt); + agmt_start(agmt); + agmt_obj = agmtlist_get_next_agreement_for_replica (data->replica, agmt_obj); + } + cleanruv_log(data->task, data->rid, CLEANALLRUV_ID, "Cleaned replication agreements."); +} + /* * Remove the "Keep-Alive" replication entry. */
0
be93d90a5da7e0bbbf0ebe451ae5b0641be52f55
389ds/389-ds-base
Ticket 49151 - Remove defunct selinux policy Bug Description: Remove defunct and unused selinux policy from the source tree. Fix Description: rm -r selinux :) https://pagure.io/389-ds-base/issue/49151 Author: wibrown Review by: mreynolds (Thanks!)
commit be93d90a5da7e0bbbf0ebe451ae5b0641be52f55 Author: William Brown <[email protected]> Date: Fri Mar 10 14:27:56 2017 +1000 Ticket 49151 - Remove defunct selinux policy Bug Description: Remove defunct and unused selinux policy from the source tree. Fix Description: rm -r selinux :) https://pagure.io/389-ds-base/issue/49151 Author: wibrown Review by: mreynolds (Thanks!) diff --git a/Makefile.am b/Makefile.am index d712aba39..ccbb5303f 100644 --- a/Makefile.am +++ b/Makefile.am @@ -240,19 +240,12 @@ CLEANFILES = dberrstrs.h ns-slapd.properties \ clean-local: -rm -rf dist - -rm -rf selinux-built -rm -rf $(abs_top_builddir)/html -rm -rf $(abs_top_builddir)/man dberrstrs.h: Makefile perl $(srcdir)/ldap/servers/slapd/mkDBErrStrs.pl -i @db_incdir@ -o . -selinux-built: - cp -r $(srcdir)/selinux $@ - -selinux-built/dirsrv.fc: selinux-built - $(fixupcmd) selinux-built/dirsrv.fc.in > $@ - #------------------------ # Install Paths @@ -316,10 +309,6 @@ else enable_presence = off endif -if SELINUX -POLICY_FC = selinux-built/dirsrv.fc -endif - if enable_acctpolicy LIBACCTPOLICY_PLUGIN = libacctpolicy-plugin.la LIBACCTPOLICY_SCHEMA = $(srcdir)/ldap/schema/60acctpolicy.ldif @@ -591,7 +580,6 @@ dist_noinst_DATA = \ $(srcdir)/rpm/389-ds-base.spec.in \ $(srcdir)/rpm/389-ds-base-devel.README \ $(srcdir)/rpm/389-ds-base-git.sh \ - $(srcdir)/selinux \ $(srcdir)/README \ $(srcdir)/LICENSE \ $(srcdir)/LICENSE.* \ diff --git a/configure.ac b/configure.ac index ebcffd5cd..23f36b113 100644 --- a/configure.ac +++ b/configure.ac @@ -765,7 +765,6 @@ else sasl_path="$sasl_libdir/sasl2" fi -AM_CONDITIONAL(SELINUX,test "$with_selinux" = "yes") AM_CONDITIONAL(OPENLDAP,test "$with_openldap" = "yes") AM_CONDITIONAL(SOLARIS,test "$platform" = "solaris") AM_CONDITIONAL(SPARC,test "x$TARGET" = xSPARC) diff --git a/m4/selinux.m4 b/m4/selinux.m4 index 80d84b2de..1920645ec 100644 --- a/m4/selinux.m4 +++ b/m4/selinux.m4 @@ -10,7 +10,7 @@ AC_CHECKING(for SELinux) # check for --with-selinux AC_MSG_CHECKING(for --with-selinux) -AC_ARG_WITH(selinux, AS_HELP_STRING([--with-selinux],[Support SELinux policy]), +AC_ARG_WITH(selinux, AS_HELP_STRING([--with-selinux],[Support SELinux features]), [ if test "$withval" = "no"; then AC_MSG_RESULT(no) @@ -21,3 +21,6 @@ AC_ARG_WITH(selinux, AS_HELP_STRING([--with-selinux],[Support SELinux policy]), fi ], AC_MSG_RESULT(no)) + +AM_CONDITIONAL(SELINUX,test "$with_selinux" = "yes") + diff --git a/selinux/Makefile b/selinux/Makefile deleted file mode 100644 index bc8e6a73b..000000000 --- a/selinux/Makefile +++ /dev/null @@ -1,17 +0,0 @@ -POLICY_MAKEFILE = /usr/share/selinux/devel/Makefile -POLICY_DIR = $(DESTDIR)/usr/share/selinux/targeted - -all: - if [ ! -e $(POLICY_MAKEFILE) ]; then echo "You need to install the SELinux policy development tools (selinux-policy)" && exit 1; fi - - $(MAKE) -f $(POLICY_MAKEFILE) $@ || exit 1; - -clean: - $(MAKE) -f $(POLICY_MAKEFILE) $@ || exit 1; - -install: all - install -d $(POLICY_DIR) - install -m 644 dirsrv.pp $(POLICY_DIR) - -load: - /usr/sbin/semodule -i dirsrv.pp diff --git a/selinux/dirsrv.fc.in b/selinux/dirsrv.fc.in deleted file mode 100644 index 1cfce884c..000000000 --- a/selinux/dirsrv.fc.in +++ /dev/null @@ -1,24 +0,0 @@ -# dirsrv executable will have: -# label: system_u:object_r:dirsrv_exec_t -# MLS sensitivity: s0 -# MCS categories: <none> - -@sbindir@/ns-slapd -- gen_context(system_u:object_r:dirsrv_exec_t,s0) -@sbindir@/ldap-agent -- gen_context(system_u:object_r:initrc_exec_t,s0) -@sbindir@/ldap-agent-bin -- gen_context(system_u:object_r:dirsrv_snmp_exec_t,s0) -@sbindir@/start-dirsrv -- gen_context(system_u:object_r:initrc_exec_t,s0) -@sbindir@/restart-dirsrv -- gen_context(system_u:object_r:initrc_exec_t,s0) -@localstatedir@/run/@package_name@ gen_context(system_u:object_r:dirsrv_var_run_t,s0) -@localstatedir@/run/@package_name@(/.*) gen_context(system_u:object_r:dirsrv_var_run_t,s0) -@localstatedir@/run/ldap-agent.pid gen_context(system_u:object_r:dirsrv_snmp_var_run_t,s0) -@localstatedir@/log/@package_name@ gen_context(system_u:object_r:dirsrv_var_log_t,s0) -@localstatedir@/log/@package_name@(/.*) gen_context(system_u:object_r:dirsrv_var_log_t,s0) -@localstatedir@/log/@package_name@/ldap-agent.log gen_context(system_u:object_r:dirsrv_snmp_var_log_t,s0) -@localstatedir@/lock/@package_name@ gen_context(system_u:object_r:dirsrv_var_lock_t,s0) -@localstatedir@/lock/@package_name@(/.*) gen_context(system_u:object_r:dirsrv_var_lock_t,s0) -@localstatedir@/lib/@package_name@ gen_context(system_u:object_r:dirsrv_var_lib_t,s0) -@localstatedir@/lib/@package_name@(/.*) gen_context(system_u:object_r:dirsrv_var_lib_t,s0) -@sysconfdir@/@package_name@ gen_context(system_u:object_r:dirsrv_config_t,s0) -@sysconfdir@/@package_name@(/.*) gen_context(system_u:object_r:dirsrv_config_t,s0) -@datadir@/@package_name@ gen_context(system_u:object_r:dirsrv_share_t,s0) -@datadir@/@package_name@(/.*) gen_context(system_u:object_r:dirsrv_share_t,s0) diff --git a/selinux/dirsrv.if b/selinux/dirsrv.if deleted file mode 100644 index 647879949..000000000 --- a/selinux/dirsrv.if +++ /dev/null @@ -1,193 +0,0 @@ -## <summary>policy for dirsrv</summary> - -######################################## -## <summary> -## Execute a domain transition to run dirsrv. -## </summary> -## <param name="domain"> -## <summary> -## Domain allowed to transition. -## </summary> -## </param> -# -interface(`dirsrv_domtrans',` - gen_require(` - type dirsrv_t, dirsrv_exec_t; - ') - - domain_auto_trans($1,dirsrv_exec_t,dirsrv_t) - - allow dirsrv_t $1:fd use; - allow dirsrv_t $1:fifo_file rw_file_perms; - allow dirsrv_t $1:process sigchld; -') - - -######################################## -## <summary> -## Allow caller to signal dirsrv. -## </summary> -## <param name="domain"> -## <summary> -## Domain allowed access. -## </summary> -## </param> -# -interface(`dirsrv_signal',` - gen_require(` - type dirsrv_t; - ') - - allow $1 dirsrv_t:process signal; -') - - -######################################## -## <summary> -## Send a null signal to dirsrv. -## </summary> -## <param name="domain"> -## <summary> -## Domain allowed access. -## </summary> -## </param> -# -interface(`dirsrv_signull',` - gen_require(` - type dirsrv_t; - ') - - allow $1 dirsrv_t:process signull; -') - -####################################### -## <summary> -## Allow a domain to manage dirsrv logs. -## </summary> -## <param name="domain"> -## <summary> -## Domain allowed access. -## </summary> -## </param> -# -interface(`dirsrv_manage_log',` - gen_require(` - type dirsrv_var_log_t; - ') - - allow $1 dirsrv_var_log_t:dir manage_dir_perms; - allow $1 dirsrv_var_log_t:file manage_file_perms; - allow $1 dirsrv_var_log_t:fifo_file manage_fifo_file_perms; -') - -####################################### -## <summary> -## Allow a domain to manage dirsrv /var/lib files. -## </summary> -## <param name="domain"> -## <summary> -## Domain allowed access. -## </summary> -## </param> -# -interface(`dirsrv_manage_var_lib',` - gen_require(` - type dirsrv_var_lib_t; - ') - allow $1 dirsrv_var_lib_t:dir manage_dir_perms; - allow $1 dirsrv_var_lib_t:file manage_file_perms; -') - -####################################### -## <summary> -## Allow a domain to manage dirsrv /var/run files. -## </summary> -## <param name="domain"> -## <summary> -## Domain allowed access. -## </summary> -## </param> -# -interface(`dirsrv_manage_var_run',` - gen_require(` - type dirsrv_var_run_t; - ') - allow $1 dirsrv_var_run_t:dir manage_dir_perms; - allow $1 dirsrv_var_run_t:file manage_file_perms; - allow $1 dirsrv_var_run_t:sock_file manage_file_perms; -') - -##################################### -# <summary> -# Allow a domain to create dirsrv pid directories. -# </summary> -# <param name="domain"> -# <summary> -# Domain allowed access. -# </summary> -# </param> -# -interface(`dirsrv_pid_filetrans',` - gen_require(` - type dirsrv_var_run_t; - ') - # Allow creating a dir in /var/run with this type - files_pid_filetrans($1, dirsrv_var_run_t, dir) -') - -####################################### -## <summary> -## Allow a domain to read dirsrv /var/run files. -## </summary> -## <param name="domain"> -## <summary> -## Domain allowed access. -## </summary> -## </param> -# -interface(`dirsrv_read_var_run',` - gen_require(` - type dirsrv_var_run_t; - ') - allow $1 dirsrv_var_run_t:dir list_dir_perms; - allow $1 dirsrv_var_run_t:file read_file_perms; -') - -######################################## -## <summary> -## Manage dirsrv configuration files. -## </summary> -## <param name="domain"> -## <summary> -## Domain allowed access. -## </summary> -## </param> -# -interface(`dirsrv_manage_config',` - gen_require(` - type dirsrv_config_t; - ') - - allow $1 dirsrv_config_t:dir manage_dir_perms; - allow $1 dirsrv_config_t:file manage_file_perms; -') - -######################################## -## <summary> -## Read dirsrv share files. -## </summary> -## <param name="domain"> -## <summary> -## Domain allowed access. -## </summary> -## </param> -# -interface(`dirsrv_read_share',` - gen_require(` - type dirsrv_share_t; - ') - - allow $1 dirsrv_share_t:dir list_dir_perms; - allow $1 dirsrv_share_t:file read_file_perms; - allow $1 dirsrv_share_t:lnk_file read; -') diff --git a/selinux/dirsrv.te b/selinux/dirsrv.te deleted file mode 100644 index d9c810dcc..000000000 --- a/selinux/dirsrv.te +++ /dev/null @@ -1,212 +0,0 @@ -policy_module(dirsrv,1.0.0) - -######################################## -# -# Declarations -# - -# NGK - this can go away when bz 478629, bz 523548, -# and bz 523771 are addressed. See the notes below -# where we work around those issues. -require { - type snmpd_var_lib_t; - type snmpd_t; -} - -# main daemon -type dirsrv_t; -type dirsrv_exec_t; -domain_type(dirsrv_t) -init_daemon_domain(dirsrv_t, dirsrv_exec_t) - -# snmp subagent daemon -type dirsrv_snmp_t; -type dirsrv_snmp_exec_t; -domain_type(dirsrv_snmp_t) -init_daemon_domain(dirsrv_snmp_t, dirsrv_snmp_exec_t) - -# var/lib files -type dirsrv_var_lib_t; -files_type(dirsrv_var_lib_t) - -# log files -type dirsrv_var_log_t; -logging_log_file(dirsrv_var_log_t) - -# snmp log file -type dirsrv_snmp_var_log_t; -logging_log_file(dirsrv_snmp_var_log_t) - -# pid files -type dirsrv_var_run_t; -files_pid_file(dirsrv_var_run_t) - -# snmp pid file -type dirsrv_snmp_var_run_t; -files_pid_file(dirsrv_snmp_var_run_t) - -# lock files -type dirsrv_var_lock_t; -files_lock_file(dirsrv_var_lock_t) - -# config files -type dirsrv_config_t; -files_type(dirsrv_config_t) - -# tmp files -type dirsrv_tmp_t; -files_tmp_file(dirsrv_tmp_t) - -# semaphores -type dirsrv_tmpfs_t; -files_tmpfs_file(dirsrv_tmpfs_t) - -# shared files -type dirsrv_share_t; -files_type(dirsrv_share_t); - -######################################## -# -# dirsrv local policy -# - -# Some common macros -files_read_etc_files(dirsrv_t) -corecmd_search_sbin(dirsrv_t) -files_read_usr_symlinks(dirsrv_t) -miscfiles_read_localization(dirsrv_t) -dev_read_urand(dirsrv_t) -libs_use_ld_so(dirsrv_t) -libs_use_shared_libs(dirsrv_t) -allow dirsrv_t self:fifo_file { read write }; - -# process stuff -allow dirsrv_t self:process { getsched setsched setfscreate signal_perms}; -allow dirsrv_t self:capability { sys_nice setuid setgid fsetid chown dac_override fowner }; - -# semaphores -allow dirsrv_t self:sem all_sem_perms; -manage_files_pattern(dirsrv_t, dirsrv_tmpfs_t, dirsrv_tmpfs_t) -fs_tmpfs_filetrans(dirsrv_t, dirsrv_tmpfs_t, file) - -# var/lib files for dirsrv -manage_files_pattern(dirsrv_t, dirsrv_var_lib_t, dirsrv_var_lib_t) -manage_dirs_pattern(dirsrv_t, dirsrv_var_lib_t, dirsrv_var_lib_t) -files_var_lib_filetrans(dirsrv_t,dirsrv_var_lib_t, { file dir sock_file }) - -# log files -manage_files_pattern(dirsrv_t, dirsrv_var_log_t, dirsrv_var_log_t) -manage_fifo_files_pattern(dirsrv_t, dirsrv_var_log_t, dirsrv_var_log_t) -allow dirsrv_t dirsrv_var_log_t:dir { setattr }; -logging_log_filetrans(dirsrv_t,dirsrv_var_log_t,{ sock_file file dir }) - -# pid files -manage_files_pattern(dirsrv_t, dirsrv_var_run_t, dirsrv_var_run_t) -files_pid_filetrans(dirsrv_t, dirsrv_var_run_t, { file sock_file }) - -# ldapi socket -manage_sock_files_pattern(dirsrv_t, dirsrv_var_run_t, dirsrv_var_run_t) - -# lock files -manage_files_pattern(dirsrv_t, dirsrv_var_lock_t, dirsrv_var_lock_t) -manage_dirs_pattern(dirsrv_t, dirsrv_var_lock_t, dirsrv_var_lock_t) -files_lock_filetrans(dirsrv_t, dirsrv_var_lock_t, { file }) - -# config files -manage_files_pattern(dirsrv_t, dirsrv_config_t, dirsrv_config_t) -manage_dirs_pattern(dirsrv_t, dirsrv_config_t, dirsrv_config_t) - -# tmp files -manage_files_pattern(dirsrv_t, dirsrv_tmp_t, dirsrv_tmp_t) -manage_dirs_pattern(dirsrv_t, dirsrv_tmp_t, dirsrv_tmp_t) -files_tmp_filetrans(dirsrv_t, dirsrv_tmp_t, { file dir }) - -# system state -fs_getattr_all_fs(dirsrv_t) -kernel_read_system_state(dirsrv_t) - -# kerberos config for SASL GSSAPI -kerberos_read_config(dirsrv_t) -kerberos_dontaudit_write_config(dirsrv_t) - -# Networking basics -sysnet_dns_name_resolve(dirsrv_t) -corenet_all_recvfrom_unlabeled(dirsrv_t) -corenet_all_recvfrom_netlabel(dirsrv_t) -corenet_tcp_sendrecv_generic_if(dirsrv_t) -corenet_tcp_sendrecv_generic_node(dirsrv_t) -corenet_tcp_sendrecv_all_ports(dirsrv_t) -corenet_tcp_bind_all_nodes(dirsrv_t) -corenet_tcp_bind_ldap_port(dirsrv_t) -corenet_tcp_bind_all_rpc_ports(dirsrv_t) -corenet_udp_bind_all_rpc_ports(dirsrv_t) -corenet_tcp_connect_all_ports(dirsrv_t) -corenet_sendrecv_ldap_server_packets(dirsrv_t) -corenet_sendrecv_all_client_packets(dirsrv_t) -allow dirsrv_t self:tcp_socket { create_stream_socket_perms }; - -# Init script handling -init_use_fds(dirsrv_t) -init_use_script_ptys(dirsrv_t) -domain_use_interactive_fds(dirsrv_t) - - -######################################## -# -# dirsrv-snmp local policy -# - -# Some common macros -files_read_etc_files(dirsrv_snmp_t) -miscfiles_read_localization(dirsrv_snmp_t) -libs_use_ld_so(dirsrv_snmp_t) -libs_use_shared_libs(dirsrv_snmp_t) -dev_read_rand(dirsrv_snmp_t) -dev_read_urand(dirsrv_snmp_t) -files_read_usr_files(dirsrv_snmp_t) -fs_getattr_tmpfs(dirsrv_snmp_t) -fs_search_tmpfs(dirsrv_snmp_t) -allow dirsrv_snmp_t self:fifo_file { read write }; -sysnet_read_config(dirsrv_snmp_t) -sysnet_dns_name_resolve(dirsrv_snmp_t) - -# Net-SNMP /var/lib files (includes agentx unix domain socket) -snmp_dontaudit_read_snmp_var_lib_files(dirsrv_snmp_t) -snmp_dontaudit_write_snmp_var_lib_files(dirsrv_snmp_t) -# NGK - there really should be a macro for this. (see bz 523771) -allow dirsrv_snmp_t snmpd_var_lib_t:file append; -# NGK - use snmp_stream_connect(dirsrv_snmp_t) when it is made -# available on all platforms we build on (see bz 478629 and bz 523548) -stream_connect_pattern(dirsrv_snmp_t, snmpd_var_lib_t, snmpd_var_lib_t, snmpd_t) - -# Net-SNMP agentx tcp socket -corenet_tcp_connect_agentx_port(dirsrv_snmp_t) - -# Net-SNMP persistent data file -files_manage_var_files(dirsrv_snmp_t) - -# stats file semaphore -rw_files_pattern(dirsrv_snmp_t, dirsrv_tmpfs_t, dirsrv_tmpfs_t) - -# stats file -read_files_pattern(dirsrv_snmp_t, dirsrv_var_run_t, dirsrv_var_run_t) - -# process stuff -allow dirsrv_snmp_t self:capability { dac_override dac_read_search }; - -# config file -read_files_pattern(dirsrv_snmp_t, dirsrv_config_t, dirsrv_config_t) - -# pid file -manage_files_pattern(dirsrv_snmp_t, dirsrv_snmp_var_run_t, dirsrv_snmp_var_run_t) -files_pid_filetrans(dirsrv_snmp_t, dirsrv_snmp_var_run_t, { file sock_file }) -search_dirs_pattern(dirsrv_snmp_t, dirsrv_var_run_t, dirsrv_var_run_t) - -# log file -manage_files_pattern(dirsrv_snmp_t, dirsrv_var_log_t, dirsrv_snmp_var_log_t); -filetrans_pattern(dirsrv_snmp_t, dirsrv_var_log_t, dirsrv_snmp_var_log_t, file) - -# Init script handling -init_use_fds(dirsrv_snmp_t) -init_use_script_ptys(dirsrv_snmp_t) -domain_use_interactive_fds(dirsrv_snmp_t)
0
b573d80d9c3acc6dba1bd60bdf7bf3fe4f4168df
389ds/389-ds-base
Ticket #47410 - changelog db deadlocks with DNA and replication https://fedorahosted.org/389/ticket/47410 Reviewed by: mreynolds (Thanks!) Branch: master Fix Description: The deadlock is caused by having an outer and an inner transaction in one thread, and a replication reader in another thread. The outer transaction acquires a write lock on certain changelog db (cldb) pages as a result of a previous nested transaction (e.g. a DNA shared config area update). The changelog reader in the cursor positioning operation acquires read locks on certain other pages. When another inner write transaction occurs, it may attempt to acquire a write lock on a page held by a read lock in the reader thread. This will eventually fail because the reader will not release its lock on the page until the outer transaction releases the write lock on the page. The solution is to change the way the deadlock detection thread works, to use a different deadlock rejection policy. When using DB_LOCK_MINWRITE instead of the default DB_LOCK_YOUNGEST, the reader thread lock request is rejected. This means the code that positions the changelog cursor has to be able to handle a DB_LOCK_DEADLOCK return. Changing the deadlock rejection policy globally to DB_LOCK_MINWRITE has the potential to cause any search to get a DB_LOCK_DEADLOCK from a db or cursor get(), so this will need to be tested a great deal to make sure we can handle all such cases. Platforms tested: RHEL6 x86_64 Flag Day: no Doc impact: no
commit b573d80d9c3acc6dba1bd60bdf7bf3fe4f4168df Author: Rich Megginson <[email protected]> Date: Wed Jun 26 13:35:39 2013 -0600 Ticket #47410 - changelog db deadlocks with DNA and replication https://fedorahosted.org/389/ticket/47410 Reviewed by: mreynolds (Thanks!) Branch: master Fix Description: The deadlock is caused by having an outer and an inner transaction in one thread, and a replication reader in another thread. The outer transaction acquires a write lock on certain changelog db (cldb) pages as a result of a previous nested transaction (e.g. a DNA shared config area update). The changelog reader in the cursor positioning operation acquires read locks on certain other pages. When another inner write transaction occurs, it may attempt to acquire a write lock on a page held by a read lock in the reader thread. This will eventually fail because the reader will not release its lock on the page until the outer transaction releases the write lock on the page. The solution is to change the way the deadlock detection thread works, to use a different deadlock rejection policy. When using DB_LOCK_MINWRITE instead of the default DB_LOCK_YOUNGEST, the reader thread lock request is rejected. This means the code that positions the changelog cursor has to be able to handle a DB_LOCK_DEADLOCK return. Changing the deadlock rejection policy globally to DB_LOCK_MINWRITE has the potential to cause any search to get a DB_LOCK_DEADLOCK from a db or cursor get(), so this will need to be tested a great deal to make sure we can handle all such cases. Platforms tested: RHEL6 x86_64 Flag Day: no Doc impact: no diff --git a/ldap/servers/plugins/replication/cl5.h b/ldap/servers/plugins/replication/cl5.h index 4c92ecd2d..33f81403b 100644 --- a/ldap/servers/plugins/replication/cl5.h +++ b/ldap/servers/plugins/replication/cl5.h @@ -73,4 +73,6 @@ void changelog5_config_done (changelog5Config *config); /* frees the content and the config structure */ void changelog5_config_free (changelog5Config **config); +#define MAX_TRIALS 50 /* number of retries on db operations */ + #endif diff --git a/ldap/servers/plugins/replication/cl5_api.c b/ldap/servers/plugins/replication/cl5_api.c index b29fa2e4e..c76cac636 100644 --- a/ldap/servers/plugins/replication/cl5_api.c +++ b/ldap/servers/plugins/replication/cl5_api.c @@ -67,7 +67,6 @@ #define GUARDIAN_FILE "guardian" /* name of the guardian file */ #define VERSION_FILE "DBVERSION" /* name of the version file */ -#define MAX_TRIALS 50 /* number of retries on db operations */ #define V_5 5 /* changelog entry version */ #define CHUNK_SIZE 64*1024 #define DBID_SIZE 64 diff --git a/ldap/servers/plugins/replication/cl5_clcache.c b/ldap/servers/plugins/replication/cl5_clcache.c index 1c20b92d5..7a6a446a1 100644 --- a/ldap/servers/plugins/replication/cl5_clcache.c +++ b/ldap/servers/plugins/replication/cl5_clcache.c @@ -380,6 +380,7 @@ clcache_load_buffer_bulk ( CLC_Buffer *buf, int flag ) DB_TXN *txn = NULL; DBC *cursor = NULL; int rc = 0; + int tries = 0; #if 0 /* txn control seems not improving anything so turn it off */ if ( *(_pool->pl_dbenv) ) { @@ -401,6 +402,7 @@ clcache_load_buffer_bulk ( CLC_Buffer *buf, int flag ) } PR_Lock ( buf->buf_busy_list->bl_lock ); +retry: if ( 0 == ( rc = clcache_open_cursor ( txn, buf, &cursor )) ) { if ( flag == DB_NEXT ) { @@ -422,10 +424,26 @@ clcache_load_buffer_bulk ( CLC_Buffer *buf, int flag ) /* * Don't keep a cursor open across the whole replication session. - * That had caused noticable DB resource contention. + * That had caused noticeable DB resource contention. */ if ( cursor ) { cursor->c_close ( cursor ); + cursor = NULL; + } + if ((rc == DB_LOCK_DEADLOCK) && (tries < MAX_TRIALS)) { + PRIntervalTime interval; + + tries++; + slapi_log_error ( SLAPI_LOG_TRACE, "clcache_load_buffer_bulk", + "deadlock number [%d] - retrying\n", tries ); + /* back off */ + interval = PR_MillisecondsToInterval(slapi_rand() % 100); + DS_Sleep(interval); + goto retry; + } + if ((rc == DB_LOCK_DEADLOCK) && (tries >= MAX_TRIALS)) { + slapi_log_error ( SLAPI_LOG_REPL, "clcache_load_buffer_bulk", + "could not load buffer from changelog after %d tries\n", tries ); } #if 0 /* txn control seems not improving anything so turn it off */
0
2d65b2c45b1e1cb17342449128638dc7dbc07b7d
389ds/389-ds-base
Replace missing makefile referenced by SunOS5.8.mk and SunOS5.9.mk. This file is needed to build on Solaris.
commit 2d65b2c45b1e1cb17342449128638dc7dbc07b7d Author: Thomas Lackey <[email protected]> Date: Thu Feb 10 01:30:49 2005 +0000 Replace missing makefile referenced by SunOS5.8.mk and SunOS5.9.mk. This file is needed to build on Solaris. diff --git a/config/SunOS5.mk b/config/SunOS5.mk new file mode 100644 index 000000000..cff753614 --- /dev/null +++ b/config/SunOS5.mk @@ -0,0 +1,103 @@ +# +# BEGIN COPYRIGHT BLOCK +# Copyright 2001 Sun Microsystems, Inc. +# Portions copyright 1999, 2001-2003 Netscape Communications Corporation. +# All rights reserved. +# END COPYRIGHT BLOCK +# +# +# Config stuff for SunOS5.x +# + +ifdef NS_USE_NATIVE +CC = cc -DNS_USE_NATIVE +CCC = CC -DNS_USE_NATIVE +ASFLAGS += -Wa,-P +OS_CFLAGS = $(NOMD_OS_CFLAGS) +ifdef BUILD_OPT +OPTIMIZER = -xcg89 -dalign -xO2 +endif +else +CC = gcc -Wall -Wno-format +CCC = g++ -Wall -Wno-format +ASFLAGS += -x assembler-with-cpp +ifdef NO_MDUPDATE +OS_CFLAGS = $(NOMD_OS_CFLAGS) +else +OS_CFLAGS = $(NOMD_OS_CFLAGS) -MDupdate $(DEPENDENCIES) +endif +endif + +RANLIB = echo + +CPU_ARCH = sparc +GFX_ARCH = x + +MOZ_CFLAGS = -DSVR4 -DSYSV -DNSPR -D__svr4 -D__svr4__ -DSOLARIS -DHAVE_WEAK_IO_SYMBOLS + +ifeq ($(SERVER_BUILD),1) +USE_KERNEL_THREADS = 1 +endif + +ifeq ($(FORCE_SW_THREADS),1) +USE_KERNEL_THREADS = 0 +endif + +# Purify doesn't like -MDupdate +ifeq ($(USE_KERNEL_THREADS), 1) +ifdef NSPR20 +NOMD_OS_CFLAGS = $(MOZ_CFLAGS) -DNSPR20 -D_PR_NTHREAD -D_REENTRANT $(SOL_CFLAGS) +else +NOMD_OS_CFLAGS = $(MOZ_CFLAGS) -DHW_THREADS -D_REENTRANT $(SOL_CFLAGS) +endif +OS_LIBS = -lthread -lposix4 -lsocket -lnsl -ldl +else +NOMD_OS_CFLAGS = $(MOZ_CFLAGS) -DSW_THREADS $(SOL_CFLAGS) +OS_LIBS = -lsocket -lnsl -ldl -L/tools/ns/lib -lposix4 +endif + +ifeq ($(OS_RELEASE),5.3) +MOTIF = /usr/local/Motif/opt/ICS/Motif/usr +MOTIFLIB = $(MOTIF)/lib/libXm.a +else +MOTIF = /usr/dt +MOTIFLIB = -lXm +endif + +INCLUDES += -I$(MOTIF)/include -I/usr/openwin/include + +MKSHLIB = $(LD) $(DSO_LDOPTS) +#Livewire httpdlw.so is using CC to link. +LWMKSHLIB = $(CCC) $(DSO_LDOPTS) + +HAVE_PURIFY = 1 + +NOSUCHFILE = /solaris-rm-f-sucks + +LOCALE_MAP = $(DEPTH)/cmd/xfe/intl/sunos.lm + +EN_LOCALE = en_US +DE_LOCALE = de +FR_LOCALE = fr +JP_LOCALE = ja +SJIS_LOCALE = ja_JP.SJIS +KR_LOCALE = ko +CN_LOCALE = zh +TW_LOCALE = zh_TW +I2_LOCALE = i2 +IT_LOCALE = it +SV_LOCALE = sv +ES_LOCALE = es +NL_LOCALE = nl +PT_LOCALE = pt + +LOC_LIB_DIR = /usr/openwin/lib/locale + +BSDECHO = /usr/ucb/echo + +# +# These defines are for building unix plugins +# +BUILD_UNIX_PLUGINS = 1 +DSO_LDOPTS = -G -L$(MOTIF)/lib -L/usr/openwin/lib +DSO_LDFLAGS =
0
20da3624e58c848a9f3621b7c928f19d533aad2e
389ds/389-ds-base
Ticket #513 - recycle operation pblocks https://fedorahosted.org/389/ticket/513 Reviewed by: nhosoi,mreynolds (Thanks!) Branch: master Fix Description: Instead of doing a malloc/free of a Slapi_PBlock for every operation, just use a local stack variable Slapi_PBlock in each worker thread stack. The only tricky thing there is that persistent search threads must make a copy of the pblock - they make a shallow copy, so we can't use slapi_pblock_init in that case, just use memset 0. For the work_q objects, reuse them by storing unused ones on a PRStack to avoid malloc/free of those. Only malloc a new one when the stack is empty. Try to reuse Slapi_Operation objects as much as possible by storing unused ones on a PRStack - only malloc a new one when the stack is empty. Platforms tested: RHEL6 x86_64 Flag Day: no Doc impact: Yes
commit 20da3624e58c848a9f3621b7c928f19d533aad2e Author: Rich Megginson <[email protected]> Date: Thu Mar 7 21:10:38 2013 -0700 Ticket #513 - recycle operation pblocks https://fedorahosted.org/389/ticket/513 Reviewed by: nhosoi,mreynolds (Thanks!) Branch: master Fix Description: Instead of doing a malloc/free of a Slapi_PBlock for every operation, just use a local stack variable Slapi_PBlock in each worker thread stack. The only tricky thing there is that persistent search threads must make a copy of the pblock - they make a shallow copy, so we can't use slapi_pblock_init in that case, just use memset 0. For the work_q objects, reuse them by storing unused ones on a PRStack to avoid malloc/free of those. Only malloc a new one when the stack is empty. Try to reuse Slapi_Operation objects as much as possible by storing unused ones on a PRStack - only malloc a new one when the stack is empty. Platforms tested: RHEL6 x86_64 Flag Day: no Doc impact: Yes diff --git a/ldap/servers/slapd/connection.c b/ldap/servers/slapd/connection.c index c68f56b42..0aec12ec7 100644 --- a/ldap/servers/slapd/connection.c +++ b/ldap/servers/slapd/connection.c @@ -58,10 +58,8 @@ #include <netinet/tcp.h> /* for TCP_CORK */ #endif - +typedef Connection work_q_item; static void connection_threadmain( void ); -static void add_pb( Slapi_PBlock * ); -static Slapi_PBlock *get_pb( void ); static void connection_add_operation(Connection* conn, Operation *op); static void connection_free_private_buffer(Connection *conn); static void op_copy_identity(Connection *conn, Operation *op); @@ -70,28 +68,89 @@ static int is_ber_too_big(const Connection *conn, ber_len_t ber_len); static void log_ber_too_big_error(const Connection *conn, ber_len_t ber_len, ber_len_t maxbersize); +static PRStack *op_stack; /* stack of Slapi_Operation * objects so we don't have to malloc/free every time */ +static PRInt32 op_stack_size; /* size of op_stack */ + +struct Slapi_op_stack { + PRStackElem stackelem; /* must be first in struct for PRStack to work */ + Slapi_Operation *op; +}; + +static void add_work_q( work_q_item *, struct Slapi_op_stack * ); +static work_q_item *get_work_q( struct Slapi_op_stack ** ); + /* - * We maintain a global work queue of Slapi_PBlock's that have not yet + * We maintain a global work queue of items that have not yet * been handed off to an operation thread. */ -struct Slapi_PBlock_q -{ - Slapi_PBlock *pb; - struct Slapi_PBlock_q *next_pb; - int pb_fd; +struct Slapi_work_q { + PRStackElem stackelem; /* must be first in struct for PRStack to work */ + work_q_item *work_item; + struct Slapi_op_stack *op_stack_obj; + struct Slapi_work_q *next_work_item; }; -static struct Slapi_PBlock_q *first_pb= NULL; /* global work queue head */ -static struct Slapi_PBlock_q *last_pb= NULL; /* global work queue tail */ -static PRLock *pb_q_lock=NULL; /* protects first_pb & last_pb */ -static PRCondVar *pb_q_cv; /* used by operation threads to wait for work - when there is a op pblock in the queue waiting to be processed */ -static PRInt32 pb_q_size; /* size of pb_q */ -static PRInt32 pb_q_size_max; /* high water mark of pb_q_size */ -#define PB_Q_EMPTY (pb_q_size == 0) +static struct Slapi_work_q *head_work_q= NULL; /* global work queue head */ +static struct Slapi_work_q *tail_work_q= NULL; /* global work queue tail */ +static PRLock *work_q_lock=NULL; /* protects head_conn_q and tail_conn_q */ +static PRCondVar *work_q_cv; /* used by operation threads to wait for work - when there is a conn in the queue waiting to be processed */ +static PRInt32 work_q_size; /* size of conn_q */ +static PRInt32 work_q_size_max; /* high water mark of work_q_size */ +#define WORK_Q_EMPTY (work_q_size == 0) +static PRStack *work_q_stack; /* stack of work_q structs so we don't have to malloc/free every time */ +static PRInt32 work_q_stack_size; /* size of work_q_stack */ +static PRInt32 work_q_stack_size_max; /* max size of work_q_stack */ static PRInt32 op_shutdown= 0; /* if non-zero, server is shutting down */ #define LDAP_SOCKET_IO_BUFFER_SIZE 512 /* Size of the buffer we give to the I/O system for reads */ +static struct Slapi_work_q * +create_work_q() +{ + struct Slapi_work_q *work_q = (struct Slapi_work_q *)PR_StackPop(work_q_stack); + if (!work_q) { + work_q = (struct Slapi_work_q *)slapi_ch_malloc(sizeof(struct Slapi_work_q)); + } else { + PR_AtomicDecrement(&work_q_stack_size); + } + return work_q; +} + +static void +destroy_work_q(struct Slapi_work_q **work_q) +{ + if (work_q && *work_q) { + PR_StackPush(work_q_stack, (PRStackElem *)*work_q); + PR_AtomicIncrement(&work_q_stack_size); + if (work_q_stack_size > work_q_stack_size_max) { + work_q_stack_size_max = work_q_stack_size; + } + } +} + +static struct Slapi_op_stack * +connection_get_operation(void) +{ + struct Slapi_op_stack *stack_obj = (struct Slapi_op_stack *)PR_StackPop(op_stack); + if (!stack_obj) { + stack_obj = (struct Slapi_op_stack *)slapi_ch_malloc(sizeof(struct Slapi_op_stack)); + stack_obj->op = operation_new( plugin_build_operation_action_bitmap( 0, + plugin_get_server_plg() )); + } else { + PR_AtomicDecrement(&op_stack_size); + operation_init(stack_obj->op, + plugin_build_operation_action_bitmap( 0, plugin_get_server_plg() )); + } + return stack_obj; +} + +static void +connection_done_operation(Connection *conn, struct Slapi_op_stack *stack_obj) +{ + operation_done(&(stack_obj->op), conn); + PR_StackPush(op_stack, (PRStackElem *)stack_obj); + PR_AtomicIncrement(&op_stack_size); +} /* * We really are done with this connection. Get rid of everything. @@ -404,21 +463,25 @@ init_op_threads() int max_threads = config_get_threadnumber(); /* Initialize the locks and cv */ - if ((pb_q_lock = PR_NewLock()) == NULL ) { + if ((work_q_lock = PR_NewLock()) == NULL ) { errorCode = PR_GetError(); LDAPDebug( LDAP_DEBUG_ANY, - "init_op_threads: PR_NewLock failed for pb_q_lock, " SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n", + "init_op_threads: PR_NewLock failed for work_q_lock, " SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n", errorCode, slapd_pr_strerror(errorCode), 0 ); exit(-1); } - if ((pb_q_cv = PR_NewCondVar( pb_q_lock )) == NULL) { + if ((work_q_cv = PR_NewCondVar( work_q_lock )) == NULL) { errorCode = PR_GetError(); - LDAPDebug( LDAP_DEBUG_ANY, "init_op_threads: PR_NewCondVar failed for pb_q_cv, " SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n", + LDAPDebug( LDAP_DEBUG_ANY, "init_op_threads: PR_NewCondVar failed for work_q_cv, " SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n", errorCode, slapd_pr_strerror(errorCode), 0 ); exit(-1); } + work_q_stack = PR_CreateStack("connection_work_q"); + + op_stack = PR_CreateStack("connection_operation"); + /* start the operation threads */ for (i=0; i < max_threads; i++) { PR_SetConcurrency(4); @@ -1678,7 +1741,7 @@ connection_free_private_buffer(Connection *conn) /* Connection status values returned by - connection_wait_for_new_pb(), connection_read_operation(), etc. */ + connection_wait_for_new_work(), connection_read_operation(), etc. */ #define CONN_FOUND_WORK_TO_DO 0 #define CONN_SHUTDOWN 1 @@ -1691,43 +1754,51 @@ connection_free_private_buffer(Connection *conn) #define CONN_TURBO_PERCENTILE 50 /* proportion of threads allowed to be in turbo mode */ #define CONN_TURBO_HYSTERESIS 0 /* avoid flip flopping in and out of turbo mode */ -int connection_wait_for_new_pb(Slapi_PBlock **ppb, PRIntervalTime interval) +void connection_make_new_pb(Slapi_PBlock *pb, Connection *conn) +{ + struct Slapi_op_stack *stack_obj = NULL; + /* we used to malloc/free the pb for each operation - now, just use a local stack pb + * in connection_threadmain, and just clear it out + */ + /* *ppb = (Slapi_PBlock *) slapi_ch_calloc( 1, sizeof(Slapi_PBlock) ); */ + /* *ppb = slapi_pblock_new(); */ + pb->pb_conn = conn; + stack_obj = connection_get_operation(); + pb->pb_op = stack_obj->op; + pb->op_stack_elem = stack_obj; + connection_add_operation( conn, pb->pb_op ); +} + +int connection_wait_for_new_work(Slapi_PBlock *pb, PRIntervalTime interval) { int ret = CONN_FOUND_WORK_TO_DO; + work_q_item *wqitem = NULL; + struct Slapi_op_stack *op_stack_obj = NULL; - PR_Lock( pb_q_lock ); + PR_Lock( work_q_lock ); - while( !op_shutdown && PB_Q_EMPTY ) { - PR_WaitCondVar( pb_q_cv, interval ); + while( !op_shutdown && WORK_Q_EMPTY ) { + PR_WaitCondVar( work_q_cv, interval ); } if ( op_shutdown ) { - LDAPDebug0Args( LDAP_DEBUG_ANY, "connection_wait_for_new_pb: shutdown\n" ); + LDAPDebug0Args( LDAP_DEBUG_TRACE, "connection_wait_for_new_work: shutdown\n" ); ret = CONN_SHUTDOWN; - } else if ( NULL == ( *ppb = get_pb() ) ) { + } else if ( NULL == ( wqitem = get_work_q( &op_stack_obj ) ) ) { /* not sure how this can happen */ - LDAPDebug0Args( LDAP_DEBUG_ANY, "connection_wait_for_new_pb: pb is null\n" ); + LDAPDebug0Args( LDAP_DEBUG_TRACE, "connection_wait_for_new_work: no work to do\n" ); ret = CONN_NOWORK; + } else { + /* make new pb */ + pb->pb_conn = (Connection *)wqitem; + pb->op_stack_elem = op_stack_obj; + pb->pb_op = op_stack_obj->op; } - PR_Unlock( pb_q_lock ); + PR_Unlock( work_q_lock ); return ret; } -void connection_make_new_pb(Slapi_PBlock **ppb, Connection *conn) -{ - /* In the classic case, the pb is made in connection_activity() and then - queued. get_pb() dequeues it. So we can just make it ourselves here */ - - /* *ppb = (Slapi_PBlock *) slapi_ch_calloc( 1, sizeof(Slapi_PBlock) ); */ - *ppb = slapi_pblock_new(); - (*ppb)->pb_conn = conn; - (*ppb)->pb_op = operation_new( plugin_build_operation_action_bitmap( 0, - plugin_get_server_plg() )); - connection_add_operation( conn, (*ppb)->pb_op ); -} - - /* * Utility function called by connection_read_operation(). This is a * small wrapper on top of libldap's ber_get_next_buffer_ext(). @@ -2145,7 +2216,8 @@ void connection_enter_leave_turbo(Connection *conn, int current_turbo_flag, int static void connection_threadmain() { - Slapi_PBlock *pb = NULL; + Slapi_PBlock local_pb; + Slapi_PBlock *pb = &local_pb; /* wait forever for new pb until one is available or shutdown */ PRIntervalTime interval = PR_INTERVAL_NO_TIMEOUT; /* PR_SecondsToInterval(10); */ Connection *conn = NULL; @@ -2163,6 +2235,7 @@ connection_threadmain() SIGNAL( SIGPIPE, SIG_IGN ); #endif + pblock_init(pb); while (1) { int is_timedout = 0; time_t curtime = 0; @@ -2174,12 +2247,12 @@ connection_threadmain() return; } - if (!thread_turbo_flag && (NULL == pb) && !more_data) { + if (!thread_turbo_flag && !more_data) { /* If more data is left from the previous connection_read_operation, we should finish the op now. Client might be thinking it's done sending the request and wait for the response forever. [blackflag 624234] */ - ret = connection_wait_for_new_pb(&pb,interval); + ret = connection_wait_for_new_work(pb,interval); switch (ret) { case CONN_NOWORK: PR_ASSERT(interval != PR_INTERVAL_NO_TIMEOUT); /* this should never happen with PR_INTERVAL_NO_TIMEOUT */ @@ -2201,7 +2274,7 @@ connection_threadmain() default: break; } - } else if (NULL == pb) { + } else { /* The turbo mode may cause threads starvation. Do a yield here to reduce the starving @@ -2210,7 +2283,7 @@ connection_threadmain() PR_Lock(conn->c_mutex); /* Make our own pb in turbo mode */ - connection_make_new_pb(&pb,conn); + connection_make_new_pb(pb,conn); if (connection_call_io_layer_callbacks(conn)) { LDAPDebug0Args( LDAP_DEBUG_ANY, "Error: could not add/remove IO layers from connection\n" ); } @@ -2245,9 +2318,9 @@ connection_threadmain() } /* turn off turbo mode immediately if any pb waiting in global queue */ - if (thread_turbo_flag && !PB_Q_EMPTY) { + if (thread_turbo_flag && !WORK_Q_EMPTY) { thread_turbo_flag = 0; - LDAPDebug2Args(LDAP_DEBUG_CONNS,"conn %" NSPRIu64 " leaving turbo mode - pb_q is not empty %d\n",conn->c_connid,pb_q_size); + LDAPDebug2Args(LDAP_DEBUG_CONNS,"conn %" NSPRIu64 " leaving turbo mode - pb_q is not empty %d\n",conn->c_connid,work_q_size); } #endif @@ -2333,12 +2406,7 @@ connection_threadmain() done: if (doshutdown) { PR_Lock(conn->c_mutex); - connection_remove_operation( conn, op ); - /* destroying the pblock will cause destruction of the operation - * so this must happend before releasing the connection - */ - slapi_pblock_destroy( pb ); - pb = NULL; + connection_remove_operation_ext(pb, conn, op); connection_make_readable_nolock(conn); conn->c_threadnumber--; connection_release_nolock(conn); @@ -2362,14 +2430,15 @@ done: PR_Lock( conn->c_mutex ); connection_release_nolock (conn); /* psearch acquires ref to conn - release this one now */ PR_Unlock( conn->c_mutex ); + /* ps_add makes a shallow copy of the pb - so we + * can't free it or init it here - just memset it to 0 + * ps_send_results will call connection_remove_operation_ext to free it + */ + memset(pb, 0, sizeof(*pb)); } else { /* delete from connection operation queue & decr refcnt */ PR_Lock( conn->c_mutex ); - connection_remove_operation( conn, op ); - /* destroying the pblock will cause destruction of the operation - * so this must happend before releasing the connection - */ - slapi_pblock_destroy( pb ); + connection_remove_operation_ext( pb, conn, op ); /* If we're in turbo mode, we keep our reference to the connection alive */ if (!more_data) { @@ -2402,7 +2471,6 @@ done: } PR_Unlock( conn->c_mutex ); } - pb = NULL; } /* while (1) */ } @@ -2410,7 +2478,7 @@ done: int connection_activity(Connection *conn) { - Slapi_PBlock *pb; + struct Slapi_op_stack *op_stack_obj; if (connection_acquire_nolock (conn) == -1) { LDAPDebug(LDAP_DEBUG_CONNS, @@ -2421,14 +2489,14 @@ connection_activity(Connection *conn) return (-1); } - connection_make_new_pb(&pb, conn); - /* set these here so setup_pr_read_pds will not add this conn back to the poll array */ conn->c_gettingber = 1; conn->c_threadnumber++; - /* Add pb to the end of the work queue. */ - /* have to do this last - add_pb will signal waiters in connection_wait_for_new_pb */ - add_pb( pb ); + op_stack_obj = connection_get_operation(); + connection_add_operation(conn, op_stack_obj->op); + /* Add conn to the end of the work queue. */ + /* have to do this last - add_work_q will signal waiters in connection_wait_for_new_work */ + add_work_q( (work_q_item *)conn, op_stack_obj ); if (! config_check_referral_mode()) { slapi_counter_increment(ops_initiated); @@ -2437,65 +2505,67 @@ connection_activity(Connection *conn) return 0; } -/* add_pb(): will add a pb to the end of the global work queue. The work queue - is implemented as a singal link list. */ +/* add_work_q(): will add a work_q_item to the end of the global work queue. The work queue + is implemented as a single link list. */ static void -add_pb( Slapi_PBlock *pb) +add_work_q( work_q_item *wqitem, struct Slapi_op_stack *op_stack_obj ) { - struct Slapi_PBlock_q *new_pb=NULL; + struct Slapi_work_q *new_work_q=NULL; - LDAPDebug( LDAP_DEBUG_TRACE, "add_pb \n", 0, 0, 0 ); + LDAPDebug( LDAP_DEBUG_TRACE, "add_work_q \n", 0, 0, 0 ); - new_pb = (struct Slapi_PBlock_q *) slapi_ch_malloc ( sizeof( struct Slapi_PBlock_q )); - new_pb->pb = pb; - new_pb->next_pb =NULL; + new_work_q = create_work_q(); + new_work_q->work_item = wqitem; + new_work_q->op_stack_obj = op_stack_obj; + new_work_q->next_work_item =NULL; - PR_Lock( pb_q_lock ); - if (last_pb == NULL) { - last_pb = new_pb; - first_pb = new_pb; + PR_Lock( work_q_lock ); + if (tail_work_q == NULL) { + tail_work_q = new_work_q; + head_work_q = new_work_q; } else { - last_pb->next_pb = new_pb; - last_pb = new_pb; + tail_work_q->next_work_item = new_work_q; + tail_work_q = new_work_q; } - PR_AtomicIncrement( &pb_q_size ); /* increment q size */ - if ( pb_q_size > pb_q_size_max ) { - pb_q_size_max = pb_q_size; + PR_AtomicIncrement( &work_q_size ); /* increment q size */ + if ( work_q_size > work_q_size_max ) { + work_q_size_max = work_q_size; } - PR_NotifyCondVar( pb_q_cv ); /* notify waiters in connection_wait_for_new_pb */ - PR_Unlock( pb_q_lock ); + PR_NotifyCondVar( work_q_cv ); /* notify waiters in connection_wait_for_new_work */ + PR_Unlock( work_q_lock ); } -/* get_pb(): will get a pb from the beginning of the work queue, return NULL if - the queue is empty. This should only be called from connection_wait_for_new_pb - with the pb_q_lock held */ +/* get_work_q(): will get a work_q_item from the beginning of the work queue, return NULL if + the queue is empty. This should only be called from connection_wait_for_new_work + with the work_q_lock held */ -static Slapi_PBlock * -get_pb() +static work_q_item * +get_work_q(struct Slapi_op_stack **op_stack_obj) { - struct Slapi_PBlock_q *tmp = NULL; - Slapi_PBlock *pb; + struct Slapi_work_q *tmp = NULL; + work_q_item *wqitem; - LDAPDebug0Args( LDAP_DEBUG_TRACE, "get_pb \n" ); - if (first_pb == NULL) { - LDAPDebug0Args( LDAP_DEBUG_TRACE, "get_pb: the work queue is empty.\n" ); + LDAPDebug0Args( LDAP_DEBUG_TRACE, "get_work_q \n" ); + if (head_work_q == NULL) { + LDAPDebug0Args( LDAP_DEBUG_TRACE, "get_work_q: the work queue is empty.\n" ); return NULL; } - tmp = first_pb; - if ( first_pb == last_pb ) { - last_pb = NULL; + tmp = head_work_q; + if ( head_work_q == tail_work_q ) { + tail_work_q = NULL; } - first_pb = tmp->next_pb; + head_work_q = tmp->next_work_item; - pb = tmp->pb; - /* Free the memory used by the pb found. */ - slapi_ch_free ((void **)&tmp); - PR_AtomicDecrement( &pb_q_size ); /* decrement q size */ + wqitem = tmp->work_item; + *op_stack_obj = tmp->op_stack_obj; + PR_AtomicDecrement( &work_q_size ); /* decrement q size */ + /* Free the memory used by the item found. */ + destroy_work_q(&tmp); - return (pb); + return (wqitem); } #endif /* LDAP_IOCP */ @@ -2519,9 +2589,9 @@ op_thread_cleanup() "slapd shutting down - signaling operation threads\n", 0, 0, 0); PR_AtomicIncrement(&op_shutdown); - PR_Lock( pb_q_lock ); - PR_NotifyAllCondVar ( pb_q_cv ); /* tell any thread waiting in connection_wait_for_new_pb to shutdown */ - PR_Unlock( pb_q_lock ); + PR_Lock( work_q_lock ); + PR_NotifyAllCondVar ( work_q_cv ); /* tell any thread waiting in connection_wait_for_new_work to shutdown */ + PR_Unlock( work_q_lock ); #ifdef _WIN32 LDAPDebug( LDAP_DEBUG_ANY, "slapd shutting down - waiting for %d threads to terminate\n", @@ -2579,6 +2649,14 @@ connection_remove_operation( Connection *conn, Operation *op ) } } +void +connection_remove_operation_ext( Slapi_PBlock *pb, Connection *conn, Operation *op ) +{ + connection_remove_operation(conn, op); + connection_done_operation(conn, pb->op_stack_elem); + pb->pb_op = NULL; + slapi_pblock_init(pb); +} /* * Return a non-zero value if any operations are pending on conn. diff --git a/ldap/servers/slapd/daemon.c b/ldap/servers/slapd/daemon.c index fa1931291..962699acb 100644 --- a/ldap/servers/slapd/daemon.c +++ b/ldap/servers/slapd/daemon.c @@ -1784,7 +1784,7 @@ daemon_register_reslimits( void ) static int compute_idletimeout( slapdFrontendConfig_t *fecfg, Connection *conn ) { - int idletimeout; + int idletimeout = 0; if ( slapi_reslimit_get_integer_limit( conn, idletimeout_reslimit_handle, &idletimeout ) != SLAPI_RESLIMIT_STATUS_SUCCESS ) { diff --git a/ldap/servers/slapd/fe.h b/ldap/servers/slapd/fe.h index d21d10808..4581f664e 100644 --- a/ldap/servers/slapd/fe.h +++ b/ldap/servers/slapd/fe.h @@ -111,6 +111,7 @@ int connection_activity( Connection *conn ); void init_op_threads(); int connection_new_private(Connection *conn); void connection_remove_operation( Connection *conn, Operation *op ); +void connection_remove_operation_ext( Slapi_PBlock *pb, Connection *conn, Operation *op ); int connection_operations_pending( Connection *conn, Operation *op2ignore, int test_resultsent ); void connection_done(Connection *conn); diff --git a/ldap/servers/slapd/operation.c b/ldap/servers/slapd/operation.c index 743b9ce4f..e47e4de79 100644 --- a/ldap/servers/slapd/operation.c +++ b/ldap/servers/slapd/operation.c @@ -161,6 +161,34 @@ ber_special_free(void* buf, BerElement *ber) } #endif +void +operation_init(Slapi_Operation *o, int flags) +{ + if (NULL != o) + { + BerElement *ber = o->o_ber; /* may have already been set */ + memset(o,0,sizeof(Slapi_Operation)); + o->o_ber = ber; + o->o_msgid = -1; + o->o_tag = LBER_DEFAULT; + o->o_status = SLAPI_OP_STATUS_PROCESSING; + slapi_sdn_init(&(o->o_sdn)); + o->o_authtype = NULL; + o->o_isroot = 0; + o->o_time = current_time(); + o->o_opid = 0; + o->o_connid = 0; + o->o_next = NULL; + o->o_flags= flags; + if ( config_get_accesslog_level() & LDAP_DEBUG_TIMING ) { + o->o_interval = PR_IntervalNow(); + } else { + o->o_interval = (PRIntervalTime)0; + } + } + +} + /* * Allocate a new Slapi_Operation. * The flag parameter indicates whether the the operation is @@ -175,8 +203,8 @@ operation_new(int flags) * not to free the Operation separately, and the ber software knows * not to free the buffer separately. */ - BerElement *ber = NULL; Slapi_Operation *o; + BerElement *ber = NULL; if(flags & OP_FLAG_INTERNAL) { o = (Slapi_Operation *) slapi_ch_malloc(sizeof(Slapi_Operation)); @@ -187,35 +215,20 @@ operation_new(int flags) } if (NULL != o) { - memset(o,0,sizeof(Slapi_Operation)); - o->o_ber = ber; - o->o_msgid = -1; - o->o_tag = LBER_DEFAULT; - o->o_status = SLAPI_OP_STATUS_PROCESSING; - slapi_sdn_init(&(o->o_sdn)); - o->o_authtype = NULL; - o->o_isroot = 0; - o->o_time = current_time(); - o->o_opid = 0; - o->o_connid = 0; - o->o_next = NULL; - o->o_flags= flags; - if ( config_get_accesslog_level() & LDAP_DEBUG_TIMING ) { - o->o_interval = PR_IntervalNow(); - } else { - o->o_interval = (PRIntervalTime)0; - } + o->o_ber = ber; + operation_init(o, flags); } return o; } void -operation_free( Slapi_Operation **op, Connection *conn ) +operation_done( Slapi_Operation **op, Connection *conn ) { if(op!=NULL && *op!=NULL) { + int options = 0; /* Call the plugin extension destructors */ - factory_destroy_extension(get_operation_object_type(),*op,conn,&((*op)->o_extension)); + factory_destroy_extension(get_operation_object_type(),*op,conn,&((*op)->o_extension)); slapi_sdn_done(&(*op)->o_sdn); slapi_sdn_free(&(*op)->o_target_spec); slapi_ch_free_string( &(*op)->o_authtype ); @@ -229,6 +242,28 @@ operation_free( Slapi_Operation **op, Connection *conn ) ldap_controls_free( (*op)->o_results.result_controls ); } slapi_ch_free_string(&(*op)->o_results.result_matched); +#if defined(USE_OPENLDAP) + /* save the old options */ + if ((*op)->o_ber) { + ber_get_option((*op)->o_ber, LBER_OPT_BER_OPTIONS, &options); + /* we don't have a way to reuse the BerElement buffer so just free it */ + ber_free_buf((*op)->o_ber); + /* clear out the ber for the next operation */ + ber_init2((*op)->o_ber, NULL, options); + } +#else + ber_special_free(*op, (*op)->o_ber); /* have to free everything here */ + *op = NULL; +#endif + } +} + +void +operation_free( Slapi_Operation **op, Connection *conn ) +{ + operation_done(op, conn); + if(op!=NULL && *op!=NULL) + { if(operation_is_flag_set(*op, OP_FLAG_INTERNAL)) { slapi_ch_free((void**)op); diff --git a/ldap/servers/slapd/proto-slap.h b/ldap/servers/slapd/proto-slap.h index a34136f76..329aa6d45 100644 --- a/ldap/servers/slapd/proto-slap.h +++ b/ldap/servers/slapd/proto-slap.h @@ -829,7 +829,9 @@ char *slapd_get_version_value( void ); /* * operation.c */ +void operation_init(Slapi_Operation *op, int flags); Slapi_Operation *operation_new(int flags); +void operation_done( Slapi_Operation **op, Connection *conn ); void operation_free( Slapi_Operation **op, Connection *conn ); int slapi_op_abandoned( Slapi_PBlock *pb ); void operation_out_of_disk_space(); diff --git a/ldap/servers/slapd/psearch.c b/ldap/servers/slapd/psearch.c index b5b4c3aab..45820397b 100644 --- a/ldap/servers/slapd/psearch.c +++ b/ldap/servers/slapd/psearch.c @@ -171,8 +171,13 @@ ps_stop_psearch_system() } } - - +static Slapi_PBlock * +pblock_copy(Slapi_PBlock *src) +{ + Slapi_PBlock *dest = slapi_pblock_new(); + *dest = *src; + return dest; +} /* * Add the given pblock to the list of outstanding persistent searches. @@ -187,7 +192,7 @@ ps_add( Slapi_PBlock *pb, ber_int_t changetypes, int send_entchg_controls ) if ( PS_IS_INITIALIZED() && NULL != pb ) { /* Create the new node */ ps = psearch_alloc(); - ps->ps_pblock = pb; + ps->ps_pblock = pblock_copy(pb); ps->ps_changetypes = changetypes; ps->ps_send_entchg_controls = send_entchg_controls; @@ -295,6 +300,7 @@ ps_send_results( void *arg ) char *fstr = NULL; char **pbattrs = NULL; int conn_acq_flag = 0; + Slapi_Connection *conn = NULL; g_incr_active_threadcnt(); @@ -418,22 +424,22 @@ ps_send_results( void *arg ) slapi_pblock_set(ps->ps_pblock, SLAPI_SEARCH_FILTER, NULL ); slapi_filter_free(filter, 1); + conn = ps->ps_pblock->pb_conn; /* save to release later - connection_remove_operation_ext will NULL the pb_conn */ /* Clean up the connection structure */ - PR_Lock( ps->ps_pblock->pb_conn->c_mutex ); + PR_Lock( conn->c_mutex ); slapi_log_error(SLAPI_LOG_CONNS, "Persistent Search", "conn=%" NSPRIu64 " op=%d Releasing the connection and operation\n", - ps->ps_pblock->pb_conn->c_connid, ps->ps_pblock->pb_op->o_opid); + conn->c_connid, ps->ps_pblock->pb_op->o_opid); /* Delete this op from the connection's list */ - connection_remove_operation( ps->ps_pblock->pb_conn, ps->ps_pblock->pb_op ); - operation_free(&(ps->ps_pblock->pb_op),ps->ps_pblock->pb_conn); - ps->ps_pblock->pb_op=NULL; + connection_remove_operation_ext( ps->ps_pblock, conn, ps->ps_pblock->pb_op ); /* Decrement the connection refcnt */ if (conn_acq_flag == 0) { /* we acquired it, so release it */ - connection_release_nolock (ps->ps_pblock->pb_conn); + connection_release_nolock (conn); } - PR_Unlock( ps->ps_pblock->pb_conn->c_mutex ); + PR_Unlock( conn->c_mutex ); + conn = NULL; PR_DestroyLock ( ps->ps_lock ); ps->ps_lock = NULL; diff --git a/ldap/servers/slapd/slap.h b/ldap/servers/slapd/slap.h index c8381da7c..74900ee25 100644 --- a/ldap/servers/slapd/slap.h +++ b/ldap/servers/slapd/slap.h @@ -1719,6 +1719,7 @@ typedef struct slapi_pblock { void *pb_syntax_filter_data; /* extra data to pass to a syntax plugin function */ int pb_paged_results_index; /* stash SLAPI_PAGED_RESULTS_INDEX */ passwdPolicy *pwdpolicy; + void *op_stack_elem; } slapi_pblock; /* index if substrlens */
0
4bf28a5ed99b44d1e93221c66988b2cb3b588d09
389ds/389-ds-base
Resolves: bug 481223 Bug Description: Removing Group Member in ADS and Send and Receive Updates Crashes the Directory Server Reviewed by: nkinder (Thanks!) Fix Description: I broke this with my earlier fix about sending mods to AD. There are calls which reset the raw entry from AD before the call to mod_already_made. The fix is to only retrieve the raw entry just before we use it, after it may have been reset. I also found a memory leak in the mod init with valueset function I added for the prior fix. Platforms tested: RHEL5 Flag Day: no Doc impact: no
commit 4bf28a5ed99b44d1e93221c66988b2cb3b588d09 Author: Rich Megginson <[email protected]> Date: Mon Jan 26 17:35:15 2009 +0000 Resolves: bug 481223 Bug Description: Removing Group Member in ADS and Send and Receive Updates Crashes the Directory Server Reviewed by: nkinder (Thanks!) Fix Description: I broke this with my earlier fix about sending mods to AD. There are calls which reset the raw entry from AD before the call to mod_already_made. The fix is to only retrieve the raw entry just before we use it, after it may have been reset. I also found a memory leak in the mod init with valueset function I added for the prior fix. Platforms tested: RHEL5 Flag Day: no Doc impact: no diff --git a/ldap/servers/plugins/replication/windows_protocol_util.c b/ldap/servers/plugins/replication/windows_protocol_util.c index 7cdf3d839..7e00e106b 100644 --- a/ldap/servers/plugins/replication/windows_protocol_util.c +++ b/ldap/servers/plugins/replication/windows_protocol_util.c @@ -62,7 +62,7 @@ int ruv_private_new( RUV **ruv, RUV *clone ); static Slapi_Entry* windows_entry_already_exists(Slapi_Entry *e); static void extract_guid_from_entry_bv(Slapi_Entry *e, const struct berval **bv); #endif -static void windows_map_mods_for_replay(Private_Repl_Protocol *prp,LDAPMod **original_mods, LDAPMod ***returned_mods, int is_user, char** password, const Slapi_Entry *ad_entry); +static void windows_map_mods_for_replay(Private_Repl_Protocol *prp,LDAPMod **original_mods, LDAPMod ***returned_mods, int is_user, char** password); static int is_subject_of_agreement_local(const Slapi_Entry *local_entry,const Repl_Agmt *ra); static int windows_create_remote_entry(Private_Repl_Protocol *prp,Slapi_Entry *original_entry, Slapi_DN *remote_sdn, Slapi_Entry **remote_entry, char** password); static int windows_get_local_entry(const Slapi_DN* local_dn,Slapi_Entry **local_entry); @@ -1290,8 +1290,7 @@ windows_replay_update(Private_Repl_Protocol *prp, slapi_operation_parameters *op } - windows_map_mods_for_replay(prp,op->p.p_modify.modify_mods, &mapped_mods, is_user, &password, - windows_private_get_raw_entry(prp->agmt)); + windows_map_mods_for_replay(prp,op->p.p_modify.modify_mods, &mapped_mods, is_user, &password); if (is_user) { winsync_plugin_call_pre_ad_mod_user_mods_cb(prp->agmt, windows_private_get_raw_entry(prp->agmt), @@ -1803,11 +1802,12 @@ windows_delete_local_entry(Slapi_DN *sdn){ error message to that effect. */ static int -mod_already_made(Private_Repl_Protocol *prp, Slapi_Mod *smod, const Slapi_Entry *ad_entry) +mod_already_made(Private_Repl_Protocol *prp, Slapi_Mod *smod) { int retval = 0; int op = 0; const char *type = NULL; + const Slapi_Entry *ad_entry = windows_private_get_raw_entry(prp->agmt); if (!slapi_mod_isvalid(smod)) { /* bogus */ slapi_log_error(SLAPI_LOG_REPL, repl_plugin_name, @@ -2062,7 +2062,7 @@ done: static void -windows_map_mods_for_replay(Private_Repl_Protocol *prp,LDAPMod **original_mods, LDAPMod ***returned_mods, int is_user, char** password, const Slapi_Entry *ad_entry) +windows_map_mods_for_replay(Private_Repl_Protocol *prp,LDAPMod **original_mods, LDAPMod ***returned_mods, int is_user, char** password) { Slapi_Mods smods = {0}; Slapi_Mods mapped_smods = {0}; @@ -2216,7 +2216,7 @@ windows_map_mods_for_replay(Private_Repl_Protocol *prp,LDAPMod **original_mods, } } /* Otherwise we do not copy this mod at all */ - if (mysmod && !mod_already_made(prp, mysmod, ad_entry)) { /* make sure this mod is still valid to send */ + if (mysmod && !mod_already_made(prp, mysmod)) { /* make sure this mod is still valid to send */ slapi_mods_add_ldapmod(&mapped_smods, slapi_mod_get_ldapmod_passout(mysmod)); } if (mysmod) { diff --git a/ldap/servers/slapd/modutil.c b/ldap/servers/slapd/modutil.c index b063fa9de..eec7b33ba 100644 --- a/ldap/servers/slapd/modutil.c +++ b/ldap/servers/slapd/modutil.c @@ -603,6 +603,8 @@ slapi_mod_init_valueset_byval(Slapi_Mod *smod, int op, const char *type, const S slapi_mod_set_type (smod, type); if (svs!=NULL) { Slapi_Value **svary = valueset_get_valuearray(svs); + ber_bvecfree(smod->mod->mod_bvalues); + smod->mod->mod_bvalues = NULL; valuearray_get_bervalarray(svary, &smod->mod->mod_bvalues); smod->num_values = slapi_valueset_count(svs); smod->num_elements = smod->num_values + 1;
0
8a3cea679aa0c6e81e8a6ef13da5b7f7bcc30fba
389ds/389-ds-base
Issue 50737 - Allow building with rust online without vendoring Bug Description: Building --rust-enable without --rust-enable-offline still requires predownloading the libraries. Fix Description: Setup .cargo/config on ./configure time allowing to subsequently do make that would in a case automatically download necessary libraries (in online mode). Fixes https://pagure.io/389-ds-base/issue/50737 Author: Matus Honek <[email protected]> Review by: ???
commit 8a3cea679aa0c6e81e8a6ef13da5b7f7bcc30fba Author: Matus Honek <[email protected]> Date: Wed Jan 22 10:05:42 2020 +0000 Issue 50737 - Allow building with rust online without vendoring Bug Description: Building --rust-enable without --rust-enable-offline still requires predownloading the libraries. Fix Description: Setup .cargo/config on ./configure time allowing to subsequently do make that would in a case automatically download necessary libraries (in online mode). Fixes https://pagure.io/389-ds-base/issue/50737 Author: Matus Honek <[email protected]> Review by: ??? diff --git a/.cargo/config b/.cargo/config deleted file mode 100644 index af24cf11b..000000000 --- a/.cargo/config +++ /dev/null @@ -1,8 +0,0 @@ - - -[source.crates-io] -replace-with = "vendored-sources" - -[source.vendored-sources] -directory = "./vendor" - diff --git a/.cargo/config.in b/.cargo/config.in new file mode 100644 index 000000000..d7d8ff4d4 --- /dev/null +++ b/.cargo/config.in @@ -0,0 +1,6 @@ +[source.crates-io] +registry = "https://github.com/rust-lang/crates.io-index" +@rust_vendor_sources@ + +[source.vendored-sources] +directory = "./vendor" diff --git a/configure.ac b/configure.ac index 40fdf3500..95772d763 100644 --- a/configure.ac +++ b/configure.ac @@ -105,11 +105,18 @@ if test "$enable_rust" = yes -o "$enable_rust_offline" = yes; then AC_MSG_FAILURE("Rust based plugins cannot be built cargo=$CARGO rustc=$RUSTC") ]) - + if test "$enable_rust_offline" = yes; then + rust_vendor_sources = "replace-with = \"vendored-sources\"" + else + rust_vendor_sources = "" + fi + AC_SUBST([rust_vendor_sources]) + AC_CONFIG_FILES([.cargo/config]) fi AC_SUBST([enable_rust]) AM_CONDITIONAL([RUST_ENABLE],[test "$enable_rust" = yes -o "$enable_rust_offline" = yes]) + AC_MSG_CHECKING(for --enable-debug) AC_ARG_ENABLE(debug, AS_HELP_STRING([--enable-debug], [Enable debug features (default: no)]), [], [ enable_debug=no ])
0
279b68d50fb8f2ebb74167a1352e5c23a1cdb17d
389ds/389-ds-base
Issue 4513 - CI Tests - fix test failures Description: Fixed tests in these suites: basic, entryuuid, filter, lib389, and schema relates: https://github.com/389ds/389-ds-base/issues/4513 Reviewed by: progier(Thanks!)
commit 279b68d50fb8f2ebb74167a1352e5c23a1cdb17d Author: Mark Reynolds <[email protected]> Date: Tue Jan 12 10:09:23 2021 -0500 Issue 4513 - CI Tests - fix test failures Description: Fixed tests in these suites: basic, entryuuid, filter, lib389, and schema relates: https://github.com/389ds/389-ds-base/issues/4513 Reviewed by: progier(Thanks!) diff --git a/dirsrvtests/tests/suites/basic/basic_test.py b/dirsrvtests/tests/suites/basic/basic_test.py index 7aaa42343..eb8e8e276 100644 --- a/dirsrvtests/tests/suites/basic/basic_test.py +++ b/dirsrvtests/tests/suites/basic/basic_test.py @@ -1059,6 +1059,41 @@ def test_search_ou(topology_st): assert len(entries) == 0 +def test_bind_invalid_entry(topology_st): + """Test the failing bind does not return information about the entry + + :id: 5cd9b083-eea6-426b-84ca-83c26fc49a6f + + :setup: Standalone instance + + :steps: + 1: bind as non existing entry + 2: check that bind info does not report 'No such entry' + + :expectedresults: + 1: pass + 2: pass + """ + + topology_st.standalone.restart() + INVALID_ENTRY="cn=foooo,%s" % DEFAULT_SUFFIX + try: + topology_st.standalone.simple_bind_s(INVALID_ENTRY, PASSWORD) + except ldap.LDAPError as e: + log.info('test_bind_invalid_entry: Failed to bind as %s (expected)' % INVALID_ENTRY) + log.info('exception description: ' + e.args[0]['desc']) + if 'info' in e.args[0]: + log.info('exception info: ' + e.args[0]['info']) + assert e.args[0]['desc'] == 'Invalid credentials' + assert 'info' not in e.args[0] + pass + + log.info('test_bind_invalid_entry: PASSED') + + # reset credentials + topology_st.standalone.simple_bind_s(DN_DM, PW_DM) + + @pytest.mark.bz1044135 @pytest.mark.ds47319 def test_connection_buffer_size(topology_st): @@ -1477,36 +1512,6 @@ def test_dscreate_with_different_rdn(dscreate_test_rdn_value): else: assert True -def test_bind_invalid_entry(topology_st): - """Test the failing bind does not return information about the entry - - :id: 5cd9b083-eea6-426b-84ca-83c26fc49a6f - - :setup: Standalone instance - - :steps: - 1: bind as non existing entry - 2: check that bind info does not report 'No such entry' - - :expectedresults: - 1: pass - 2: pass - """ - - topology_st.standalone.restart() - INVALID_ENTRY="cn=foooo,%s" % DEFAULT_SUFFIX - try: - topology_st.standalone.simple_bind_s(INVALID_ENTRY, PASSWORD) - except ldap.LDAPError as e: - log.info('test_bind_invalid_entry: Failed to bind as %s (expected)' % INVALID_ENTRY) - log.info('exception description: ' + e.args[0]['desc']) - if 'info' in e.args[0]: - log.info('exception info: ' + e.args[0]['info']) - assert e.args[0]['desc'] == 'Invalid credentials' - assert 'info' not in e.args[0] - pass - - log.info('test_bind_invalid_entry: PASSED') if __name__ == '__main__': # Run isolated diff --git a/dirsrvtests/tests/suites/entryuuid/basic_test.py b/dirsrvtests/tests/suites/entryuuid/basic_test.py index 4d8a40909..3c458da4b 100644 --- a/dirsrvtests/tests/suites/entryuuid/basic_test.py +++ b/dirsrvtests/tests/suites/entryuuid/basic_test.py @@ -37,6 +37,7 @@ def _entryuuid_import_and_search(topology): target_ldif = os.path.join(ldif_dir, 'localhost-userRoot-2020_03_30_13_14_47.ldif') import_ldif = os.path.join(DATADIR1, 'localhost-userRoot-2020_03_30_13_14_47.ldif') shutil.copyfile(import_ldif, target_ldif) + os.chmod(target_ldif, 0o777) be = Backends(topology.standalone).get('userRoot') task = be.import_ldif([target_ldif]) diff --git a/dirsrvtests/tests/suites/filter/rfc3673_all_oper_attrs_test.py b/dirsrvtests/tests/suites/filter/rfc3673_all_oper_attrs_test.py index 6d507abd8..4cc945ba8 100644 --- a/dirsrvtests/tests/suites/filter/rfc3673_all_oper_attrs_test.py +++ b/dirsrvtests/tests/suites/filter/rfc3673_all_oper_attrs_test.py @@ -53,11 +53,11 @@ TEST_PARAMS = [(DN_ROOT, False, [ (TEST_USER_DN, False, [ 'createTimestamp', 'creatorsName', 'entrydn', 'entryid', 'modifiersName', 'modifyTimestamp', - 'nsUniqueId', 'parentid' + 'nsUniqueId', 'parentid', 'entryUUID' ]), (TEST_USER_DN, True, [ 'createTimestamp', 'creatorsName', 'entrydn', - 'entryid', 'modifyTimestamp', 'nsUniqueId', 'parentid' + 'entryid', 'modifyTimestamp', 'nsUniqueId', 'parentid', 'entryUUID' ]), (DN_CONFIG, False, [ 'numSubordinates', 'passwordHistory', 'modifyTimestamp', diff --git a/dirsrvtests/tests/suites/lib389/config_compare_test.py b/dirsrvtests/tests/suites/lib389/config_compare_test.py index 709bae8cb..84f55acfa 100644 --- a/dirsrvtests/tests/suites/lib389/config_compare_test.py +++ b/dirsrvtests/tests/suites/lib389/config_compare_test.py @@ -22,15 +22,18 @@ def test_config_compare(topology_i2): st2_config = topology_i2.ins.get('standalone2').config # 'nsslapd-port' attribute is expected to be same in cn=config comparison, # but they are different in our testing environment - # as we are using 2 DS instances running, both running simultaneuosly. + # as we are using 2 DS instances running, both running simultaneously. # Hence explicitly adding 'nsslapd-port' to compare_exclude. st1_config._compare_exclude.append('nsslapd-port') st2_config._compare_exclude.append('nsslapd-port') st1_config._compare_exclude.append('nsslapd-secureport') st2_config._compare_exclude.append('nsslapd-secureport') + st1_config._compare_exclude.append('nsslapd-ldapssotoken-secret') + st2_config._compare_exclude.append('nsslapd-ldapssotoken-secret') assert Config.compare(st1_config, st2_config) + if __name__ == '__main__': # Run isolated # -s for DEBUG mode diff --git a/dirsrvtests/tests/suites/lib389/idm/user_compare_i2_test.py b/dirsrvtests/tests/suites/lib389/idm/user_compare_i2_test.py index c7540e4ce..ccde0f6b0 100644 --- a/dirsrvtests/tests/suites/lib389/idm/user_compare_i2_test.py +++ b/dirsrvtests/tests/suites/lib389/idm/user_compare_i2_test.py @@ -39,6 +39,9 @@ def test_user_compare_i2(topology_i2): st2_users.create(properties=user_properties) st2_testuser = st2_users.get('testuser') + st1_testuser._compare_exclude.append('entryuuid') + st2_testuser._compare_exclude.append('entryuuid') + assert UserAccount.compare(st1_testuser, st2_testuser) diff --git a/dirsrvtests/tests/suites/schema/schema_reload_test.py b/dirsrvtests/tests/suites/schema/schema_reload_test.py index 73f66a291..232a497af 100644 --- a/dirsrvtests/tests/suites/schema/schema_reload_test.py +++ b/dirsrvtests/tests/suites/schema/schema_reload_test.py @@ -103,7 +103,7 @@ def test_schema_operation(topo): schema_file.write("objectclasses: ( 1.2.3.4.5.6.7 NAME 'MozillaObject' " + "SUP top MUST ( objectclass $ cn ) MAY ( MoZiLLaaTTRiBuTe )" + " X-ORIGIN 'user defined' )')\n") - + os.chmod(schema_filename, 0o777) except OSError as e: log.fatal("Failed to create schema file: " + "{} Error: {}".format(schema_filename, str(e))) @@ -132,7 +132,7 @@ def test_schema_operation(topo): schema_file.write("objectclasses: ( 1.2.3.4.5.6.7 NAME 'MozillaObject' "+ "SUP top MUST ( objectclass $ cn ) MAY ( MOZILLAATTRIBUTE ) "+ "X-ORIGIN 'user defined' )')\n") - + os.chmod(schema_filename, 0o777) except OSError as e: log.fatal("Failed to create schema file: " + "{} Error: {}".format(schema_filename, str(e))) @@ -195,6 +195,7 @@ def test_valid_schema(topo): schema_file.write("objectclasses: ( 1.2.3.4.5.6.7.8 NAME 'TestObject' " + "SUP top MUST ( objectclass $ cn ) MAY ( givenName $ " + "sn $ ValidAttribute ) X-ORIGIN 'user defined' )')\n") + os.chmod(schema_filename, 0o777) except OSError as e: log.fatal("Failed to create schema file: " + "{} Error: {}".format(schema_filename, str(e))) @@ -245,6 +246,7 @@ def test_invalid_schema(topo): schema_file.write("objectclasses: ( 1.2.3.4.5.6.7 NAME 'MoZiLLaOBJeCT' " + "SUP top MUST ( objectclass $ cn ) MAY ( givenName $ " + "sn $ MozillaAttribute ) X-ORIGIN 'user defined' )')\n") + os.chmod(schema_filename, 0o777) except OSError as e: log.fatal("Failed to create schema file: " + "{} Error: {}".format(schema_filename, str(e))) @@ -261,6 +263,7 @@ def test_invalid_schema(topo): schema_file.write("objectclasses: ( 1.2.3.4.5.6.70 NAME 'MoZiLLaOBJeCT' " + "SUP top MUST ( objectclass $ cn ) MAY ( givenName $ " + "cn $ MoZiLLaATTRiBuTe ) X-ORIGIN 'user defined' )')\n") + os.chmod(schema_filename, 0o777) except OSError as e: log.fatal("Failed to create schema file: " + "{} Error: {}".format(schema_filename, str(e)))
0
df93b03da12c22d18a4153105f687671e52efdd5
389ds/389-ds-base
Ticket #47428 - Memory leak in 389-ds-base 1.2.11.15 https://fedorahosted.org/389/ticket/47428 Reviewed by: rmeggins Branch: master Fix Description: Call ber_sockbuf_remove_io to remove our openldap io layer from the connection c_sb and free the data associated with it. Platforms tested: RHEL6 x86_64 Flag Day: no Doc impact: no
commit df93b03da12c22d18a4153105f687671e52efdd5 Author: Matthew Via <​[email protected]> Date: Wed Jul 10 11:30:57 2013 -0600 Ticket #47428 - Memory leak in 389-ds-base 1.2.11.15 https://fedorahosted.org/389/ticket/47428 Reviewed by: rmeggins Branch: master Fix Description: Call ber_sockbuf_remove_io to remove our openldap io layer from the connection c_sb and free the data associated with it. Platforms tested: RHEL6 x86_64 Flag Day: no Doc impact: no diff --git a/ldap/servers/slapd/connection.c b/ldap/servers/slapd/connection.c index 687bf4202..b2ed83c44 100644 --- a/ldap/servers/slapd/connection.c +++ b/ldap/servers/slapd/connection.c @@ -263,6 +263,7 @@ connection_cleanup(Connection *conn) /* destroy any sasl context */ sasl_dispose((sasl_conn_t**)&conn->c_sasl_conn); /* PAGED_RESULTS */ + handle_closed_connection(conn); /* Clean up sockbufs */ pagedresults_cleanup(conn, 0 /* do not need to lock inside */); /* free the connection socket buffer */ diff --git a/ldap/servers/slapd/daemon.c b/ldap/servers/slapd/daemon.c index e0c14c8ea..817fea793 100644 --- a/ldap/servers/slapd/daemon.c +++ b/ldap/servers/slapd/daemon.c @@ -2593,6 +2593,13 @@ bail: #endif /* ENABLE_AUTOBIND */ #endif /* ENABLE_LDAPI */ +void +handle_closed_connection(Connection *conn) +{ + ber_sockbuf_remove_io(conn->c_sb, &openldap_sockbuf_io, + LBER_SBIOD_LEVEL_PROVIDER); +} + /* NOTE: this routine is not reentrant */ static int handle_new_connection(Connection_Table *ct, int tcps, PRFileDesc *pr_acceptfd, int secure, int local) diff --git a/ldap/servers/slapd/proto-slap.h b/ldap/servers/slapd/proto-slap.h index dc73faa1c..447d7d522 100644 --- a/ldap/servers/slapd/proto-slap.h +++ b/ldap/servers/slapd/proto-slap.h @@ -1413,6 +1413,7 @@ int sasl_io_setup(Connection *c); /* * daemon.c */ +void handle_closed_connection(Connection *); #ifndef LINUX void slapd_do_nothing(int); #endif
0
bb55a7285226847f738078348fd47ec7633a39a3
389ds/389-ds-base
Ticket #48008 - db2bak.pl man page should be improved. Description: Adding a new option "-A backupdir" to the db2bak.pl manpage. -A backupdir This is similar to -a, except that a sub-directory of backupdir will be created for the backup, and the name of the sub-direc‐ tory will be a timestamp of the form server-instance-date_time. https://fedorahosted.org/389/ticket/48008 Reviewed by [email protected] (Thank you, Rich!!)
commit bb55a7285226847f738078348fd47ec7633a39a3 Author: Noriko Hosoi <[email protected]> Date: Wed Jun 10 09:41:02 2015 -0700 Ticket #48008 - db2bak.pl man page should be improved. Description: Adding a new option "-A backupdir" to the db2bak.pl manpage. -A backupdir This is similar to -a, except that a sub-directory of backupdir will be created for the backup, and the name of the sub-direc‐ tory will be a timestamp of the form server-instance-date_time. https://fedorahosted.org/389/ticket/48008 Reviewed by [email protected] (Thank you, Rich!!) diff --git a/man/man8/db2bak.pl.8 b/man/man8/db2bak.pl.8 index 9bd0810b6..71beae4e6 100644 --- a/man/man8/db2bak.pl.8 +++ b/man/man8/db2bak.pl.8 @@ -18,7 +18,7 @@ .SH NAME db2bak.pl - Directory Server perl script for creating a backup .SH SYNOPSIS -db2bak.pl [\-Z serverID] [\-D rootdn] { \-w password | \-w \- | \-j filename } [\-t dbtype] [\-a backupdir] [\-P protocol] [\-v] [\-h] +db2bak.pl [\-Z serverID] [\-D rootdn] { \-w password | \-w \- | \-j filename } [\-t dbtype] [\-a backupdir] [\-A backupdir] [\-P protocol] [\-v] [\-h] .SH DESCRIPTION Creates a backup of the Directory Server database. The Directory Server must be started prior to running this script. @@ -49,6 +49,9 @@ The backend database type (default: ldbm database). .B \fB\-a\fR \fIbackupdir\fR The directory where the backup should be stored. .TP +.B \fB\-A\fR \fIbackupdir\fR +This is similar to \fB-a\fR, except that a sub-directory of \fIbackupdir\fR will be created for the backup, and the name of the sub-directory will be a timestamp of the form \fIserver-instance-date_time\fR. +.TP .B \fB\-P\fR \fIProtocol\fR The connection protocol to connect to the Directory Server. Protocols are STARTTLS, LDAPS, LDAPI, and LDAP. If this option is skipped, the most secure protocol that is available is used. For LDAPI, AUTOBIND is also
0
3aa14161cfe827ce0f29ce3c0059a10305149b91
389ds/389-ds-base
Ticket 49421 - on bind password upgrade proof of concept Bug Description: Improve security of accounts by upgrading their password hashes on login when we have the plaintext password available. Fix Description: Implement the upgrade on bind function and provide it to bind.c https://pagure.io/389-ds-base/issue/49421 Author: Emanuel Rietveld <[email protected]> Review by: William Brown
commit 3aa14161cfe827ce0f29ce3c0059a10305149b91 Author: Emanuel Rietveld <[email protected]> Date: Thu May 2 12:02:38 2019 +0200 Ticket 49421 - on bind password upgrade proof of concept Bug Description: Improve security of accounts by upgrading their password hashes on login when we have the plaintext password available. Fix Description: Implement the upgrade on bind function and provide it to bind.c https://pagure.io/389-ds-base/issue/49421 Author: Emanuel Rietveld <[email protected]> Review by: William Brown diff --git a/ldap/servers/slapd/bind.c b/ldap/servers/slapd/bind.c index 314b7c4ea..d2a89ba4f 100644 --- a/ldap/servers/slapd/bind.c +++ b/ldap/servers/slapd/bind.c @@ -762,6 +762,9 @@ do_bind(Slapi_PBlock *pb) goto free_and_return; } } + + update_pw_encoding(pb, bind_target_entry, sdn, cred.bv_val); + bind_credentials_set(pb_conn, authtype, slapi_ch_strdup(slapi_sdn_get_ndn(sdn)), NULL, NULL, NULL, bind_target_entry); @@ -783,6 +786,7 @@ do_bind(Slapi_PBlock *pb) /* need_new_pw failed; need_new_pw already send_ldap_result in it. */ goto free_and_return; } + } else { /* anonymous */ /* set bind creds here so anonymous limits are set */ bind_credentials_set(pb_conn, authtype, NULL, NULL, NULL, NULL, NULL); diff --git a/ldap/servers/slapd/pw.c b/ldap/servers/slapd/pw.c index 5e7788af3..a618b2a52 100644 --- a/ldap/servers/slapd/pw.c +++ b/ldap/servers/slapd/pw.c @@ -3247,3 +3247,101 @@ add_shadow_ext_password_attrs(Slapi_PBlock *pb, Slapi_Entry **e) return rc; } +/* + * Re-encode a user's password if a different encoding scheme is configured + * in the password policy than the password is currently encoded with. + * + * Returns: + * success ( 0 ) + * operationsError ( -1 ), + */ +int update_pw_encoding(Slapi_PBlock *orig_pb, Slapi_Entry *e, Slapi_DN *sdn, char *cleartextpassword) { + char *dn = (char *)slapi_sdn_get_ndn(sdn); + Slapi_Attr *pw = NULL; + Slapi_Value **password_values = NULL; + passwdPolicy *pwpolicy = NULL; + struct pw_scheme *curpwsp = NULL; + Slapi_Mods smods; + char *hashed_val = NULL; + Slapi_PBlock *pb = NULL; + int res = 0; + + slapi_mods_init(&smods, 0); + + if (e == NULL || slapi_entry_attr_find(e, SLAPI_USERPWD_ATTR, &pw) != 0 || pw == NULL) { + slapi_log_err(SLAPI_LOG_WARNING, + "update_pw_encoding", "Could not read password attribute on '%s'\n", + dn); + res = -1; + goto free_and_return; + } + + password_values = attr_get_present_values(pw); + if (password_values == NULL || password_values[0] == NULL) { + slapi_log_err(SLAPI_LOG_WARNING, + "update_pw_encoding", "Could not get password values for '%s'\n", + dn); + res = -1; + goto free_and_return; + } + if (password_values[1] != NULL) { + slapi_log_err(SLAPI_LOG_WARNING, + "update_pw_encoding", "Multivalued password attribute not supported: '%s'\n", + dn); + res = -1; + goto free_and_return; + } + + pwpolicy = new_passwdPolicy(orig_pb, dn); + if (pwpolicy == NULL || pwpolicy->pw_storagescheme == NULL) { + slapi_log_err(SLAPI_LOG_WARNING, + "update_pw_encoding", "Could not get requested encoding scheme: '%s'\n", + dn); + res = -1; + goto free_and_return; + } + + curpwsp = pw_val2scheme((char *)slapi_value_get_string(password_values[0]), NULL, 1); + if (curpwsp != NULL && strcmp(curpwsp->pws_name, pwpolicy->pw_storagescheme->pws_name) == 0) { + res = 0; // Nothing to do + goto free_and_return; + } + + hashed_val = slapi_encode_ext(NULL, NULL, cleartextpassword, pwpolicy->pw_storagescheme->pws_name); + if (hashed_val == NULL) { + slapi_log_err(SLAPI_LOG_WARNING, + "update_pw_encoding", "Could not re-encode password: '%s'\n", + dn); + res = -1; + goto free_and_return; + } + + slapi_mods_add_string(&smods, LDAP_MOD_REPLACE, SLAPI_USERPWD_ATTR, hashed_val); + slapi_ch_free((void **)&hashed_val); + + pb = slapi_pblock_new(); + /* We don't want to overwrite the modifiersname, etc. attributes, + * so we set a flag for this operation. + * We also set the repl flag to avoid updating password history */ + slapi_modify_internal_set_pb_ext(pb, sdn, + slapi_mods_get_ldapmods_byref(&smods), + NULL, /* Controls */ + NULL, /* UniqueID */ + pw_get_componentID(), /* PluginID */ + OP_FLAG_SKIP_MODIFIED_ATTRS & + OP_FLAG_REPLICATED); /* Flags */ + slapi_modify_internal_pb(pb); + + slapi_pblock_get(pb, SLAPI_PLUGIN_INTOP_RESULT, &res); + if (res != LDAP_SUCCESS) { + slapi_log_err(SLAPI_LOG_WARNING, + "update_pw_encoding", "Modify error %d on entry '%s'\n", + res, dn); + } + +free_and_return: + if (curpwsp) free_pw_scheme(curpwsp); + if (pb) slapi_pblock_destroy(pb); + slapi_mods_done(&smods); + return res; +} diff --git a/ldap/servers/slapd/slapi-plugin.h b/ldap/servers/slapd/slapi-plugin.h index a4a9ee961..d26397d19 100644 --- a/ldap/servers/slapd/slapi-plugin.h +++ b/ldap/servers/slapd/slapi-plugin.h @@ -5385,6 +5385,7 @@ int slapi_value_find(void *plugin, struct berval **vals, struct berval *v); */ #define SLAPI_USERPWD_ATTR "userpassword" int slapi_pw_find_sv(Slapi_Value **vals, const Slapi_Value *v); +int update_pw_encoding(Slapi_PBlock *orig_pb, Slapi_Entry *e, Slapi_DN *sdn, char *cleartextpassword); /* value encoding encoding */ /* checks if the value is encoded with any known algorithm*/
0
d86e748fa3e108a1c0adec397b1a0c4709233de6
389ds/389-ds-base
Issue 4165 - Don't apply RootDN access control restrictions to UNIX connections Bug Description: The RootDN access control plugin prevents access via UNIX sockets (ldapi://) when host or IP restrictions are configured. Fix Description: The host and IP restrictions are no longer applied if the client connected via UNIX sockets. relates: https://github.com/389ds/389-ds-base/issues/4165 Author: Sam Morris Reviewed by: @mreynolds389, @Firstyear
commit d86e748fa3e108a1c0adec397b1a0c4709233de6 Author: Sam Morris <[email protected]> Date: Fri Nov 26 10:35:14 2021 +0000 Issue 4165 - Don't apply RootDN access control restrictions to UNIX connections Bug Description: The RootDN access control plugin prevents access via UNIX sockets (ldapi://) when host or IP restrictions are configured. Fix Description: The host and IP restrictions are no longer applied if the client connected via UNIX sockets. relates: https://github.com/389ds/389-ds-base/issues/4165 Author: Sam Morris Reviewed by: @mreynolds389, @Firstyear diff --git a/ldap/servers/plugins/rootdn_access/rootdn_access.c b/ldap/servers/plugins/rootdn_access/rootdn_access.c index b256fa290..d8d14f95c 100644 --- a/ldap/servers/plugins/rootdn_access/rootdn_access.c +++ b/ldap/servers/plugins/rootdn_access/rootdn_access.c @@ -452,6 +452,7 @@ free_and_return: static int32_t rootdn_check_access(Slapi_PBlock *pb) { + PRNetAddr *server_addr = NULL; PRNetAddr *client_addr = NULL; PRHostEnt *host_entry = NULL; time_t curr_time; @@ -513,6 +514,22 @@ rootdn_check_access(Slapi_PBlock *pb) return -1; } } + + server_addr = (PRNetAddr *)slapi_ch_malloc(sizeof(PRNetAddr)); + if (slapi_pblock_get(pb, SLAPI_CONN_SERVERNETADDR, server_addr) != 0) { + slapi_log_err(SLAPI_LOG_ERR, ROOTDN_PLUGIN_SUBSYSTEM, + "rootdn_check_access - Could not get server address.\n"); + rc = -1; + goto free_and_return; + } + /* + * Remaining checks are only relevant for AF_INET/AF_INET6 connections + */ + if (PR_NetAddrFamily(server_addr) == PR_AF_LOCAL) { + rc = 0; + goto free_and_return; + } + /* * Check the host restrictions, deny always overrides allow */ @@ -688,6 +705,7 @@ rootdn_check_access(Slapi_PBlock *pb) } free_and_return: + slapi_ch_free((void **)&server_addr); slapi_ch_free((void **)&client_addr); slapi_ch_free((void **)&host_entry); slapi_ch_free_string(&dnsName);
0
072b290d22ec404bb9e74ef43bd19570e01b2884
389ds/389-ds-base
Issue 6191 - Node.js 16 actions are deprecated Description: Node.js 16 actions are deprecated. Update * actions/checkout to v4 * actions/download-artifact to v4 * actions/upload-artifact to v4 Fixes: https://github.com/389ds/389-ds-base/issues/6191 Reviewed by: @progier389, @droideck (Thanks!)
commit 072b290d22ec404bb9e74ef43bd19570e01b2884 Author: Viktor Ashirov <[email protected]> Date: Mon Jun 10 10:35:30 2024 +0200 Issue 6191 - Node.js 16 actions are deprecated Description: Node.js 16 actions are deprecated. Update * actions/checkout to v4 * actions/download-artifact to v4 * actions/upload-artifact to v4 Fixes: https://github.com/389ds/389-ds-base/issues/6191 Reviewed by: @progier389, @droideck (Thanks!) diff --git a/.github/workflows/compile.yml b/.github/workflows/compile.yml index 06872c8cd..0176e88c2 100644 --- a/.github/workflows/compile.yml +++ b/.github/workflows/compile.yml @@ -58,7 +58,7 @@ jobs: image: ${{ matrix.image }} steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Checkout and configure run: autoreconf -fvi && ./configure env: @@ -72,7 +72,7 @@ jobs: - name: Build using ${{ matrix.compiler }} run: bash -c "(make V=0 2> >(tee /dev/stderr)) > log.txt" - - uses: actions/upload-artifact@v3 + - uses: actions/upload-artifact@v4 with: name: ${{ matrix.name }} path: log.txt diff --git a/.github/workflows/lmdbpytest.yml b/.github/workflows/lmdbpytest.yml index c4083cf8d..dae65e223 100644 --- a/.github/workflows/lmdbpytest.yml +++ b/.github/workflows/lmdbpytest.yml @@ -31,7 +31,7 @@ jobs: matrix: ${{ steps.set-matrix.outputs.matrix }} steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Add GITHUB_WORKSPACE as a safe directory run: git config --global --add safe.directory "$GITHUB_WORKSPACE" @@ -47,7 +47,7 @@ jobs: run: tar -cvf dist.tar dist/ - name: Upload RPMs - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: rpms path: dist.tar @@ -62,7 +62,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Setup tmate session uses: mxschmitt/action-tmate@v3 @@ -79,7 +79,7 @@ jobs: sudo systemctl start docker - name: Download RPMs - uses: actions/download-artifact@v3 + uses: actions/download-artifact@v4 with: name: rpms @@ -114,7 +114,7 @@ jobs: - name: Upload pytest test results if: always() - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: pytest-${{ env.PYTEST_SUITE }} path: | diff --git a/.github/workflows/npm.yml b/.github/workflows/npm.yml index 89efc06a8..f2c5d9ca9 100644 --- a/.github/workflows/npm.yml +++ b/.github/workflows/npm.yml @@ -19,7 +19,7 @@ jobs: image: quay.io/389ds/ci-images:test steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Run NPM Audit CI run: cd $GITHUB_WORKSPACE/src/cockpit/389-console && npx --yes audit-ci --config audit-ci.json diff --git a/.github/workflows/pytest.yml b/.github/workflows/pytest.yml index 44cb26dc5..76a1eb4b0 100644 --- a/.github/workflows/pytest.yml +++ b/.github/workflows/pytest.yml @@ -31,7 +31,7 @@ jobs: matrix: ${{ steps.set-matrix.outputs.matrix }} steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Add GITHUB_WORKSPACE as a safe directory run: git config --global --add safe.directory "$GITHUB_WORKSPACE" @@ -47,7 +47,7 @@ jobs: run: tar -cvf dist.tar dist/ - name: Upload RPMs - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: rpms path: dist.tar @@ -62,7 +62,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Setup tmate session uses: mxschmitt/action-tmate@v3 @@ -79,7 +79,7 @@ jobs: sudo systemctl start docker - name: Download RPMs - uses: actions/download-artifact@v3 + uses: actions/download-artifact@v4 with: name: rpms @@ -114,7 +114,7 @@ jobs: - name: Upload pytest test results if: always() - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: pytest-${{ env.PYTEST_SUITE }} path: | diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d09482f76..8bf44efe4 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -33,7 +33,7 @@ jobs: VERSION: ${{ github.event.inputs.version || github.ref_name }} - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 with: fetch-depth: 0 ref: ${{ steps.get_version.outputs.version }} @@ -60,7 +60,7 @@ jobs: TAG=${{ steps.get_version.outputs.version }} make -f rpm.mk dist-bz2 - name: Upload tarball - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: ${{ steps.get_version.outputs.version }}.tar.bz2 path: ${{ steps.get_version.outputs.version }}.tar.bz2 diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 04b2c98c8..af969bf7b 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -16,7 +16,7 @@ jobs: image: quay.io/389ds/ci-images:test steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Run testimony if: always()
0
b6d259dfeca81ab8f0e443b6981131d0eee38bb0
389ds/389-ds-base
Ticket #48048 - Fix coverity issues - 2015/2/24 Coverity defect 13058 - Resource leak Description: In error cases, input_cursors leaked. modified: import_merge_one_file in import-merge.c
commit b6d259dfeca81ab8f0e443b6981131d0eee38bb0 Author: Noriko Hosoi <[email protected]> Date: Tue Feb 24 15:44:08 2015 -0800 Ticket #48048 - Fix coverity issues - 2015/2/24 Coverity defect 13058 - Resource leak Description: In error cases, input_cursors leaked. modified: import_merge_one_file in import-merge.c diff --git a/ldap/servers/slapd/back-ldbm/import-merge.c b/ldap/servers/slapd/back-ldbm/import-merge.c index a728165c3..db85a1456 100644 --- a/ldap/servers/slapd/back-ldbm/import-merge.c +++ b/ldap/servers/slapd/back-ldbm/import-merge.c @@ -398,6 +398,7 @@ static int import_merge_one_file(ImportWorkerInfo *worker, int passes, int number_found = 0; int pass_number = 0; DB **input_files = NULL; + DBC **input_cursors = NULL; PR_ASSERT(NULL != inst); @@ -441,7 +442,6 @@ static int import_merge_one_file(ImportWorkerInfo *worker, int passes, } else { /* We really need to merge */ import_merge_queue_entry *merge_queue = NULL; - DBC **input_cursors = NULL; DBT key = {0}; import_merge_thang thang = {0}; int i = 0; @@ -629,13 +629,13 @@ static int import_merge_one_file(ImportWorkerInfo *worker, int passes, } } if (preclose_ret != 0) ret = preclose_ret; - slapi_ch_free( (void**)&input_cursors); } if (EOF == ret) { ret = 0; } error: + slapi_ch_free((void**)&input_cursors); slapi_ch_free((void**)&input_files); if (ret) { import_log_notice(worker->job, "%s: Import merge failed. "
0
e62a443685435fcb3652c1b94bc158ff3d49d810
389ds/389-ds-base
Issue 48085 - Add encryption cl5 test suite Description: Add a test suite that checks AES and 3DES encryption algorithms. Check unhashed#user#password for encryption in different circomstances. The test suite based on Sankar Ramalingam test suite. http://pagure.io/389-ds-base/issue/48085 Reviewed by: lkrispen, wibrown (Thanks!)
commit e62a443685435fcb3652c1b94bc158ff3d49d810 Author: Simon Pichugin <[email protected]> Date: Tue Feb 6 16:33:59 2018 +0100 Issue 48085 - Add encryption cl5 test suite Description: Add a test suite that checks AES and 3DES encryption algorithms. Check unhashed#user#password for encryption in different circomstances. The test suite based on Sankar Ramalingam test suite. http://pagure.io/389-ds-base/issue/48085 Reviewed by: lkrispen, wibrown (Thanks!) diff --git a/dirsrvtests/tests/suites/replication/encryption_cl5_test.py b/dirsrvtests/tests/suites/replication/encryption_cl5_test.py new file mode 100644 index 000000000..c3dfa2435 --- /dev/null +++ b/dirsrvtests/tests/suites/replication/encryption_cl5_test.py @@ -0,0 +1,130 @@ +# --- BEGIN COPYRIGHT BLOCK --- +# Copyright (C) 2017 Red Hat, Inc. +# All rights reserved. +# +# License: GPL (version 3 or any later version). +# See LICENSE for details. +# --- END COPYRIGHT BLOCK --- +# +import logging +import pytest +from lib389.utils import ensure_bytes +from lib389.replica import ReplicationManager +from lib389.dseldif import DSEldif +from lib389.idm.user import UserAccounts, TEST_USER_PROPERTIES +from lib389.topologies import topology_m2 +from lib389._constants import * + +ATTRIBUTE = 'unhashed#user#password' + +DEBUGGING = os.getenv("DEBUGGING", default=False) +if DEBUGGING: + logging.getLogger(__name__).setLevel(logging.DEBUG) +else: + logging.getLogger(__name__).setLevel(logging.INFO) +log = logging.getLogger(__name__) + + [email protected](scope="module") +def topology_with_tls(topology_m2): + """Enable TLS on all masters""" + + [i.enable_tls() for i in topology_m2] + + repl = ReplicationManager(DEFAULT_SUFFIX) + repl.test_replication(topology_m2.ms['master1'], topology_m2.ms['master2']) + + return topology_m2 + + +def _enable_changelog_encryption(inst, encrypt_algorithm): + """Configure changelog encryption for master""" + + dse_ldif = DSEldif(inst) + log.info('Configuring changelog encryption:{} for: {}'.format(inst.serverid, encrypt_algorithm)) + inst.stop() + dse_ldif.replace(DN_CHANGELOG, 'nsslapd-encryptionalgorithm', encrypt_algorithm) + if dse_ldif.get(DN_CHANGELOG, 'nsSymmetricKey'): + dse_ldif.delete(DN_CHANGELOG, 'nsSymmetricKey') + inst.start() + + +def _check_unhashed_userpw_encrypted(inst, change_type, user_dn, user_pw, is_encrypted): + """Check if unhashed#user#password attribute value is encrypted or not""" + + changelog_dbdir = os.path.join(os.path.dirname(inst.dbdir), DEFAULT_CHANGELOG_DB) + for dbfile in os.listdir(changelog_dbdir): + if dbfile.endswith('.db'): + changelog_dbfile = os.path.join(changelog_dbdir, dbfile) + log.info('Changelog dbfile file exist: {}'.format(changelog_dbfile)) + log.info('Running dbscan -f to check {} attr'.format(ATTRIBUTE)) + dbscanOut = inst.dbscan(DEFAULT_CHANGELOG_DB, changelog_dbfile) + count = 0 + for entry in dbscanOut.split(b'dbid: '): + if ensure_bytes('operation: {}'.format(change_type)) in entry and\ + ensure_bytes(ATTRIBUTE) in entry and ensure_bytes(user_dn) in entry: + count += 1 + user_pw_attr = ensure_bytes('{}: {}'.format(ATTRIBUTE, user_pw)) + if is_encrypted: + assert user_pw_attr not in entry, 'Changelog entry contains clear text password' + else: + assert user_pw_attr in entry, 'Changelog entry does not contain clear text password' + assert count, 'Operation type and DN of the entry not matched in changelog' + + [email protected]("encryption", ["AES", "3DES"]) +def test_algorithm_unhashed(topology_with_tls, encryption): + """Check encryption algowithm AES and 3DES. + And check unhashed#user#password attribute for encryption. + + :id: b7a37bf8-4b2e-4dbd-9891-70117d67558c + :setup: Replication with two masters and SSL configured. + :steps: 1. Enable changelog encrytion on master1 (try AES and 3DES). + 2. Add a user to master1/master2 + 3. Run dbscan -f on m1 to check unhashed#user#password + attribute is encrypted. + 4. Run dbscan -f on m2 to check unhashed#user#password + attribute is in cleartext. + 5. Modify password in master2/master1 + 6. Run dbscan -f on m1 to check unhashed#user#password + attribute is encrypted. + 7. Run dbscan -f on m2 to check unhashed#user#password + attribute is in cleartext. + :expectedresults: + 1. It should pass + 2. It should pass + 3. It should pass + 4. It should pass + 5. It should pass + 6. It should pass + 7. It should pass + """ + + m1 = topology_with_tls.ms['master1'] + m2 = topology_with_tls.ms['master2'] + test_passw = 'm2Test199' + + _enable_changelog_encryption(m1, encryption) + + for inst1, inst2 in ((m1, m2), (m2, m1)): + user_props = TEST_USER_PROPERTIES.copy() + user_props["userPassword"] = PASSWORD + users = UserAccounts(inst1, DEFAULT_SUFFIX) + tuser = users.create(properties=user_props) + + _check_unhashed_userpw_encrypted(m1, 'add', tuser.dn, PASSWORD, True) + _check_unhashed_userpw_encrypted(m2, 'add', tuser.dn, PASSWORD, False) + + users = UserAccounts(inst2, DEFAULT_SUFFIX) + tuser = users.get(tuser.rdn) + tuser.set('userPassword', test_passw) + _check_unhashed_userpw_encrypted(m1, 'modify', tuser.dn, test_passw, True) + _check_unhashed_userpw_encrypted(m2, 'modify', tuser.dn, test_passw, False) + tuser.delete() + + +if __name__ == '__main__': + # Run isolated + # -s for DEBUG mode + CURRENT_FILE = os.path.realpath(__file__) + pytest.main("-s {}".format(CURRENT_FILE))
0
24c303d3e6c91358fc645268d582144f377e3902
389ds/389-ds-base
Ticket #48030 - spec file should run "systemctl stop" against each running instance instead of dirsrv.target A patch was provided by [email protected] (Thank you, Ludwig!!) https://fedorahosted.org/389/ticket/48030
commit 24c303d3e6c91358fc645268d582144f377e3902 Author: Noriko Hosoi <[email protected]> Date: Wed Feb 25 18:39:45 2015 -0800 Ticket #48030 - spec file should run "systemctl stop" against each running instance instead of dirsrv.target A patch was provided by [email protected] (Thank you, Ludwig!!) https://fedorahosted.org/389/ticket/48030 diff --git a/rpm/389-ds-base.spec.in b/rpm/389-ds-base.spec.in index af9244aae..17a1f86bb 100644 --- a/rpm/389-ds-base.spec.in +++ b/rpm/389-ds-base.spec.in @@ -227,35 +227,44 @@ ninst=0 # number of instances found in total if [ -n "$DEBUGPOSTTRANS" ] ; then output=$DEBUGPOSTTRANS fi -echo looking for services in %{_sysconfdir}/systemd/system/%{groupname}.wants/* > $output 2>&1 || : +echo looking for services in %{_sysconfdir}/systemd/system/%{groupname}.wants/* >> $output 2>&1 || : for service in %{_sysconfdir}/systemd/system/%{groupname}.wants/* ; do if [ ! -f "$service" ] ; then continue ; fi # in case nothing matches inst=`echo $service | sed -e 's,%{_sysconfdir}/systemd/system/%{groupname}.wants/,,'` - echo found instance $inst - getting status > $output 2>&1 || : + echo found instance $inst - getting status >> $output 2>&1 || : if /bin/systemctl -q is-active $inst ; then - echo instance $inst is running > $output 2>&1 || : + echo instance $inst is running >> $output 2>&1 || : instances="$instances $inst" else - echo instance $inst is not running > $output 2>&1 || : + echo instance $inst is not running >> $output 2>&1 || : fi ninst=`expr $ninst + 1` done if [ $ninst -eq 0 ] ; then - echo no instances to upgrade > $output 2>&1 || : + echo no instances to upgrade >> $output 2>&1 || : exit 0 # have no instances to upgrade - just skip the rest fi # shutdown all instances -echo shutting down all instances . . . > $output 2>&1 || : -/bin/systemctl stop %{groupname} > $output 2>&1 || : -echo remove pid files . . . > $output 2>&1 || : +echo shutting down all instances . . . >> $output 2>&1 || : +for inst in $instances ; do + echo stopping instance $inst >> $output 2>&1 || : + /bin/systemctl stop $inst >> $output 2>&1 || : +done +echo remove pid files . . . >> $output 2>&1 || : /bin/rm -f /var/run/%{pkgname}*.pid /var/run/%{pkgname}*.startpid # do the upgrade -echo upgrading instances . . . > $output 2>&1 || : -%{_sbindir}/setup-ds.pl -l $output -u -s General.UpdateMode=offline > $output 2>&1 || : +echo upgrading instances . . . >> $output 2>&1 || : +DEBUGPOSTSETUPOPT=`/usr/bin/echo $DEBUGPOSTSETUP | /usr/bin/sed -e "s/[^d]//g"` +if [ -n "$DEBUGPOSTSETUPOPT" ] ; then + %{_sbindir}/setup-ds.pl -l $output -$DEBUGPOSTSETUPOPT -u -s General.UpdateMode=offline >> $output 2>&1 || : +else + %{_sbindir}/setup-ds.pl -l $output -u -s General.UpdateMode=offline >> $output 2>&1 || : +fi + # restart instances that require it for inst in $instances ; do - echo restarting instance $inst > $output 2>&1 || : - /bin/systemctl start $inst > $output 2>&1 || : + echo restarting instance $inst >> $output 2>&1 || : + /bin/systemctl start $inst >> $output 2>&1 || : done exit 0 @@ -316,6 +325,10 @@ fi %{_libdir}/%{pkgname}/libns-dshttpd.so* %changelog +* Wed Feb 25 2015 Noriko Hosoi <[email protected]> - 1.3.3.8-2 +- Ticket 48030 - DNS errors after IPA upgrade due to broken ReplSync + Fixes spec file to make sure all the server instances are stopped before upgrade + * Sat Jun 15 2013 Noriko Hosoi <[email protected]> - 1.3.1.2-1 - bump version to 1.3.1.2 - Ticket 47391 - deleting and adding userpassword fails to update the password
0
2f59fa4c73e006af32a402dac503635188a017b4
389ds/389-ds-base
[203214] RHDS fails to start on HP-UX 11.23. Fix Descrition: Stopped using basename and dirname.
commit 2f59fa4c73e006af32a402dac503635188a017b4 Author: Noriko Hosoi <[email protected]> Date: Thu Aug 24 00:03:19 2006 +0000 [203214] RHDS fails to start on HP-UX 11.23. Fix Descrition: Stopped using basename and dirname. diff --git a/ldap/servers/slapd/util.c b/ldap/servers/slapd/util.c index 22e3253d5..f2a4eacb6 100644 --- a/ldap/servers/slapd/util.c +++ b/ldap/servers/slapd/util.c @@ -413,13 +413,18 @@ normalize_path(char *path) char **dp = dirs; char **rdp; do { - bnamep = basename(dnamep); + bnamep = strrchr(dnamep, _CSEP); + if (NULL == bnamep) { + bnamep = dnamep; + } else { + *bnamep = '\0'; + bnamep++; + } if (0 != strcmp(bnamep, ".")) { *dp++ = slapi_ch_strdup(bnamep); /* remove "/./" in the path */ } - dnamep = dirname(dnamep); - } while (strcmp(dnamep, _PSEP) && - !(0 == strcmp(dnamep, ".") && 0 == strcmp(bnamep, "."))); + } while (NULL != dnamep && '\0' != *dnamep && /* done or relative path */ + !(0 == strcmp(dnamep, ".") && 0 == strcmp(bnamep, "."))); /* remove "xxx/.." in the path */ for (dp = dirs, rdp = rdirs; dp && *dp; dp++) { @@ -462,6 +467,7 @@ char * rel2abspath_ext( char *relpath, char *cwd ) { char abspath[ MAXPATHLEN + 1 ]; + char *retpath = NULL; #if defined( _WIN32 ) CHAR szDrive[_MAX_DRIVE]; @@ -512,9 +518,11 @@ rel2abspath_ext( char *relpath, char *cwd ) PL_strcatn( abspath, sizeof(abspath), relpath ); } } + retpath = slapi_ch_strdup(abspath); + /* if there's no '.', no need to call normalize_path */ + if (NULL != strchr(abspath, '.')) { char **norm_path = normalize_path(abspath); - char *retpath = slapi_ch_strdup(abspath); /* size is long enough */ char **np, *rp; int pathlen = strlen(abspath) + 1; int usedlen = 0; @@ -526,8 +534,8 @@ rel2abspath_ext( char *relpath, char *cwd ) usedlen += thislen; } clean_path(norm_path); - return retpath; } + return retpath; }
0
eb6a462b8ed8ddffa29e01178e39d77112dcfe32
389ds/389-ds-base
Ticket 47368 - Fix Jenkins errors Removed some unused variables, fixed a memory leak when removing a nsds4AgmtMaxCSN value, and fixed a bug where if you deleted one agmt, it would remove all the nsds5AgmtMaxCSN attributes. https://fedorahosted.org/389/ticket/47368
commit eb6a462b8ed8ddffa29e01178e39d77112dcfe32 Author: Mark Reynolds <[email protected]> Date: Thu Oct 31 14:49:07 2013 -0400 Ticket 47368 - Fix Jenkins errors Removed some unused variables, fixed a memory leak when removing a nsds4AgmtMaxCSN value, and fixed a bug where if you deleted one agmt, it would remove all the nsds5AgmtMaxCSN attributes. https://fedorahosted.org/389/ticket/47368 diff --git a/ldap/servers/plugins/replication/repl5_agmt.c b/ldap/servers/plugins/replication/repl5_agmt.c index d78f67592..e57c2f4e2 100644 --- a/ldap/servers/plugins/replication/repl5_agmt.c +++ b/ldap/servers/plugins/replication/repl5_agmt.c @@ -2877,7 +2877,6 @@ agmt_set_maxcsn(Repl_Agmt *ra) slapi_pblock_get(pb, SLAPI_PLUGIN_INTOP_RESULT, &rc); if (rc == LDAP_SUCCESS){ - ReplicaId rid; Replica *r; Object *repl_obj; char **maxcsns; @@ -2896,7 +2895,6 @@ agmt_set_maxcsn(Repl_Agmt *ra) if(repl_obj && maxcsns){ r = (Replica *)object_get_data(repl_obj); if(r){ - rid = replica_get_rid(r); /* * Loop over all the agmt maxcsns and find ours */ @@ -3007,7 +3005,6 @@ agmt_remove_maxcsn(Repl_Agmt *ra) * Ok we have the db tombstone entry, start looking through the agmt maxcsns * for a match to this replica agmt. */ - ReplicaId rid; Slapi_Mod smod; LDAPMod *mods[2]; char **maxcsns = NULL; @@ -3025,14 +3022,13 @@ agmt_remove_maxcsn(Repl_Agmt *ra) if(repl_obj && maxcsns){ r = (Replica *)object_get_data(repl_obj); if(r){ - rid = replica_get_rid(r); /* * Loop over all the agmt maxcsns and find ours... */ for(i = 0; maxcsns[i]; i++){ char buf[BUFSIZ]; char unavail_buf[BUFSIZ]; - char *val; + struct berval val; PR_snprintf(buf, BUFSIZ,"%s;%s;%s;%d;",slapi_sdn_get_dn(ra->replarea), slapi_rdn_get_value_by_ref(slapi_rdn_get_rdn(ra->rdn)), @@ -3046,15 +3042,16 @@ agmt_remove_maxcsn(Repl_Agmt *ra) * We found the matching agmt maxcsn, now remove agmt maxcsn * from the tombstone entry. */ - val = maxcsns[i]; - modpb = slapi_pblock_new(); + val.bv_val = maxcsns[i]; + val.bv_len = strlen(maxcsns[i]); slapi_mod_init (&smod, 2); slapi_mod_set_type (&smod, type_agmtMaxCSN); slapi_mod_set_operation (&smod, LDAP_MOD_DELETE | LDAP_MOD_BVALUES); + slapi_mod_add_value(&smod, &val); mods [0] = smod.mod; mods [1] = NULL; - modpb = slapi_pblock_new(); + modpb = slapi_pblock_new(); slapi_modify_internal_set_pb_ext( modpb, tombstone_sdn,
0
b086d41607628635e242a8a80631dfe259fcc75f
389ds/389-ds-base
Ticket 49425 - improve demo objects for install Bug Description: Improve demo objects for install Fix Description: Change the tree a tiny bit - add hidden 389 container, add ous, use better aci examples. This also adds a set of tests to assert the default aci's work as advertised. https://pagure.io/389-ds-base/issue/49425 Author: wibrown Review by: mreynolds, spichugi, tbordaz, lkrispen (Thank you all!)
commit b086d41607628635e242a8a80631dfe259fcc75f Author: William Brown <[email protected]> Date: Wed Jan 10 10:04:39 2018 +1000 Ticket 49425 - improve demo objects for install Bug Description: Improve demo objects for install Fix Description: Change the tree a tiny bit - add hidden 389 container, add ous, use better aci examples. This also adds a set of tests to assert the default aci's work as advertised. https://pagure.io/389-ds-base/issue/49425 Author: wibrown Review by: mreynolds, spichugi, tbordaz, lkrispen (Thank you all!) diff --git a/ldap/schema/30ns-common.ldif b/ldap/schema/30ns-common.ldif index 2b6edc198..80b8cf6fc 100644 --- a/ldap/schema/30ns-common.ldif +++ b/ldap/schema/30ns-common.ldif @@ -54,6 +54,8 @@ attributeTypes: ( nsLogSuppress-oid NAME 'nsLogSuppress' DESC 'Netscape defined attributeTypes: ( nsJarfilename-oid NAME 'nsJarfilename' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 X-ORIGIN 'Netscape' ) attributeTypes: ( nsClassname-oid NAME 'nsClassname' DESC 'Netscape defined attribute type' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 X-ORIGIN 'Netscape' ) attributeTypes: ( 2.16.840.1.113730.3.1.2337 NAME 'nsCertSubjectDN' DESC 'An x509 DN from a certificate used to map during a TLS bind process' SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 X-ORIGIN '389 Directory Server Project' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2342 NAME 'nsSshPublicKey' DESC 'An nsSshPublicKey record' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 X-ORIGIN '389 Directory Server Project' ) +attributeTypes: ( 2.16.840.1.113730.3.1.2343 NAME 'legalName' DESC 'An individuals legalName' EQUALITY caseIgnoreMatch SUBSTR caseIgnoreSubstringsMatch SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE X-ORIGIN '389 Directory Server Project' ) objectClasses: ( nsAdminDomain-oid NAME 'nsAdminDomain' DESC 'Netscape defined objectclass' SUP organizationalUnit MAY ( nsAdminDomainName ) X-ORIGIN 'Netscape' ) objectClasses: ( nsHost-oid NAME 'nsHost' DESC 'Netscape defined objectclass' SUP top MUST ( cn ) MAY ( serverHostName $ description $ l $ nsHostLocation $ nsHardwarePlatform $ nsOsVersion ) X-ORIGIN 'Netscape' ) objectClasses: ( nsAdminGroup-oid NAME 'nsAdminGroup' DESC 'Netscape defined objectclass' SUP top MUST ( cn ) MAY ( nsAdminGroupName $ description $ nsConfigRoot $ nsAdminSIEDN ) X-ORIGIN 'Netscape' ) @@ -65,4 +67,11 @@ objectClasses: ( nsAdminObject-oid NAME 'nsAdminObject' DESC 'Netscape defined o objectClasses: ( nsConfig-oid NAME 'nsConfig' DESC 'Netscape defined objectclass' SUP top MUST ( cn ) MAY ( description $ nsServerPort $ nsServerAddress $ nsSuiteSpotUser $ nsErrorLog $ nsPidLog $ nsAccessLog $ nsDefaultAcceptLanguage $ nsServerSecurity ) X-ORIGIN 'Netscape' ) objectClasses: ( nsDirectoryInfo-oid NAME 'nsDirectoryInfo' DESC 'Netscape defined objectclass' SUP top MUST ( cn ) MAY ( nsBindDN $ nsBindPassword $ nsDirectoryURL $ nsDirectoryFailoverList $ nsDirectoryInfoRef ) X-ORIGIN 'Netscape' ) objectClasses: ( 2.16.840.1.113730.3.2.329 NAME 'nsMemberOf' DESC 'Allow memberOf assignment on groups for nesting and users' SUP top AUXILIARY MAY ( memberOf ) X-ORIGIN '389 Directory Server Project' ) -objectClasses: ( 2.16.840.1.113730.3.2.331 NAME 'nsAccount' DESC 'A representation of a user in a directory server' SUP top AUXILIARY MAY ( userCertificate $ nsCertSubjectDN ) X-ORIGIN '389 Directory Server Project' ) +objectClasses: ( 2.16.840.1.113730.3.2.331 NAME 'nsAccount' DESC 'A representation of a binding user in a directory server' SUP top AUXILIARY MAY ( userCertificate $ nsCertSubjectDN $ nsSshPublicKey $ userPassword ) X-ORIGIN '389 Directory Server Project' ) +objectClasses: ( 2.16.840.1.113730.3.2.333 NAME 'nsPerson' DESC 'A representation of a person in a directory server' SUP top STRUCTURAL MUST ( displayName $ cn ) MAY ( userPassword $ seeAlso $ description $ legalName $ mail $ preferredLanguage ) X-ORIGIN '389 Directory Server Project' ) +objectClasses: ( 2.16.840.1.113730.3.2.334 NAME 'nsOrgPerson' DESC 'A representation of an org person in directory server. See also inetOrgPerson.' SUP top AUXILIARY MAY ( + businessCategory $ carLicense $ departmentNumber $ employeeNumber $ employeeType $ + homePhone $ homePostalAddress $ initials $ jpegPhoto $ labeledURI $ manager $ + mobile $ o $ pager $ photo $ roomNumber $ uid $ userCertificate $ telephoneNumber $ + x500uniqueIdentifier $ userSMIMECertificate $ userPKCS12 ) + X-ORIGIN '389 Directory Server Project' ) diff --git a/src/lib389/lib389/cli_idm/user.py b/src/lib389/lib389/cli_idm/user.py index 70e7148f4..b2f71d9e8 100644 --- a/src/lib389/lib389/cli_idm/user.py +++ b/src/lib389/lib389/cli_idm/user.py @@ -7,7 +7,7 @@ # --- END COPYRIGHT BLOCK --- import argparse -from lib389.idm.user import UserAccount, UserAccounts, MUST_ATTRIBUTES +from lib389.idm.user import nsUserAccount, nsUserAccounts from lib389.cli_base import ( populate_attr_arguments, @@ -22,8 +22,8 @@ from lib389.cli_base import ( _warn, ) -SINGULAR = UserAccount -MANY = UserAccounts +SINGULAR = nsUserAccount +MANY = nsUserAccounts RDN = 'uid' # These are a generic specification, try not to tamper with them @@ -40,7 +40,7 @@ def get_dn(inst, basedn, log, args): _generic_get_dn(inst, basedn, log.getChild('_generic_get_dn'), MANY, dn) def create(inst, basedn, log, args): - kwargs = _get_attributes(args, MUST_ATTRIBUTES) + kwargs = _get_attributes(args, SINGULAR._must_attributes) _generic_create(inst, basedn, log.getChild('_generic_create'), MANY, kwargs) def delete(inst, basedn, log, args, warn=True): @@ -51,7 +51,7 @@ def delete(inst, basedn, log, args, warn=True): def status(inst, basedn, log, args): uid = _get_arg( args.uid, msg="Enter %s to check" % RDN) - uas = UserAccounts(inst, basedn) + uas = MANY(inst, basedn) acct = uas.get(uid) acct_str = "locked: %s" % acct.is_locked() log.info('uid: %s' % uid) @@ -59,14 +59,14 @@ def status(inst, basedn, log, args): def lock(inst, basedn, log, args): uid = _get_arg( args.uid, msg="Enter %s to check" % RDN) - accounts = UserAccounts(inst, basedn) + accounts = MANY(inst, basedn) acct = accounts.get(uid) acct.lock() log.info('locked %s' % uid) def unlock(inst, basedn, log, args): uid = _get_arg( args.uid, msg="Enter %s to check" % RDN) - accounts = UserAccounts(inst, basedn) + accounts = MANY(inst, basedn) acct = accounts.get(uid) acct.unlock() log.info('unlocked %s' % uid) diff --git a/src/lib389/lib389/configurations/__init__.py b/src/lib389/lib389/configurations/__init__.py index c7b90677f..434147a7d 100644 --- a/src/lib389/lib389/configurations/__init__.py +++ b/src/lib389/lib389/configurations/__init__.py @@ -6,20 +6,30 @@ # See LICENSE for details. # --- END COPYRIGHT BLOCK --- +from lib389.utils import ds_is_newer from lib389._constants import INSTALL_LATEST_CONFIG from .config_001003006 import c001003006, c001003006_sample_entries +from .config_001004000 import c001004000, c001004000_sample_entries def get_config(version): - if (version == INSTALL_LATEST_CONFIG): + # We do this to avoid test breaking on older version that may + # not expect the new default layout. + if (version == INSTALL_LATEST_CONFIG and ds_is_newer('1.4.0')): + return c001004000 + elif (version == INSTALL_LATEST_CONFIG): return c001003006 - if (version == '001003006'): + elif (version == '001004000' and ds_is_newer('1.4.0')): + return c001004000 + elif (version == '001003006'): return c001003006 raise Exception('version %s no match' % version) def get_sample_entries(version): if (version == INSTALL_LATEST_CONFIG): - return c001003006_sample_entries - if (version == '001003006'): + return c001004000_sample_entries + elif (version == '001004000'): + return c001004000_sample_entries + elif (version == '001003006'): return c001003006_sample_entries raise Exception('version %s no match' % version) diff --git a/src/lib389/lib389/configurations/config_001004000.py b/src/lib389/lib389/configurations/config_001004000.py new file mode 100644 index 000000000..36b89e95d --- /dev/null +++ b/src/lib389/lib389/configurations/config_001004000.py @@ -0,0 +1,151 @@ +# --- BEGIN COPYRIGHT BLOCK --- +# Copyright (C) 2017 Red Hat, Inc. +# All rights reserved. +# +# License: GPL (version 3 or any later version). +# See LICENSE for details. +# --- END COPYRIGHT BLOCK --- + +from ldap import dn + +from .config import baseconfig, configoperation +from .sample import sampleentries + +from lib389.idm.domain import Domain +from lib389.idm.organisationalunit import OrganisationalUnits +from lib389.idm.group import Groups +from lib389.idm.posixgroup import PosixGroups +from lib389.idm.user import nsUserAccounts +from lib389.idm.services import ServiceAccounts + +from lib389.idm.nscontainer import nsHiddenContainers + +class c001004000_sample_entries(sampleentries): + def __init__(self, instance, basedn): + super(c001004000_sample_entries, self).__init__(instance, basedn) + self.description = """Apply sample entries matching the 1.4.0 sample data and access controls""" + + # All checks done, apply! + def _apply(self): + # Create the base domain object + domain = Domain(self._instance, dn=self._basedn) + # Explode the dn to get the first bit. + avas = dn.str2dn(self._basedn) + dc_ava = avas[0][0][1] + + domain.create(properties={ + # I think in python 2 this forces unicode return ... + 'dc': dc_ava, + 'description': self._basedn, + 'aci': [ + # Allow reading the base domain object + '(targetattr="dc || description || objectClass")(targetfilter="(objectClass=domain)")(version 3.0; acl "Enable anyone domain read"; allow (read, search, compare)(userdn="ldap:///anyone");)', + # Allow reading the ou + '(targetattr="ou || objectClass")(targetfilter="(objectClass=organizationalUnit)")(version 3.0; acl "Enable anyone ou read"; allow (read, search, compare)(userdn="ldap:///anyone");)' + ] + }) + + # Create the 389 service container + # This could also move to be part of core later .... + hidden_containers = nsHiddenContainers(self._instance, self._basedn) + ns389container = hidden_containers.create(properties={ + 'cn': '389_ds_system' + }) + + # Create our ous. + ous = OrganisationalUnits(self._instance, self._basedn) + ous.create(properties = { + 'ou': 'groups', + 'aci': [ + # Allow anon partial read + '(targetattr="cn || member || gidNumber || nsUniqueId || description || objectClass")(targetfilter="(objectClass=groupOfNames)")(version 3.0; acl "Enable anyone group read"; allow (read, search, compare)(userdn="ldap:///anyone");)', + # Allow group_modify to modify but not create groups + '(targetattr="member")(targetfilter="(objectClass=groupOfNames)")(version 3.0; acl "Enable group_modify to alter members"; allow (write)(groupdn="ldap:///cn=group_modify,ou=permissions,{BASEDN}");)'.format(BASEDN=self._basedn), + # Allow group_admin to fully manage groups (posix or not). + '(targetattr="cn || member || gidNumber || description || objectClass")(targetfilter="(objectClass=groupOfNames)")(version 3.0; acl "Enable group_admin to manage groups"; allow (write, add, delete)(groupdn="ldap:///cn=group_admin,ou=permissions,{BASEDN}");)'.format(BASEDN=self._basedn), + ] + }) + + ous.create(properties = { + 'ou': 'people', + 'aci': [ + # allow anon partial read. + '(targetattr="objectClass || description || nsUniqueId || uid || displayName || loginShell || uidNumber || gidNumber || gecos || homeDirectory || cn || memberOf || mail || nsSshPublicKey || nsAccountLock || userCertificate")(targetfilter="(objectClass=posixaccount)")(version 3.0; acl "Enable anyone user read"; allow (read, search, compare)(userdn="ldap:///anyone");)', + # allow self partial mod + '(targetattr="displayName || nsSshPublicKey")(version 3.0; acl "Enable self partial modify"; allow (write)(userdn="ldap:///self");)', + # Allow self full read + '(targetattr="legalName || telephoneNumber || mobile")(targetfilter="(objectClass=nsPerson)")(version 3.0; acl "Enable self legalname read"; allow (read, search, compare)(userdn="ldap:///self");)', + # Allow reading legal name + '(targetattr="legalName || telephoneNumber")(targetfilter="(objectClass=nsPerson)")(version 3.0; acl "Enable user legalname read"; allow (read, search, compare)(groupdn="ldap:///cn=user_private_read,ou=permissions,{BASEDN}");)'.format(BASEDN=self._basedn), + # These below need READ so they can read userPassword and legalName + # Allow user admin create mod + '(targetattr="uid || description || displayName || loginShell || uidNumber || gidNumber || gecos || homeDirectory || cn || memberOf || mail || legalName || telephoneNumber || mobile")(targetfilter="(&(objectClass=nsPerson)(objectClass=nsAccount))")(version 3.0; acl "Enable user admin create"; allow (write, add, delete, read)(groupdn="ldap:///cn=user_admin,ou=permissions,{BASEDN}");)'.format(BASEDN=self._basedn), + # Allow user mod mod only + '(targetattr="uid || description || displayName || loginShell || uidNumber || gidNumber || gecos || homeDirectory || cn || memberOf || mail || legalName || telephoneNumber || mobile")(targetfilter="(&(objectClass=nsPerson)(objectClass=nsAccount))")(version 3.0; acl "Enable user modify to change users"; allow (write, read)(groupdn="ldap:///cn=user_modify,ou=permissions,{BASEDN}");)'.format(BASEDN=self._basedn), + # Allow user_pw_admin to nsaccountlock and password + '(targetattr="userPassword || nsAccountLock || userCertificate || nsSshPublicKey")(targetfilter="(objectClass=nsAccount)")(version 3.0; acl "Enable user password reset"; allow (write, read)(groupdn="ldap:///cn=user_passwd_reset,ou=permissions,{BASEDN}");)'.format(BASEDN=self._basedn), + ] + }) + + ous.create(properties = { + 'ou': 'permissions', + }) + + ous.create(properties = { + 'ou': 'services', + 'aci': [ + # Minimal service read + '(targetattr="objectClass || description || nsUniqueId || cn || memberOf || nsAccountLock ")(targetfilter="(objectClass=netscapeServer)")(version 3.0; acl "Enable anyone service account read"; allow (read, search, compare)(userdn="ldap:///anyone");)', + ] + }) + + # Create the demo user + users = nsUserAccounts(self._instance, self._basedn) + users.create(properties={ + 'uid': 'demo_user', + 'cn': 'Demo User', + 'displayName': 'Demo User', + 'legalName': 'Demo User Name', + 'uidNumber': '99998', + 'gidNumber': '99998', + 'homeDirectory': '/var/empty', + 'loginShell': '/bin/false', + 'nsAccountlock': 'true' + }) + + # Create the demo group + groups = PosixGroups(self._instance, self._basedn) + groups.create(properties={ + 'cn' : 'demo_group', + 'gidNumber': '99999' + }) + + # Create the permission groups required for the acis + permissions = Groups(self._instance, self._basedn, rdn='ou=permissions') + permissions.create(properties={ + 'cn': 'group_admin', + }) + permissions.create(properties={ + 'cn': 'group_modify', + }) + permissions.create(properties={ + 'cn': 'user_admin', + }) + permissions.create(properties={ + 'cn': 'user_modify', + }) + permissions.create(properties={ + 'cn': 'user_passwd_reset', + }) + permissions.create(properties={ + 'cn': 'user_private_read', + }) + + +class c001004000(baseconfig): + def __init__(self, instance): + super(c001004000, self).__init__(instance) + self._operations = [ + # For now this is an empty place holder - likely this + # will become part of core server. + ] diff --git a/src/lib389/lib389/idm/account.py b/src/lib389/lib389/idm/account.py index 92038bffe..100bfec53 100644 --- a/src/lib389/lib389/idm/account.py +++ b/src/lib389/lib389/idm/account.py @@ -93,6 +93,22 @@ class Account(DSLdapObject): inst_clone.open(saslmethod='gssapi') return inst_clone + def enroll_certificate(self, der_path): + """Enroll a certificate for certmap verification. Because of the userCertificate + attribute, we have to do this on userAccount which has support for it. + + :param der_path: the certificate file in DER format to include. + :type der_path: str + """ + if ds_is_older('1.4.0'): + raise Exception("This version of DS does not support nsAccount") + # Given a cert path, add this to the object as a userCertificate + crt = None + with open(der_path, 'rb') as f: + crt = f.read() + self.add('usercertificate;binary', crt) + + class Accounts(DSLdapObjects): """DSLdapObjects that represents Account entry @@ -106,9 +122,12 @@ class Accounts(DSLdapObjects): super(Accounts, self).__init__(instance) # These are all the objects capable of holding a password. self._objectclasses = [ + 'nsAccount', + 'nsPerson', 'simpleSecurityObject', 'organization', - 'personperson', + 'person', + 'account', 'organizationalUnit', 'netscapeServer', 'domain', diff --git a/src/lib389/lib389/idm/user.py b/src/lib389/lib389/idm/user.py index c4d792877..38977a5fe 100644 --- a/src/lib389/lib389/idm/user.py +++ b/src/lib389/lib389/idm/user.py @@ -30,10 +30,89 @@ TEST_USER_PROPERTIES = { 'homeDirectory' : '/home/testuser' } +#### Modern userAccounts + +class nsUserAccount(Account): + _must_attributes = [ + 'uid', + 'cn', + 'displayName', + 'uidNumber', + 'gidNumber', + 'homeDirectory', + ] + + """A single instance of an nsPerson, capable of posix login, certificate + authentication, sshkey distribution, and more. + + This is the modern and correct userAccount type to choose for DS 1.4.0 and above. + + :param instance: An instance + :type instance: lib389.DirSrv + :param dn: Entry DN + :type dn: str + """ + def __init__(self, instance, dn=None): + if ds_is_older('1.4.0'): + raise Exception("Not supported") + super(nsUserAccount, self).__init__(instance, dn) + self._rdn_attribute = RDN + self._must_attributes = nsUserAccount._must_attributes + # Can I generate these from schema? + self._create_objectclasses = [ + 'top', + 'nsPerson', + 'nsAccount', + 'nsOrgPerson', + 'posixAccount', + ] + user_compare_exclude = [ + 'nsUniqueId', + 'modifyTimestamp', + 'createTimestamp', + 'entrydn' + ] + self._compare_exclude = self._compare_exclude + user_compare_exclude + self._protected = False + +class nsUserAccounts(DSLdapObjects): + """DSLdapObjects that represents all nsUserAccount entries in suffix. + By default it uses 'ou=People' as rdn. + + This is the modern and correct userAccount type to choose for DS 1.4.0 and above. + + :param instance: An instance + :type instance: lib389.DirSrv + :param basedn: Suffix DN + :type basedn: str + :param rdn: The DN that will be combined wit basedn + :type rdn: str + """ + + def __init__(self, instance, basedn, rdn='ou=people'): + super(nsUserAccounts, self).__init__(instance) + self._objectclasses = [ + 'nsPerson', + 'nsAccount', + 'nsOrgPerson', + 'posixAccount', + ] + self._filterattrs = [RDN, 'displayName', 'cn'] + self._childobject = nsUserAccount + if rdn is None: + self._basedn = basedn + else: + self._basedn = '{},{}'.format(rdn, basedn) + + +#### Traditional style userAccounts. class UserAccount(Account): """A single instance of User Account entry + This is the classic "user account" style of cn + sn. You should consider + nsUserAccount instead. + :param instance: An instance :type instance: lib389.DirSrv :param dn: Entry DN @@ -49,12 +128,8 @@ class UserAccount(Account): 'top', 'account', 'posixaccount', - # inetOrgPerson allows userCertificate 'inetOrgPerson', 'organizationalPerson', - # This may not always work at sites? - # Can we get this into core? - # 'ldapPublicKey', ] if ds_is_older('1.3.7'): self._create_objectclasses.append('inetUser') @@ -77,29 +152,14 @@ class UserAccount(Account): return super(UserAccount, self)._validate(rdn, properties, basedn) - def enroll_certificate(self, der_path): - """Enroll a certificate for certmap verification. Because of the userCertificate - attribute, we have to do this on userAccount which has support for it. - - :param der_path: the certificate file in DER format to include. - :type der_path: str - """ - if ds_is_older('1.4.0'): - raise Exception("This version of DS does not support nsAccount") - # Given a cert path, add this to the object as a userCertificate - crt = None - with open(der_path, 'rb') as f: - crt = f.read() - self.add('usercertificate;binary', crt) - - # Add a set password function.... - # Can't I actually just set, and it will hash? - class UserAccounts(DSLdapObjects): """DSLdapObjects that represents all User Account entries in suffix. By default it uses 'ou=People' as rdn. + This is the classic "user account" style of cn + sn. You should consider + nsUserAccounts instead. + :param instance: An instance :type instance: lib389.DirSrv :param basedn: Suffix DN diff --git a/src/lib389/lib389/tests/cli/idm_user_test.py b/src/lib389/lib389/tests/cli/idm_user_test.py index da579b4d0..537e12d16 100644 --- a/src/lib389/lib389/tests/cli/idm_user_test.py +++ b/src/lib389/lib389/tests/cli/idm_user_test.py @@ -44,9 +44,10 @@ def test_user_tasks(topology): # Create the user topology.logcap.flush() - u_args.cn = 'testuser' u_args.uid = 'testuser' - u_args.sn = 'testuser' + # u_args.sn = 'testuser' + u_args.cn = 'Test User' + u_args.displayName = 'Test User' u_args.homeDirectory = '/home/testuser' u_args.uidNumber = '5000' u_args.gidNumber = '5000' diff --git a/src/lib389/lib389/tests/configurations/config_001004000_test.py b/src/lib389/lib389/tests/configurations/config_001004000_test.py new file mode 100644 index 000000000..0cb31ab35 --- /dev/null +++ b/src/lib389/lib389/tests/configurations/config_001004000_test.py @@ -0,0 +1,231 @@ +# --- BEGIN COPYRIGHT BLOCK --- +# Copyright (C) 2017 Red Hat, Inc. +# All rights reserved. +# +# License: GPL (version 3 or any later version). +# See LICENSE for details. +# --- END COPYRIGHT BLOCK --- +# +import ldap + +import logging +import sys +import time + +import pytest + +from lib389 import DirSrv +from lib389._constants import * +from lib389.properties import * + +from lib389.topologies import topology_st + +from lib389.idm.user import nsUserAccounts +from lib389.idm.posixgroup import PosixGroups +from lib389.idm.group import Groups + +from lib389.utils import ds_is_older +pytestmark = pytest.mark.skipif(ds_is_older('1.4.0'), reason="Not implemented") + +REQUIRED_DNS = [ + 'dc=example,dc=com', + 'ou=groups,dc=example,dc=com', + 'ou=people,dc=example,dc=com', + 'ou=services,dc=example,dc=com', + 'ou=permissions,dc=example,dc=com', + 'uid=demo_user,ou=people,dc=example,dc=com', + 'cn=demo_group,ou=groups,dc=example,dc=com', + 'cn=group_admin,ou=permissions,dc=example,dc=com', + 'cn=group_modify,ou=permissions,dc=example,dc=com', + 'cn=user_admin,ou=permissions,dc=example,dc=com', + 'cn=user_modify,ou=permissions,dc=example,dc=com', + 'cn=user_passwd_reset,ou=permissions,dc=example,dc=com', + 'cn=user_private_read,ou=permissions,dc=example,dc=com', +] + +def test_install_sample_entries(topology_st): + """Assert that our entries match.""" + + entries = topology_st.standalone.search_s(DEFAULT_SUFFIX, ldap.SCOPE_SUBTREE) + + for entry in entries: + assert(entry.dn in REQUIRED_DNS) + # We can make this assert the full object content, plugins and more later. + +def test_install_aci(topology_st): + """Assert our default aci's work as expected.""" + + # Create some users and groups. + users = nsUserAccounts(topology_st.standalone, DEFAULT_SUFFIX) + groups = PosixGroups(topology_st.standalone, DEFAULT_SUFFIX) + + user_basic = users.create(properties={ + 'uid': 'basic', + 'cn': 'Basic', + 'displayName': 'Basic', + 'uidNumber': '100000', + 'gidNumber': '100000', + 'homeDirectory': '/home/basic', + 'userPassword': 'password', + 'legalName': 'Super Secret PII', + }) + + user_modify = users.create(properties={ + 'uid': 'modify', + 'cn': 'Modify', + 'displayName': 'Modify', + 'uidNumber': '100001', + 'gidNumber': '100001', + 'homeDirectory': '/home/modify', + 'userPassword': 'password', + 'legalName': 'Super Secret PII', + }) + + user_admin = users.create(properties={ + 'uid': 'admin', + 'cn': 'Admin', + 'displayName': 'Admin', + 'uidNumber': '100002', + 'gidNumber': '100002', + 'homeDirectory': '/home/admin', + 'userPassword': 'password', + 'legalName': 'Super Secret PII', + }) + + user_pw_reset = users.create(properties={ + 'uid': 'pw_reset', + 'cn': 'Password Reset', + 'displayName': 'Password Reset', + 'uidNumber': '100003', + 'gidNumber': '100003', + 'homeDirectory': '/home/pw_reset', + 'userPassword': 'password', + 'legalName': 'Super Secret PII', + }) + + # Add users to various permissions. + + permissions = Groups(topology_st.standalone, DEFAULT_SUFFIX, rdn='ou=permissions') + + g_group_admin = permissions.get('group_admin') + g_group_modify = permissions.get('group_modify') + g_user_admin = permissions.get('user_admin') + g_user_modify = permissions.get('user_modify') + g_user_pw_reset = permissions.get('user_passwd_reset') + + g_group_admin.add_member(user_admin.dn) + g_user_admin.add_member(user_admin.dn) + + g_group_modify.add_member(user_modify.dn) + g_user_modify.add_member(user_modify.dn) + + g_user_pw_reset.add_member(user_pw_reset.dn) + + # Bind as a user and assert what we can and can not see + c_user_basic = user_basic.bind(password='password') + c_user_modify = user_modify.bind(password='password') + c_user_admin = user_admin.bind(password='password') + c_user_pw_reset = user_pw_reset.bind(password='password') + + c_user_basic_users = nsUserAccounts(c_user_basic, DEFAULT_SUFFIX) + c_user_pw_reset_users = nsUserAccounts(c_user_pw_reset, DEFAULT_SUFFIX) + c_user_modify_users = nsUserAccounts(c_user_modify, DEFAULT_SUFFIX) + c_user_admin_users = nsUserAccounts(c_user_admin, DEFAULT_SUFFIX) + + # Should be able to see users, but not their legalNames + user_basic_view_demo_user = c_user_basic_users.get('demo_user') + assert user_basic_view_demo_user.get_attr_val_utf8('legalName') is None + assert user_basic_view_demo_user.get_attr_val_utf8('uid') == 'demo_user' + + with pytest.raises(ldap.INSUFFICIENT_ACCESS): + user_basic_view_demo_user.replace('description', 'change value') + + user_pw_reset_view_demo_user = c_user_pw_reset_users.get('demo_user') + assert user_pw_reset_view_demo_user.get_attr_val_utf8('legalName') is None + assert user_pw_reset_view_demo_user.get_attr_val_utf8('uid') == 'demo_user' + + with pytest.raises(ldap.INSUFFICIENT_ACCESS): + user_pw_reset_view_demo_user.replace('description', 'change value') + + # The user admin and modify should be able to read it. + user_modify_view_demo_user = c_user_modify_users.get('demo_user') + assert user_modify_view_demo_user.get_attr_val_utf8('legalName') == 'Demo User Name' + assert user_modify_view_demo_user.get_attr_val_utf8('uid') == 'demo_user' + user_modify_view_demo_user.replace('description', 'change value') + + user_admin_view_demo_user = c_user_admin_users.get('demo_user') + assert user_admin_view_demo_user.get_attr_val_utf8('legalName') == 'Demo User Name' + assert user_admin_view_demo_user.get_attr_val_utf8('uid') == 'demo_user' + user_admin_view_demo_user.replace('description', 'change value') + + # Assert only admin can create: + + test_user_properties = { + 'uid': 'test_user', + 'cn': 'Test User', + 'displayName': 'Test User', + 'uidNumber': '100005', + 'gidNumber': '100005', + 'homeDirectory': '/home/test_user', + 'legalName': 'Super Secret PII', + } + + with pytest.raises(ldap.INSUFFICIENT_ACCESS): + c_user_basic_users.create(properties=test_user_properties) + with pytest.raises(ldap.INSUFFICIENT_ACCESS): + c_user_pw_reset_users.create(properties=test_user_properties) + with pytest.raises(ldap.INSUFFICIENT_ACCESS): + c_user_modify_users.create(properties=test_user_properties) + + test_user = c_user_admin_users.create(properties=test_user_properties) + test_user.delete() + + # Assert on pw_reset can unlock/pw + + with pytest.raises(ldap.INSUFFICIENT_ACCESS): + user_basic_view_demo_user.lock() + with pytest.raises(ldap.INSUFFICIENT_ACCESS): + user_modify_view_demo_user.lock() + with pytest.raises(ldap.INSUFFICIENT_ACCESS): + user_admin_view_demo_user.lock() + user_pw_reset_view_demo_user.lock() + + # Group test + c_user_basic_groups = PosixGroups(c_user_basic, DEFAULT_SUFFIX) + c_user_pw_reset_groups = PosixGroups(c_user_pw_reset, DEFAULT_SUFFIX) + c_user_modify_groups = PosixGroups(c_user_modify, DEFAULT_SUFFIX) + c_user_admin_groups = PosixGroups(c_user_admin, DEFAULT_SUFFIX) + + # Assert that members can be read, but only modify/admin can edit. + user_basic_view_demo_group = c_user_basic_groups.get('demo_group') + assert user_basic_view_demo_group.get_attr_val_utf8('cn') == 'demo_group' + with pytest.raises(ldap.INSUFFICIENT_ACCESS): + user_basic_view_demo_group.add_member(user_basic.dn) + + user_pw_reset_view_demo_group = c_user_pw_reset_groups.get('demo_group') + assert user_pw_reset_view_demo_group.get_attr_val_utf8('cn') == 'demo_group' + with pytest.raises(ldap.INSUFFICIENT_ACCESS): + user_pw_reset_view_demo_group.add_member(user_pw_reset.dn) + + user_modify_view_demo_group = c_user_modify_groups.get('demo_group') + assert user_modify_view_demo_group.get_attr_val_utf8('cn') == 'demo_group' + user_modify_view_demo_group.add_member(user_modify.dn) + + user_admin_view_demo_group = c_user_admin_groups.get('demo_group') + assert user_admin_view_demo_group.get_attr_val_utf8('cn') == 'demo_group' + user_admin_view_demo_group.add_member(user_admin.dn) + + # Assert that only admin can add new group. + group_properties = { + 'cn': 'test_group', + 'gidNumber': '100009' + } + + with pytest.raises(ldap.INSUFFICIENT_ACCESS): + c_user_basic_groups.create(properties=group_properties) + with pytest.raises(ldap.INSUFFICIENT_ACCESS): + c_user_pw_reset_groups.create(properties=group_properties) + with pytest.raises(ldap.INSUFFICIENT_ACCESS): + c_user_modify_groups.create(properties=group_properties) + c_user_admin_groups.create(properties=group_properties) +
0
4c6319c3d44e1a7d356500a607b6252e8f43c0a1
389ds/389-ds-base
Ticket 48303 - Fix lib389 broken tests - backend_test Description: Fix the imports to the correct ones. Add Red Hat copyright block. Remove "Created on" block, because git contains this information. Add a logging. Add docstrings to the all tests. Divide the delete test case into two: for valid and invalid cases. Fix expected exception assertions within the create and the delete_invalid test cases. Add assert statement to the toSuffix test case. Refactore code to the pytest compatibility. https://fedorahosted.org/389/ticket/48303 Review by: mreynolds (Thanks!)
commit 4c6319c3d44e1a7d356500a607b6252e8f43c0a1 Author: Simon Pichugin <[email protected]> Date: Fri Oct 9 18:12:09 2015 +0200 Ticket 48303 - Fix lib389 broken tests - backend_test Description: Fix the imports to the correct ones. Add Red Hat copyright block. Remove "Created on" block, because git contains this information. Add a logging. Add docstrings to the all tests. Divide the delete test case into two: for valid and invalid cases. Fix expected exception assertions within the create and the delete_invalid test cases. Add assert statement to the toSuffix test case. Refactore code to the pytest compatibility. https://fedorahosted.org/389/ticket/48303 Review by: mreynolds (Thanks!) diff --git a/src/lib389/tests/backend_test.py b/src/lib389/tests/backend_test.py index b4345c0ad..7924cf705 100644 --- a/src/lib389/tests/backend_test.py +++ b/src/lib389/tests/backend_test.py @@ -1,22 +1,25 @@ -''' -Created on Dec 17, 2013 - -@author: tbordaz -''' +# --- BEGIN COPYRIGHT BLOCK --- +# Copyright (C) 2015 Red Hat, Inc. +# All rights reserved. +# +# License: GPL (version 3 or any later version). +# See LICENSE for details. +# --- END COPYRIGHT BLOCK --- +# import os -import pwd -import ldap -from random import randint -from lib389.tools import DirSrvTools +import pytest +import logging + from lib389._constants import * from lib389.properties import * -from lib389 import DirSrv,Entry, InvalidArgumentError +from lib389 import DirSrv, InvalidArgumentError, UnwillingToPerformError +logging.getLogger(__name__).setLevel(logging.DEBUG) +log = logging.getLogger(__name__) TEST_REPL_DN = "uid=test,%s" % DEFAULT_SUFFIX INSTANCE_PORT = 54321 INSTANCE_SERVERID = 'dirsrv' -#INSTANCE_PREFIX = os.environ.get('PREFIX', None) INSTANCE_PREFIX = None INSTANCE_BACKUP = os.environ.get('BACKUPDIR', DEFAULT_BACKUPDIR) NEW_SUFFIX_1 = 'o=test_create' @@ -28,202 +31,225 @@ NEW_BACKEND_2 = 'test_bis_createdb' NEW_CHILDSUFFIX_2 = 'o=child2,o=test_bis_create' NEW_CHILDBACKEND_2 = 'test_bis_createchilddb' -class Test_Backend(object): - - - def setUp(self): - instance = DirSrv(verbose=False) - instance.log.debug("Instance allocated") - args = {SER_HOST: LOCALHOST, - SER_PORT: INSTANCE_PORT, - SER_DEPLOYED_DIR: INSTANCE_PREFIX, - SER_SERVERID_PROP: INSTANCE_SERVERID - } - instance.allocate(args) - if instance.exists(): - instance.delete() - instance.create() - instance.open() - self.instance = instance - - - def tearDown(self): - if self.instance.exists(): - self.instance.delete() - - - def test_list(self): - ents = self.instance.backend.list() - nb_backend = len(ents) - for ent in ents: - self.instance.log.info("List(%d): backend %s" % (nb_backend, ent.dn)) - - # Create a first backend and check list all backends - backendEntry = self.instance.backend.create(suffix=NEW_SUFFIX_1, properties={BACKEND_NAME: NEW_BACKEND_1}) - ents = self.instance.backend.list() - for ent in ents: - self.instance.log.info("List(%d): backend %s" % (nb_backend + 1, ent.dn)) - assert len(ents) == (nb_backend + 1) - - # Create a second backend and check list all backends - backendEntry = self.instance.backend.create(suffix=NEW_SUFFIX_2, properties={BACKEND_NAME: NEW_BACKEND_2}) - ents = self.instance.backend.list() - for ent in ents: - self.instance.log.info("List(%d): backend %s" % (nb_backend + 2, ent.dn)) - assert len(ents) == (nb_backend + 2) - - # Check list a backend per suffix - ents = self.instance.backend.list(suffix=NEW_SUFFIX_1) - for ent in ents: - self.instance.log.info("List suffix (%d): backend %s" % (1, ent.dn)) - assert len(ents) == 1 - - # Check list a backend by its name - ents = self.instance.backend.list(bename=NEW_BACKEND_2) - for ent in ents: - self.instance.log.info("List name (%d): backend %s" % (1, ent.dn)) + +class TopologyStandalone(object): + def __init__(self, standalone): + standalone.open() + self.standalone = standalone + + [email protected](scope="module") +def topology(request): + standalone = DirSrv(verbose=False) + standalone.log.debug("Instance allocated") + args = {SER_HOST: LOCALHOST, + SER_PORT: INSTANCE_PORT, + SER_DEPLOYED_DIR: INSTANCE_PREFIX, + SER_SERVERID_PROP: INSTANCE_SERVERID} + standalone.allocate(args) + if standalone.exists(): + standalone.delete() + standalone.create() + standalone.open() + + def fin(): + standalone.delete() + request.addfinalizer(fin) + + return TopologyStandalone(standalone) + + +def test_list(topology): + """Test backend.list() function behaviour after: + - creating new suffixes + - filter with suffix + - filter with backend name (bename) + - filter with backend dn + - filter with invalid suffix/bename + """ + + ents = topology.standalone.backend.list() + nb_backend = len(ents) + for ent in ents: + topology.standalone.log.info("List(%d): backend %s" % (nb_backend, ent.dn)) + + log.info("Create a first backend and check list all backends") + topology.standalone.backend.create(suffix=NEW_SUFFIX_1, + properties={BACKEND_NAME: NEW_BACKEND_1}) + ents = topology.standalone.backend.list() + for ent in ents: + topology.standalone.log.info("List(%d): backend %s" % (nb_backend + 1, ent.dn)) + assert len(ents) == (nb_backend + 1) + + log.info("Create a second backend and check list all backends") + topology.standalone.backend.create(suffix=NEW_SUFFIX_2, + properties={BACKEND_NAME: NEW_BACKEND_2}) + ents = topology.standalone.backend.list() + for ent in ents: + topology.standalone.log.info("List(%d): backend %s" % (nb_backend + 2, ent.dn)) + assert len(ents) == (nb_backend + 2) + + log.info("Check list a backend per suffix") + ents = topology.standalone.backend.list(suffix=NEW_SUFFIX_1) + for ent in ents: + topology.standalone.log.info("List suffix (%d): backend %s" % (1, ent.dn)) + assert len(ents) == 1 + + log.info("Check list a backend by its name") + ents = topology.standalone.backend.list(bename=NEW_BACKEND_2) + for ent in ents: + topology.standalone.log.info("List name (%d): backend %s" % (1, ent.dn)) + assert len(ents) == 1 + + log.info("Check list backends by their DN") + all = topology.standalone.backend.list() + for ent in all: + ents = topology.standalone.backend.list(backend_dn=ent.dn) + for bck in ents: + topology.standalone.log.info("List DN (%d): backend %s" % (1, bck.dn)) assert len(ents) == 1 - - # Check list backends by their DN - all = self.instance.backend.list() - for ent in all: - ents = self.instance.backend.list(backend_dn=ent.dn) - for bck in ents: - self.instance.log.info("List DN (%d): backend %s" % (1, bck.dn)) - assert len(ents) == 1 - - # Check list with valid backend DN but invalid suffix/bename - all = self.instance.backend.list() - for ent in all: - ents = self.instance.backend.list(suffix="o=dummy", backend_dn=ent.dn, bename="dummydb") - for bck in ents: - self.instance.log.info("List invalid suffix+bename (%d): backend %s" % (1, bck.dn)) - assert len(ents) == 1 - - def test_create(self): - # just to make it clean before starting - self.instance.backend.delete(suffix=NEW_SUFFIX_1) - self.instance.backend.delete(suffix=NEW_SUFFIX_2) - - # create a backend - backendEntry = self.instance.backend.create(suffix=NEW_SUFFIX_1, properties={BACKEND_NAME: NEW_BACKEND_1}) - - # check missing suffix - try: - backendEntry = self.instance.backend.create() - assert backendEntry == None - except Exception as e: - self.instance.log.info('Fail to create (expected)%s: %s' % (type(e).__name__,e.args)) - pass - - # check already existing backend for that suffix - try: - backendEntry = self.instance.backend.create(suffix=NEW_SUFFIX_1) - assert backendEntry == None - except Exception as e: - self.instance.log.info('Fail to create (expected)%s: %s' % (type(e).__name__, e.args)) - pass - - # check already existing backend DN, create for a different suffix but same backend name - try: - backendEntry = self.instance.backend.create(suffix=NEW_SUFFIX_2, properties={BACKEND_NAME: NEW_BACKEND_1}) - assert backendEntry == None - except Exception as e: - self.instance.log.info('Fail to create (expected)%s: %s' % (type(e).__name__, e.args)) - pass - - # create a backend without properties - backendEntry = self.instance.backend.create(suffix=NEW_SUFFIX_2) - ents = self.instance.backend.list() - for ent in ents: - self.instance.log.info("List: backend %s" % (ent.dn)) - - - def test_delete(self): - # just to make it clean before starting - self.instance.backend.delete(suffix=NEW_SUFFIX_1) - self.instance.backend.delete(suffix=NEW_SUFFIX_2) - ents = self.instance.backend.list() - nb_backend = len(ents) - - # Check the various possibility to delete a backend - # First with suffix - backendEntry = self.instance.backend.create(suffix=NEW_SUFFIX_1, properties={BACKEND_NAME: NEW_BACKEND_1}) - self.instance.backend.delete(suffix=NEW_SUFFIX_1) - ents = self.instance.backend.list() - assert len(ents) == nb_backend - - # Second with backend name - backendEntry = self.instance.backend.create(suffix=NEW_SUFFIX_1, properties={BACKEND_NAME: NEW_BACKEND_1}) - self.instance.backend.delete(bename=NEW_BACKEND_1) - ents = self.instance.backend.list() - assert len(ents) == nb_backend - - # Third with backend DN - backendEntry = self.instance.backend.create(suffix=NEW_SUFFIX_1, properties={BACKEND_NAME: NEW_BACKEND_1}) - ents = self.instance.backend.list(suffix=NEW_SUFFIX_1) + + log.info("Check list with valid backend DN but invalid suffix/bename") + all = topology.standalone.backend.list() + for ent in all: + ents = topology.standalone.backend.list(suffix="o=dummy", backend_dn=ent.dn, bename="dummydb") + for bck in ents: + topology.standalone.log.info("List invalid suffix+bename (%d): backend %s" % (1, bck.dn)) assert len(ents) == 1 - self.instance.backend.delete(backend_dn=ents[0].dn) - ents = self.instance.backend.list() - assert len(ents) == nb_backend - - # Now check the failure cases - # First no argument -> InvalidArgumentError - try: - backendEntry = self.instance.backend.create(suffix=NEW_SUFFIX_1, properties={BACKEND_NAME: NEW_BACKEND_1}) - self.instance.backend.delete() - except Exception as e: - self.instance.log.info('Fail to delete (expected)%s: %s' % (type(e).__name__,e.args)) - self.instance.backend.delete(suffix=NEW_SUFFIX_1) - pass - - # second invalid suffix -> InvalidArgumentError - try: - self.instance.backend.delete(suffix=NEW_SUFFIX_2) - except Exception as e: - self.instance.log.info('Fail to delete (expected)%s: %s' % (type(e).__name__,e.args)) - pass - - # existing a mapping tree -> UnwillingToPerformError - backendEntry = self.instance.backend.create(suffix=NEW_SUFFIX_1, properties={BACKEND_NAME: NEW_BACKEND_1}) - self.instance.mappingtree.create(NEW_SUFFIX_1, bename=NEW_BACKEND_1) - try: - self.instance.backend.delete(suffix=NEW_SUFFIX_1) - except Exception as e: - self.instance.log.info('Fail to delete (expected)%s: %s' % (type(e).__name__,e.args)) - self.instance.mappingtree.delete(suffix=NEW_SUFFIX_1,bename=NEW_BACKEND_1) - self.instance.backend.delete(suffix=NEW_SUFFIX_1) - - # backend name differs -> UnwillingToPerformError - backendEntry = self.instance.backend.create(suffix=NEW_SUFFIX_1, properties={BACKEND_NAME: NEW_BACKEND_1}) - try: - self.instance.backend.delete(suffix=NEW_SUFFIX_1, bename='dummydb') - except Exception as e: - self.instance.log.info('Fail to delete (expected)%s: %s' % (type(e).__name__,e.args)) - self.instance.backend.delete(suffix=NEW_SUFFIX_1) - - def test_toSuffix(self): - backendEntry = self.instance.backend.create(suffix=NEW_SUFFIX_1, properties={BACKEND_NAME: NEW_BACKEND_1}) - self.instance.mappingtree.create(NEW_SUFFIX_1, bename=NEW_BACKEND_1) - - ents = self.instance.backend.list() - for ent in ents: - suffix = ent.getValues(BACKEND_PROPNAME_TO_ATTRNAME[BACKEND_SUFFIX]) - values = self.instance.backend.toSuffix(name=ent.dn) - if not suffix[0] in values: - self.instance.log.info("Fail we do not retrieve the suffix %s in %s" % (suffix[0], values)) - else: - self.instance.log.info("%s retrieved" % suffix) - - + + log.info("Just to make it clean in the end") + topology.standalone.backend.delete(suffix=NEW_SUFFIX_1) + topology.standalone.backend.delete(suffix=NEW_SUFFIX_2) + + +def test_create(topology): + """Test backend.create() function with: + - specifying no suffix + - specifying already existing backend suffix + - specifying already existing backend name, but new suffix + - specifying no properties + """ + + log.info("Create a backend") + topology.standalone.backend.create(suffix=NEW_SUFFIX_1, + properties={BACKEND_NAME: NEW_BACKEND_1}) + + log.info("Check behaviour with missing suffix") + with pytest.raises(ValueError) as excinfo: + topology.standalone.backend.create() + assert 'suffix is mandatory' in str(excinfo.value) + + log.info("Check behaviour with already existing backend for that suffix") + with pytest.raises(InvalidArgumentError) as excinfo: + topology.standalone.backend.create(suffix=NEW_SUFFIX_1) + assert 'It already exists backend(s)' in str(excinfo.value) + + log.info("Check behaviour with already existing backend DN, but new suffix") + with pytest.raises(InvalidArgumentError) as excinfo: + topology.standalone.backend.create(suffix=NEW_SUFFIX_2, + properties={BACKEND_NAME: NEW_BACKEND_1}) + assert 'It already exists a backend with that DN' in str(excinfo.value) + + log.info("Create a backend without properties") + topology.standalone.backend.create(suffix=NEW_SUFFIX_2) + ents = topology.standalone.backend.list(suffix=NEW_SUFFIX_2) + assert len(ents) == 1 + + log.info("Just to make it clean in the end") + topology.standalone.backend.delete(suffix=NEW_SUFFIX_1) + topology.standalone.backend.delete(suffix=NEW_SUFFIX_2) + + +def test_delete_valid(topology): + """Test the various possibilities to delete a backend: + - with suffix + - with backend name + - with backend DN + """ + + ents = topology.standalone.backend.list() + nb_backend = len(ents) + + log.info("Try to delete a backend with suffix") + topology.standalone.backend.create(suffix=NEW_SUFFIX_1, + properties={BACKEND_NAME: NEW_BACKEND_1}) + topology.standalone.backend.delete(suffix=NEW_SUFFIX_1) + ents = topology.standalone.backend.list() + assert len(ents) == nb_backend + + log.info("Try to delete a backend with backend name") + topology.standalone.backend.create(suffix=NEW_SUFFIX_1, + properties={BACKEND_NAME: NEW_BACKEND_1}) + topology.standalone.backend.delete(bename=NEW_BACKEND_1) + ents = topology.standalone.backend.list() + assert len(ents) == nb_backend + + log.info("Try to delete a backend with backend DN") + topology.standalone.backend.create(suffix=NEW_SUFFIX_1, + properties={BACKEND_NAME: NEW_BACKEND_1}) + ents = topology.standalone.backend.list(suffix=NEW_SUFFIX_1) + assert len(ents) == 1 + topology.standalone.backend.delete(backend_dn=ents[0].dn) + ents = topology.standalone.backend.list() + assert len(ents) == nb_backend + + +def test_delete_invalid(topology): + """Test the invalid situations with the backend removal: + - no argument + - invalid suffix + - existing a mapping tree + - backend name differs + """ + + topology.standalone.backend.create(suffix=NEW_SUFFIX_1, + properties={BACKEND_NAME: NEW_BACKEND_1}) + topology.standalone.mappingtree.create(NEW_SUFFIX_1, bename=NEW_BACKEND_1) + + log.info("First no argument -> InvalidArgumentError") + with pytest.raises(InvalidArgumentError) as excinfo: + topology.standalone.backend.delete() + assert 'suffix and backend DN and backend name are missing' in str(excinfo.value) + + log.info("Second invalid suffix -> InvalidArgumentError") + with pytest.raises(InvalidArgumentError) as excinfo: + topology.standalone.backend.delete(suffix=NEW_SUFFIX_2) + assert 'Unable to retrieve the backend' in str(excinfo.value) + + log.info("Existing a mapping tree -> UnwillingToPerformError") + with pytest.raises(UnwillingToPerformError) as excinfo: + topology.standalone.backend.delete(suffix=NEW_SUFFIX_1) + assert 'It still exists a mapping tree' in str(excinfo.value) + topology.standalone.mappingtree.delete(suffix=NEW_SUFFIX_1, bename=NEW_BACKEND_1) + + log.info("Backend name differs -> UnwillingToPerformError") + with pytest.raises(UnwillingToPerformError) as excinfo: + topology.standalone.backend.delete(suffix=NEW_SUFFIX_1, bename='dummydb') + assert 'Backend name specified (dummydb) differs from' in str(excinfo.value) + topology.standalone.backend.delete(suffix=NEW_SUFFIX_1) + + +def test_toSuffix(topology): + """Test backend.toSuffix() function + by comparing its result to the true value + """ + + log.info("Create one backend") + topology.standalone.backend.create(suffix=NEW_SUFFIX_1, + properties={BACKEND_NAME: NEW_BACKEND_1}) + + log.info("Run through all backends and compare backend.toSuffix() "\ + "function results with true values taken from attributes") + ents = topology.standalone.backend.list() + for ent in ents: + suffix = ent.getValues(BACKEND_PROPNAME_TO_ATTRNAME[BACKEND_SUFFIX]) + values = topology.standalone.backend.toSuffix(name=ent.dn) + assert suffix[0] in values + + log.info("Clean up after test") + topology.standalone.backend.delete(suffix=NEW_SUFFIX_1) + + if __name__ == "__main__": - test = Test_Backend() - test.setUp() - - test.test_list() - test.test_create() - test.test_delete() - test.test_toSuffix() - - test.tearDown() - + CURRENT_FILE = os.path.realpath(__file__) + pytest.main("-s -v %s" % CURRENT_FILE)
0
f6b74ad18a52720c4558d4a46cbb2eeb21109033
389ds/389-ds-base
Trac Ticket #346 - Slow ldapmodify operation time for large quantities of multi-valued attribute values https://fedorahosted.org/389/ticket/346 Fix Description: Fix in "commit c0151f78509c35250095da6e2785842337963008" takes advantage of the knowledge on normalized attribute DNs. When generating index keys from the attribute value, it has to be case normalized, but the attribute DN is normalized w/o the cases lowered. This patch introduces attribute flags to distinguish the 2 cases: SLAPI_ATTR_FLAG_NORMALIZED_CES - normalized but not case- normalized. SLAPI_ATTR_FLAG_NORMALIZED_CIS - case-normalized And SLAPI_ATTR_FLAG_NORMALIZED is the combination of the 2 macros. (cherry picked from commit 63d68b122dc5efe6cd0e73873e26c38ba8a2d2f4)
commit f6b74ad18a52720c4558d4a46cbb2eeb21109033 Author: Noriko Hosoi <[email protected]> Date: Fri Jul 13 11:56:30 2012 -0700 Trac Ticket #346 - Slow ldapmodify operation time for large quantities of multi-valued attribute values https://fedorahosted.org/389/ticket/346 Fix Description: Fix in "commit c0151f78509c35250095da6e2785842337963008" takes advantage of the knowledge on normalized attribute DNs. When generating index keys from the attribute value, it has to be case normalized, but the attribute DN is normalized w/o the cases lowered. This patch introduces attribute flags to distinguish the 2 cases: SLAPI_ATTR_FLAG_NORMALIZED_CES - normalized but not case- normalized. SLAPI_ATTR_FLAG_NORMALIZED_CIS - case-normalized And SLAPI_ATTR_FLAG_NORMALIZED is the combination of the 2 macros. (cherry picked from commit 63d68b122dc5efe6cd0e73873e26c38ba8a2d2f4) diff --git a/ldap/servers/plugins/syntaxes/string.c b/ldap/servers/plugins/syntaxes/string.c index 5c78d6ae6..8d047469c 100644 --- a/ldap/servers/plugins/syntaxes/string.c +++ b/ldap/servers/plugins/syntaxes/string.c @@ -448,21 +448,31 @@ string_values2keys( Slapi_PBlock *pb, Slapi_Value **bvals, for ( bvlp = bvals, nbvlp = nbvals; bvlp && *bvlp; bvlp++, nbvlp++ ) { + unsigned long value_flags = slapi_value_get_flags(*bvlp); c = slapi_ch_strdup(slapi_value_get_string(*bvlp)); /* if the NORMALIZED flag is set, skip normalizing */ - if (!(slapi_value_get_flags(*bvlp) & SLAPI_ATTR_FLAG_NORMALIZED)) { + if (!(value_flags & SLAPI_ATTR_FLAG_NORMALIZED)) { /* 3rd arg: 1 - trim leading blanks */ value_normalize_ext( c, syntax, 1, &alt ); + value_flags |= SLAPI_ATTR_FLAG_NORMALIZED; + } else if ((syntax & SYNTAX_DN) && + (value_flags & SLAPI_ATTR_FLAG_NORMALIZED_CES)) { + /* This dn value is normalized, but not case-normalized. */ + slapi_dn_ignore_case(c); + /* This dn value is case-normalized */ + value_flags &= ~SLAPI_ATTR_FLAG_NORMALIZED_CES; + value_flags |= SLAPI_ATTR_FLAG_NORMALIZED_CIS; } if (alt) { slapi_ch_free_string(&c); - *nbvlp = slapi_value_new_string_passin(alt); + *nbvlp = slapi_value_new_string_passin(alt); alt = NULL; } else { - *nbvlp = slapi_value_new_string_passin(c); + *nbvlp = slapi_value_new_string_passin(c); + c = NULL; } /* new value is normalized */ - slapi_value_set_flags(*nbvlp, slapi_value_get_flags(*bvlp)|SLAPI_ATTR_FLAG_NORMALIZED); + slapi_value_set_flags(*nbvlp, value_flags); } *ivals = nbvals; break; @@ -570,8 +580,9 @@ string_values2keys( Slapi_PBlock *pb, Slapi_Value **bvals, bvdup= slapi_value_new(); for ( bvlp = bvals; bvlp && *bvlp; bvlp++ ) { + unsigned long value_flags = slapi_value_get_flags(*bvlp); /* 3rd arg: 1 - trim leading blanks */ - if (!(slapi_value_get_flags(*bvlp) & SLAPI_ATTR_FLAG_NORMALIZED)) { + if (!(value_flags & SLAPI_ATTR_FLAG_NORMALIZED)) { c = slapi_ch_strdup(slapi_value_get_string(*bvlp)); value_normalize_ext( c, syntax, 1, &alt ); if (alt) { @@ -583,6 +594,17 @@ string_values2keys( Slapi_PBlock *pb, Slapi_Value **bvals, c = NULL; } bvp = slapi_value_get_berval(bvdup); + value_flags |= SLAPI_ATTR_FLAG_NORMALIZED; + } else if ((syntax & SYNTAX_DN) && + (value_flags & SLAPI_ATTR_FLAG_NORMALIZED_CES)) { + /* This dn value is normalized, but not case-normalized. */ + c = slapi_ch_strdup(slapi_value_get_string(*bvlp)); + slapi_dn_ignore_case(c); + slapi_value_set_string_passin(bvdup, c); + c = NULL; + /* This dn value is case-normalized */ + value_flags &= ~SLAPI_ATTR_FLAG_NORMALIZED_CES; + value_flags |= SLAPI_ATTR_FLAG_NORMALIZED_CIS; } else { bvp = slapi_value_get_berval(*bvlp); } @@ -595,7 +617,7 @@ string_values2keys( Slapi_PBlock *pb, Slapi_Value **bvals, } buf[substrlens[INDEX_SUBSTRBEGIN]] = '\0'; (*ivals)[n] = slapi_value_new_string(buf); - slapi_value_set_flags((*ivals)[n], slapi_value_get_flags(*bvlp)|SLAPI_ATTR_FLAG_NORMALIZED); + slapi_value_set_flags((*ivals)[n], value_flags); n++; } @@ -608,7 +630,7 @@ string_values2keys( Slapi_PBlock *pb, Slapi_Value **bvals, } buf[substrlens[INDEX_SUBSTRMIDDLE]] = '\0'; (*ivals)[n] = slapi_value_new_string(buf); - slapi_value_set_flags((*ivals)[n], slapi_value_get_flags(*bvlp)|SLAPI_ATTR_FLAG_NORMALIZED); + slapi_value_set_flags((*ivals)[n], value_flags); n++; } @@ -621,7 +643,7 @@ string_values2keys( Slapi_PBlock *pb, Slapi_Value **bvals, buf[substrlens[INDEX_SUBSTREND] - 1] = '$'; buf[substrlens[INDEX_SUBSTREND]] = '\0'; (*ivals)[n] = slapi_value_new_string(buf); - slapi_value_set_flags((*ivals)[n], slapi_value_get_flags(*bvlp)|SLAPI_ATTR_FLAG_NORMALIZED); + slapi_value_set_flags((*ivals)[n], value_flags); n++; } } @@ -674,8 +696,16 @@ string_assertion2keys_ava( alt = NULL; } tmpval->bv.bv_len=strlen(tmpval->bv.bv_val); + flags |= SLAPI_ATTR_FLAG_NORMALIZED; + } else if ((syntax & SYNTAX_DN) && + (flags & SLAPI_ATTR_FLAG_NORMALIZED_CES)) { + /* This dn value is normalized, but not case-normalized. */ + slapi_dn_ignore_case(tmpval->bv.bv_val); + /* This dn value is case-normalized */ + flags &= ~SLAPI_ATTR_FLAG_NORMALIZED_CES; + flags |= SLAPI_ATTR_FLAG_NORMALIZED_CIS; } - slapi_value_set_flags(tmpval, flags|SLAPI_ATTR_FLAG_NORMALIZED); + slapi_value_set_flags(tmpval, flags); break; case LDAP_FILTER_EQUALITY: (*ivals) = (Slapi_Value **) slapi_ch_malloc( 2 * sizeof(Slapi_Value *) ); @@ -689,8 +719,16 @@ string_assertion2keys_ava( (*ivals)[0]->bv.bv_len = strlen( (*ivals)[0]->bv.bv_val ); alt = NULL; } - slapi_value_set_flags((*ivals)[0], flags|SLAPI_ATTR_FLAG_NORMALIZED); - } + flags |= SLAPI_ATTR_FLAG_NORMALIZED; + } else if ((syntax & SYNTAX_DN) && + (flags & SLAPI_ATTR_FLAG_NORMALIZED_CES)) { + /* This dn value is normalized, but not case-normalized. */ + slapi_dn_ignore_case((*ivals)[0]->bv.bv_val); + /* This dn value is case-normalized */ + flags &= ~SLAPI_ATTR_FLAG_NORMALIZED_CES; + flags |= SLAPI_ATTR_FLAG_NORMALIZED_CIS; + } + slapi_value_set_flags((*ivals)[0], flags); (*ivals)[1] = NULL; break; diff --git a/ldap/servers/slapd/attrlist.c b/ldap/servers/slapd/attrlist.c index 4ae5fcf53..e365f3d58 100644 --- a/ldap/servers/slapd/attrlist.c +++ b/ldap/servers/slapd/attrlist.c @@ -292,7 +292,7 @@ int attrlist_replace(Slapi_Attr **alist, const char *type, struct berval **vals) valuearray_init_bervalarray(vals, &values); if (slapi_attr_is_dn_syntax_attr(*a)) { valuearray_dn_normalize_value(values); - (*a)->a_flags |= SLAPI_ATTR_FLAG_NORMALIZED; + (*a)->a_flags |= SLAPI_ATTR_FLAG_NORMALIZED_CES; } rc = attr_replace(*a, values); } @@ -319,7 +319,7 @@ int attrlist_replace_with_flags(Slapi_Attr **alist, const char *type, struct ber valuearray_init_bervalarray_with_flags(vals, &values, flags); if (slapi_attr_is_dn_syntax_attr(*a)) { valuearray_dn_normalize_value(values); - (*a)->a_flags |= SLAPI_ATTR_FLAG_NORMALIZED; + (*a)->a_flags |= SLAPI_ATTR_FLAG_NORMALIZED_CES; } rc = attr_replace(*a, values); } diff --git a/ldap/servers/slapd/back-ldbm/index.c b/ldap/servers/slapd/back-ldbm/index.c index 43b68f556..a5c6ac580 100644 --- a/ldap/servers/slapd/back-ldbm/index.c +++ b/ldap/servers/slapd/back-ldbm/index.c @@ -455,7 +455,9 @@ index_addordel_entry( /* skip "entrydn" */ continue; } else { - slapi_values_set_flags(svals, SLAPI_ATTR_FLAG_NORMALIZED); + /* entrydn is case-normalized */ + slapi_values_set_flags(svals, + SLAPI_ATTR_FLAG_NORMALIZED_CIS); } } result = index_addordel_values_sv( be, type, svals, NULL, diff --git a/ldap/servers/slapd/back-ldbm/ldbm_add.c b/ldap/servers/slapd/back-ldbm/ldbm_add.c index 18390c246..158dc8e4b 100644 --- a/ldap/servers/slapd/back-ldbm/ldbm_add.c +++ b/ldap/servers/slapd/back-ldbm/ldbm_add.c @@ -1189,7 +1189,7 @@ add_update_entrydn_operational_attributes(struct backentry *ep) bv.bv_val = (void*)backentry_get_ndn(ep); bv.bv_len = strlen( bv.bv_val ); entry_replace_values_with_flags( ep->ep_entry, LDBM_ENTRYDN_STR, bvp, - SLAPI_ATTR_FLAG_NORMALIZED ); + SLAPI_ATTR_FLAG_NORMALIZED_CIS ); } /* diff --git a/ldap/servers/slapd/entry.c b/ldap/servers/slapd/entry.c index 429a74826..1c4569fb1 100644 --- a/ldap/servers/slapd/entry.c +++ b/ldap/servers/slapd/entry.c @@ -3533,7 +3533,7 @@ slapi_entry_add_values_sv(Slapi_Entry *e, attrlist_find_or_create(alist, type, &a); if (slapi_attr_is_dn_syntax_attr(*a)) { valuearray_dn_normalize_value(vals); - (*a)->a_flags |= SLAPI_ATTR_FLAG_NORMALIZED; + (*a)->a_flags |= SLAPI_ATTR_FLAG_NORMALIZED_CES; } rc= attr_add_valuearray(*a,vals,slapi_entry_get_dn_const(e)); } diff --git a/ldap/servers/slapd/entrywsi.c b/ldap/servers/slapd/entrywsi.c index 639baa203..52555b70d 100644 --- a/ldap/servers/slapd/entrywsi.c +++ b/ldap/servers/slapd/entrywsi.c @@ -442,7 +442,7 @@ entry_add_present_values_wsi(Slapi_Entry *e, const char *type, struct berval **b /* Check if the type of the to-be-added values has DN syntax or not. */ if (slapi_attr_is_dn_syntax_attr(a)) { valuearray_dn_normalize_value(valuestoadd); - a->a_flags |= SLAPI_ATTR_FLAG_NORMALIZED; + a->a_flags |= SLAPI_ATTR_FLAG_NORMALIZED_CES; } if(urp) { @@ -564,7 +564,7 @@ entry_delete_present_values_wsi(Slapi_Entry *e, const char *type, struct berval * or not. */ if (slapi_attr_is_dn_syntax_attr(a)) { valuearray_dn_normalize_value(valuestodelete); - a->a_flags |= SLAPI_ATTR_FLAG_NORMALIZED; + a->a_flags |= SLAPI_ATTR_FLAG_NORMALIZED_CES; } if(urp) { diff --git a/ldap/servers/slapd/slapi-plugin.h b/ldap/servers/slapd/slapi-plugin.h index 7652306c6..a703a4ce3 100644 --- a/ldap/servers/slapd/slapi-plugin.h +++ b/ldap/servers/slapd/slapi-plugin.h @@ -177,7 +177,15 @@ NSPR_API(PRUint32) PR_fprintf(struct PRFileDesc* fd, const char *fmt, ...) * \see slapi_value_set_flags() * \see slapi_values_set_flags() */ -#define SLAPI_ATTR_FLAG_NORMALIZED 0x0200 /* the attr value is normalized */ +/* the attr value is normalized */ +#define SLAPI_ATTR_FLAG_NORMALIZED \ + (SLAPI_ATTR_FLAG_NORMALIZED_CES|SLAPI_ATTR_FLAG_NORMALIZED_CIS) +#define SLAPI_ATTR_FLAG_NORMALIZED_CES 0x0200 /* the attr value is normalized, + but not case-normalized. + Used for DN. */ +#define SLAPI_ATTR_FLAG_NORMALIZED_CIS 0x0400 /* the attr value is normalized + including case. + Used for DN. */ /** * Flag to indicate that the attribute value is not exposed if specified. diff --git a/ldap/servers/slapd/value.c b/ldap/servers/slapd/value.c index 6d30f63f1..73e5d20c2 100644 --- a/ldap/servers/slapd/value.c +++ b/ldap/servers/slapd/value.c @@ -595,7 +595,7 @@ value_dn_normalize_value(Slapi_Value *value) value->bv.bv_val = slapi_ch_strdup(slapi_sdn_get_dn(sdn)); value->bv.bv_len = slapi_sdn_get_ndn_len(sdn); slapi_sdn_free(&sdn); - slapi_value_set_flags(value, SLAPI_ATTR_FLAG_NORMALIZED); + slapi_value_set_flags(value, SLAPI_ATTR_FLAG_NORMALIZED_CES); } else { rc = 1; slapi_ch_free((void **)&sdn); /* free just Slapi_DN */
0
58b0496f82c8fbf30ef9c36f4d7b6c24578522db
389ds/389-ds-base
Don't build policy module from Makefile. This removes the Makefile rule that builds the SELinux policy module. The removed rule was only building and installing the module for the targeted policy. There are different base policies (targeted, strict, mls) on different systems, so it makes more sense to build the policy module from the spec file where we can define the available base policy types for the platform in question. We still need a "--with-selinux" option to enable the SELinux specific setup code as well as creating the policy .fc file with the proper paths that are defined at build time.
commit 58b0496f82c8fbf30ef9c36f4d7b6c24578522db Author: Nathan Kinder <[email protected]> Date: Tue Sep 22 08:39:12 2009 -0700 Don't build policy module from Makefile. This removes the Makefile rule that builds the SELinux policy module. The removed rule was only building and installing the module for the targeted policy. There are different base policies (targeted, strict, mls) on different systems, so it makes more sense to build the policy module from the spec file where we can define the available base policy types for the platform in question. We still need a "--with-selinux" option to enable the SELinux specific setup code as well as creating the policy .fc file with the proper paths that are defined at build time. diff --git a/Makefile.am b/Makefile.am index f79312067..b8724cadf 100644 --- a/Makefile.am +++ b/Makefile.am @@ -63,7 +63,8 @@ LIBCRUN=@LIBCRUN@ #------------------------ # Generated Sources #------------------------ -BUILT_SOURCES = dberrstrs.h +BUILT_SOURCES = dberrstrs.h \ + $(POLICY_FC) CLEANFILES = dberrstrs.h ns-slapd.properties \ ldap/admin/src/scripts/template-dbverify ldap/admin/src/template-initconfig \ @@ -107,10 +108,6 @@ selinux-built: selinux-built/dirsrv.fc: selinux-built $(fixupcmd) selinux-built/dirsrv.fc.in > $@ -selinux-built/dirsrv.pp: selinux-built/dirsrv.fc - cd selinux-built && $(MAKE) - - #------------------------ # Install Paths @@ -128,7 +125,6 @@ instconfigdir = @instconfigdir@ perldir = $(libdir)@perldir@ infdir = $(datadir)@infdir@ mibdir = $(datadir)@mibdir@ -policydir = $(datadir)/selinux/targeted updatedir = $(datadir)@updatedir@ defaultuser=@defaultuser@ @@ -168,7 +164,7 @@ enable_presence = off endif if SELINUX -POLICY_MODULE = selinux-built/dirsrv.pp +POLICY_FC = selinux-built/dirsrv.fc endif serverplugin_LTLIBRARIES = libacl-plugin.la libattr-unique-plugin.la \ @@ -191,8 +187,6 @@ noinst_LIBRARIES = libavl.a libldaputil.a #------------------------ # Installed Files #------------------------ -policy_DATA = $(POLICY_MODULE) - config_DATA = $(srcdir)/lib/ldaputil/certmap.conf \ $(srcdir)/ldap/schema/slapd-collations.conf \ ldap/admin/src/template-initconfig \ diff --git a/Makefile.in b/Makefile.in index 0900553e2..49cde44fc 100644 --- a/Makefile.in +++ b/Makefile.in @@ -102,9 +102,8 @@ am__installdirs = "$(DESTDIR)$(serverdir)" \ "$(DESTDIR)$(configdir)" "$(DESTDIR)$(infdir)" \ "$(DESTDIR)$(initconfigdir)" "$(DESTDIR)$(mibdir)" \ "$(DESTDIR)$(propertydir)" "$(DESTDIR)$(perldir)" \ - "$(DESTDIR)$(policydir)" "$(DESTDIR)$(propertydir)" \ - "$(DESTDIR)$(sampledatadir)" "$(DESTDIR)$(schemadir)" \ - "$(DESTDIR)$(updatedir)" + "$(DESTDIR)$(propertydir)" "$(DESTDIR)$(sampledatadir)" \ + "$(DESTDIR)$(schemadir)" "$(DESTDIR)$(updatedir)" serverLTLIBRARIES_INSTALL = $(INSTALL) serverpluginLTLIBRARIES_INSTALL = $(INSTALL) LTLIBRARIES = $(server_LTLIBRARIES) $(serverplugin_LTLIBRARIES) @@ -887,15 +886,13 @@ initconfigDATA_INSTALL = $(INSTALL_DATA) mibDATA_INSTALL = $(INSTALL_DATA) nodist_propertyDATA_INSTALL = $(INSTALL_DATA) perlDATA_INSTALL = $(INSTALL_DATA) -policyDATA_INSTALL = $(INSTALL_DATA) propertyDATA_INSTALL = $(INSTALL_DATA) sampledataDATA_INSTALL = $(INSTALL_DATA) schemaDATA_INSTALL = $(INSTALL_DATA) updateDATA_INSTALL = $(INSTALL_DATA) DATA = $(config_DATA) $(inf_DATA) $(initconfig_DATA) $(mib_DATA) \ - $(nodist_property_DATA) $(perl_DATA) $(policy_DATA) \ - $(property_DATA) $(sampledata_DATA) $(schema_DATA) \ - $(update_DATA) + $(nodist_property_DATA) $(perl_DATA) $(property_DATA) \ + $(sampledata_DATA) $(schema_DATA) $(update_DATA) ETAGS = etags CTAGS = ctags DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) @@ -1169,7 +1166,9 @@ KERBEROS_LINK = $(kerberos_lib) #------------------------ # Generated Sources #------------------------ -BUILT_SOURCES = dberrstrs.h +BUILT_SOURCES = dberrstrs.h \ + $(POLICY_FC) + CLEANFILES = dberrstrs.h ns-slapd.properties \ ldap/admin/src/scripts/template-dbverify ldap/admin/src/template-initconfig \ ldap/admin/src/scripts/dscreate.map ldap/admin/src/scripts/remove-ds.pl \ @@ -1201,7 +1200,6 @@ CLEANFILES = dberrstrs.h ns-slapd.properties \ ldap/ldif/template-state.ldif ldap/ldif/template-suffix-db.ldif taskdir = $(datadir)@scripttemplatedir@ -policydir = $(datadir)/selinux/targeted server_LTLIBRARIES = libslapd.la libns-dshttpd.la # this is how to add optional plugins @@ -1215,7 +1213,7 @@ server_LTLIBRARIES = libslapd.la libns-dshttpd.la @enable_presence_TRUE@LIBPRESENCE_SCHEMA = $(srcdir)/ldap/schema/10presence.ldif @enable_presence_FALSE@enable_presence = off @enable_presence_TRUE@enable_presence = on -@SELINUX_TRUE@POLICY_MODULE = selinux-built/dirsrv.pp +@SELINUX_TRUE@POLICY_FC = selinux-built/dirsrv.fc serverplugin_LTLIBRARIES = libacl-plugin.la libattr-unique-plugin.la \ libback-ldbm.la libchainingdb-plugin.la libcollation-plugin.la \ libcos-plugin.la libderef-plugin.la libdes-plugin.la libdistrib-plugin.la \ @@ -1233,7 +1231,6 @@ noinst_LIBRARIES = libavl.a libldaputil.a #------------------------ # Installed Files #------------------------ -policy_DATA = $(POLICY_MODULE) config_DATA = $(srcdir)/lib/ldaputil/certmap.conf \ $(srcdir)/ldap/schema/slapd-collations.conf \ ldap/admin/src/template-initconfig \ @@ -9420,23 +9417,6 @@ uninstall-perlDATA: echo " rm -f '$(DESTDIR)$(perldir)/$$f'"; \ rm -f "$(DESTDIR)$(perldir)/$$f"; \ done -install-policyDATA: $(policy_DATA) - @$(NORMAL_INSTALL) - test -z "$(policydir)" || $(mkdir_p) "$(DESTDIR)$(policydir)" - @list='$(policy_DATA)'; for p in $$list; do \ - if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ - f=$(am__strip_dir) \ - echo " $(policyDATA_INSTALL) '$$d$$p' '$(DESTDIR)$(policydir)/$$f'"; \ - $(policyDATA_INSTALL) "$$d$$p" "$(DESTDIR)$(policydir)/$$f"; \ - done - -uninstall-policyDATA: - @$(NORMAL_UNINSTALL) - @list='$(policy_DATA)'; for p in $$list; do \ - f=$(am__strip_dir) \ - echo " rm -f '$(DESTDIR)$(policydir)/$$f'"; \ - rm -f "$(DESTDIR)$(policydir)/$$f"; \ - done install-propertyDATA: $(property_DATA) @$(NORMAL_INSTALL) test -z "$(propertydir)" || $(mkdir_p) "$(DESTDIR)$(propertydir)" @@ -9687,7 +9667,7 @@ check: $(BUILT_SOURCES) all-am: Makefile $(LIBRARIES) $(LTLIBRARIES) $(PROGRAMS) $(SCRIPTS) \ $(MANS) $(DATA) config.h installdirs: - for dir in "$(DESTDIR)$(serverdir)" "$(DESTDIR)$(serverplugindir)" "$(DESTDIR)$(bindir)" "$(DESTDIR)$(sbindir)" "$(DESTDIR)$(bindir)" "$(DESTDIR)$(initdir)" "$(DESTDIR)$(sbindir)" "$(DESTDIR)$(taskdir)" "$(DESTDIR)$(updatedir)" "$(DESTDIR)$(man1dir)" "$(DESTDIR)$(man8dir)" "$(DESTDIR)$(configdir)" "$(DESTDIR)$(infdir)" "$(DESTDIR)$(initconfigdir)" "$(DESTDIR)$(mibdir)" "$(DESTDIR)$(propertydir)" "$(DESTDIR)$(perldir)" "$(DESTDIR)$(policydir)" "$(DESTDIR)$(propertydir)" "$(DESTDIR)$(sampledatadir)" "$(DESTDIR)$(schemadir)" "$(DESTDIR)$(updatedir)"; do \ + for dir in "$(DESTDIR)$(serverdir)" "$(DESTDIR)$(serverplugindir)" "$(DESTDIR)$(bindir)" "$(DESTDIR)$(sbindir)" "$(DESTDIR)$(bindir)" "$(DESTDIR)$(initdir)" "$(DESTDIR)$(sbindir)" "$(DESTDIR)$(taskdir)" "$(DESTDIR)$(updatedir)" "$(DESTDIR)$(man1dir)" "$(DESTDIR)$(man8dir)" "$(DESTDIR)$(configdir)" "$(DESTDIR)$(infdir)" "$(DESTDIR)$(initconfigdir)" "$(DESTDIR)$(mibdir)" "$(DESTDIR)$(propertydir)" "$(DESTDIR)$(perldir)" "$(DESTDIR)$(propertydir)" "$(DESTDIR)$(sampledatadir)" "$(DESTDIR)$(schemadir)" "$(DESTDIR)$(updatedir)"; do \ test -z "$$dir" || $(mkdir_p) "$$dir"; \ done install: $(BUILT_SOURCES) @@ -9824,10 +9804,9 @@ info-am: install-data-am: install-configDATA install-infDATA \ install-initSCRIPTS install-initconfigDATA install-man \ install-mibDATA install-nodist_propertyDATA install-perlDATA \ - install-policyDATA install-propertyDATA install-sampledataDATA \ - install-schemaDATA install-serverLTLIBRARIES \ - install-serverpluginLTLIBRARIES install-taskSCRIPTS \ - install-updateDATA install-updateSCRIPTS + install-propertyDATA install-sampledataDATA install-schemaDATA \ + install-serverLTLIBRARIES install-serverpluginLTLIBRARIES \ + install-taskSCRIPTS install-updateDATA install-updateSCRIPTS install-exec-am: install-binPROGRAMS install-binSCRIPTS \ install-sbinPROGRAMS install-sbinSCRIPTS @@ -9862,7 +9841,7 @@ uninstall-am: uninstall-binPROGRAMS uninstall-binSCRIPTS \ uninstall-configDATA uninstall-infDATA uninstall-info-am \ uninstall-initSCRIPTS uninstall-initconfigDATA uninstall-man \ uninstall-mibDATA uninstall-nodist_propertyDATA \ - uninstall-perlDATA uninstall-policyDATA uninstall-propertyDATA \ + uninstall-perlDATA uninstall-propertyDATA \ uninstall-sampledataDATA uninstall-sbinPROGRAMS \ uninstall-sbinSCRIPTS uninstall-schemaDATA \ uninstall-serverLTLIBRARIES uninstall-serverpluginLTLIBRARIES \ @@ -9886,7 +9865,7 @@ uninstall-man: uninstall-man1 uninstall-man8 install-initSCRIPTS install-initconfigDATA install-man \ install-man1 install-man8 install-mibDATA \ install-nodist_propertyDATA install-perlDATA \ - install-policyDATA install-propertyDATA install-sampledataDATA \ + install-propertyDATA install-sampledataDATA \ install-sbinPROGRAMS install-sbinSCRIPTS install-schemaDATA \ install-serverLTLIBRARIES install-serverpluginLTLIBRARIES \ install-strip install-taskSCRIPTS install-updateDATA \ @@ -9899,12 +9878,11 @@ uninstall-man: uninstall-man1 uninstall-man8 uninstall-initSCRIPTS uninstall-initconfigDATA uninstall-man \ uninstall-man1 uninstall-man8 uninstall-mibDATA \ uninstall-nodist_propertyDATA uninstall-perlDATA \ - uninstall-policyDATA uninstall-propertyDATA \ - uninstall-sampledataDATA uninstall-sbinPROGRAMS \ - uninstall-sbinSCRIPTS uninstall-schemaDATA \ - uninstall-serverLTLIBRARIES uninstall-serverpluginLTLIBRARIES \ - uninstall-taskSCRIPTS uninstall-updateDATA \ - uninstall-updateSCRIPTS + uninstall-propertyDATA uninstall-sampledataDATA \ + uninstall-sbinPROGRAMS uninstall-sbinSCRIPTS \ + uninstall-schemaDATA uninstall-serverLTLIBRARIES \ + uninstall-serverpluginLTLIBRARIES uninstall-taskSCRIPTS \ + uninstall-updateDATA uninstall-updateSCRIPTS clean-local: @@ -9919,9 +9897,6 @@ selinux-built: selinux-built/dirsrv.fc: selinux-built $(fixupcmd) selinux-built/dirsrv.fc.in > $@ -selinux-built/dirsrv.pp: selinux-built/dirsrv.fc - cd selinux-built && $(MAKE) - #------------------------ # ns-slapd.properties #------------------------
0
813030cc7a82fd5789cc92052b34f8c8ebc9e93a
389ds/389-ds-base
Ticket 50259 - implement dn construction test Bug Description: Implement a lib389 dn test to show we have correct behaviour with dn derivation in lib389 creation. Fix Description: Add test case. https://pagure.io/389-ds-base/issue/50259 Author: William Brown <[email protected]> Review by: spichugi (Thanks!)
commit 813030cc7a82fd5789cc92052b34f8c8ebc9e93a Author: William Brown <[email protected]> Date: Thu Mar 7 13:22:54 2019 +1000 Ticket 50259 - implement dn construction test Bug Description: Implement a lib389 dn test to show we have correct behaviour with dn derivation in lib389 creation. Fix Description: Add test case. https://pagure.io/389-ds-base/issue/50259 Author: William Brown <[email protected]> Review by: spichugi (Thanks!) diff --git a/dirsrvtests/tests/suites/lib389/__init__.py b/dirsrvtests/tests/suites/lib389/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/dirsrvtests/tests/suites/lib389/dsldapobject/__init__.py b/dirsrvtests/tests/suites/lib389/dsldapobject/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/dirsrvtests/tests/suites/lib389/dsldapobject/dn_construct_test.py b/dirsrvtests/tests/suites/lib389/dsldapobject/dn_construct_test.py new file mode 100644 index 000000000..f5d306a25 --- /dev/null +++ b/dirsrvtests/tests/suites/lib389/dsldapobject/dn_construct_test.py @@ -0,0 +1,234 @@ +# --- BEGIN COPYRIGHT BLOCK --- +# Copyright (C) 2019 William Brown <[email protected]> +# All rights reserved. +# +# License: GPL (version 3 or any later version). +# See LICENSE for details. +# --- END COPYRIGHT BLOCK --- +# + +import ldap +import pytest + +from lib389._constants import DEFAULT_SUFFIX +from lib389.topologies import topology_st + +from lib389.idm.group import Groups, Group + +################################################################################# +# This is a series of test cases to assert that various DN construction scenarios +# work as expected in lib389. +# +# DSLdapObjects are designed to allow explicit control, or to "safely assume" +# so that ldap concepts aren't as confusing. +# You can thus construct an object with a DN that is: +# * defined by you expliticly +# * derived from properties of the object automatically +# +# There are also two paths to construction: from the pluralised factory style +# builder, or from the singular. The factory style has very few extra parts +# but it's worth testing anyway. +# +# In no case do we derive a multi value rdn due to their complexity. +# + +def test_mul_explicit_rdn(topology_st): + """Test that with multiple cn and an explicit rdn, we use the rdn + + :id: b39ef204-45c0-4a74-9b59-b4ac1199d78c + + :setup: standalone instance + + :steps: 1. Create with mulitple cn and rdn + + :expectedresults: 1. Create success + """ + # Create with an explicit rdn value, given to the properties/rdn + gps = Groups(topology_st.standalone, DEFAULT_SUFFIX) + gp = gps.create('cn=test_mul_explicit_rdn', + properties={ + 'cn': ['test_mul_explicit_rdn', 'other_cn_test_mul_explicit_rdn'], + }) + assert gp.dn.lower() == f'cn=test_mul_explicit_rdn,ou=groups,{DEFAULT_SUFFIX}'.lower() + gp.delete() + +def test_mul_derive_single_dn(topology_st): + """Test that with single cn we derive rdn correctly. + + :id: f34f271a-ca57-4aa0-905a-b5392ce06c79 + + :setup: standalone instance + + :steps: 1. Create with single cn + + :expectedresults: 1. Create success + """ + gps = Groups(topology_st.standalone, DEFAULT_SUFFIX) + gp = gps.create(properties={ + 'cn': ['test_mul_derive_single_dn'], + }) + assert gp.dn.lower() == f'cn=test_mul_derive_single_dn,ou=groups,{DEFAULT_SUFFIX}'.lower() + gp.delete() + +def test_mul_derive_mult_dn(topology_st): + """Test that with multiple cn we derive rdn correctly. + + :id: 1e1f5483-bfad-4f73-9dfb-aec54d08b268 + + :setup: standalone instance + + :steps: 1. Create with multiple cn + + :expectedresults: 1. Create success + """ + gps = Groups(topology_st.standalone, DEFAULT_SUFFIX) + gp = gps.create(properties={ + 'cn': ['test_mul_derive_mult_dn', 'test_mul_derive_single_dn'], + }) + assert gp.dn.lower() == f'cn=test_mul_derive_mult_dn,ou=groups,{DEFAULT_SUFFIX}'.lower() + gp.delete() + +def test_sin_explicit_dn(topology_st): + """Test explicit dn with create + + :id: 2d812225-243b-4f87-85ad-d403a4ae0267 + + :setup: standalone instance + + :steps: 1. Create with explicit dn + + :expectedresults: 1. Create success + """ + expect_dn = f'cn=test_sin_explicit_dn,ou=groups,{DEFAULT_SUFFIX}' + gp = Group(topology_st.standalone, dn=expect_dn) + gp.create(properties={ + 'cn': ['test_sin_explicit_dn'], + }) + assert gp.dn.lower() == expect_dn.lower() + gp.delete() + +def test_sin_explicit_rdn(topology_st): + """Test explicit rdn with create. + + :id: a2c14e50-8086-4edb-9088-3f4a8e875c3a + + :setup: standalone instance + + :steps: 1. Create with explicit rdn + + :expectedresults: 1. Create success + """ + gp = Group(topology_st.standalone) + gp.create(rdn='cn=test_sin_explicit_rdn', + basedn=f'ou=groups,{DEFAULT_SUFFIX}', + properties={ + 'cn': ['test_sin_explicit_rdn'], + }) + assert gp.dn.lower() == f'cn=test_sin_explicit_rdn,ou=groups,{DEFAULT_SUFFIX}'.lower() + gp.delete() + +def test_sin_derive_single_dn(topology_st): + """Derive the dn from a single cn + + :id: d7597016-214c-4fbd-8b48-71eb16ea9ede + + :setup: standalone instance + + :steps: 1. Create with a single cn (no dn, no rdn) + + :expectedresults: 1. Create success + """ + gp = Group(topology_st.standalone) + gp.create(basedn=f'ou=groups,{DEFAULT_SUFFIX}', + properties={ + 'cn': ['test_sin_explicit_dn'], + }) + assert gp.dn.lower() == f'cn=test_sin_explicit_dn,ou=groups,{DEFAULT_SUFFIX}'.lower() + gp.delete() + +def test_sin_derive_mult_dn(topology_st): + """Derive the dn from multiple cn + + :id: 0a1a7132-a08f-4b56-ae52-30c8ca59cfaf + + :setup: standalone instance + + :steps: 1. Create with multiple cn + + :expectedresults: 1. Create success + """ + gp = Group(topology_st.standalone) + gp.create(basedn=f'ou=groups,{DEFAULT_SUFFIX}', + properties={ + 'cn': ['test_sin_derive_mult_dn', 'other_test_sin_derive_mult_dn'], + }) + assert gp.dn.lower() == f'cn=test_sin_derive_mult_dn,ou=groups,{DEFAULT_SUFFIX}'.lower() + gp.delete() + +def test_sin_invalid_no_basedn(topology_st): + """Test that with insufficent data, create fails. + + :id: a710b81c-cb74-4632-97b3-bdbcccd40954 + + :setup: standalone instance + + :steps: 1. Create with no basedn (no rdn derivation will work) + + :expectedresults: 1. Create fails + """ + gp = Group(topology_st.standalone) + # No basedn, so we can't derive the full dn from this. + with pytest.raises(ldap.UNWILLING_TO_PERFORM): + gp.create(properties={ + 'cn': ['test_sin_invalid_no_basedn'], + }) + +def test_sin_invalid_no_rdn(topology_st): + """Test that with no cn, rdn derivation fails. + + :id: c3bb28f8-db59-4d8a-8920-169879ef702b + + :setup: standalone instance + + :steps: 1. Create with no cn + + :expectedresults: 1. Create fails + """ + gp = Group(topology_st.standalone) + with pytest.raises(ldap.UNWILLING_TO_PERFORM): + # Note lack of rdn derivable type (cn) AND no rdn + gp.create(basedn=f'ou=groups,{DEFAULT_SUFFIX}', + properties={ + 'member': ['test_sin_explicit_dn'], + }) + +def test_sin_non_present_rdn(topology_st): + """Test that with an rdn not present in attributes, create succeeds in some cases. + + :id: a5d9cb24-8907-4622-ac85-90407a66e00a + + :setup: standalone instance + + :steps: 1. Create with an rdn not in properties + + :expectedresults: 1. Create success + """ + # Test that creating something with an rdn not present in the properties works + # NOTE: I think that this is 389-ds making this work, NOT lib389. + gp1 = Group(topology_st.standalone) + gp1.create(rdn='cn=test_sin_non_present_rdn', + basedn=f'ou=groups,{DEFAULT_SUFFIX}', + properties={ + 'cn': ['other_test_sin_non_present_rdn'], + }) + assert gp1.dn.lower() == f'cn=test_sin_non_present_rdn,ou=groups,{DEFAULT_SUFFIX}'.lower() + gp1.delete() + + # Now, test where there is no cn. lib389 is blocking this today, but + # 50259 will change this. + gp2 = Group(topology_st.standalone) + gp2.create(rdn='cn=test_sin_non_present_rdn', + basedn=f'ou=groups,{DEFAULT_SUFFIX}', + properties={}) + assert gp2.dn.lower() == f'cn=test_sin_non_present_rdn,ou=groups,{DEFAULT_SUFFIX}'.lower() + gp2.delete() diff --git a/src/lib389/lib389/_mapped_object.py b/src/lib389/lib389/_mapped_object.py index f35b19e1f..95b40cf71 100644 --- a/src/lib389/lib389/_mapped_object.py +++ b/src/lib389/lib389/_mapped_object.py @@ -724,14 +724,19 @@ class DSLdapObject(DSLogging): # Turn it into a list instead. properties[k] = [v, ] - # This change here, means we can pre-load a full dn to _dn, or we can - # accept based on the rdn + # If we were created with a dn= in the object init, we set tdn now, and skip + # any possible dn derivation steps that follow. tdn = self._dn + # However, if no DN was provided, we attempt to derive the DN from the relevant + # properties of the object. The idea being that by defining only the attributes + # of the object, we can just solve a possible rdn instead of asking for the same + # data twice. if tdn is None: if basedn is None: raise ldap.UNWILLING_TO_PERFORM('Invalid request to create. basedn cannot be None') + # Were we given a relative component? Yes? Go ahead! if rdn is not None: tdn = ensure_str('%s,%s' % (rdn, basedn)) elif properties.get(self._rdn_attribute, None) is not None:
0
468b8a8dfed096cb77b6345519bd2b48085b3cfe
389ds/389-ds-base
Issue: 50112 - Port ACI test suit from TET to python3(keyaci) Port ACI test suit from TET to python3(keyaci) https://pagure.io/389-ds-base/issue/50112 Reviewed by: Mark Reynolds, Simon Pichugin, William Brown, Viktor Ashirov
commit 468b8a8dfed096cb77b6345519bd2b48085b3cfe Author: Anuj Borah <[email protected]> Date: Mon Jan 28 08:57:41 2019 +0530 Issue: 50112 - Port ACI test suit from TET to python3(keyaci) Port ACI test suit from TET to python3(keyaci) https://pagure.io/389-ds-base/issue/50112 Reviewed by: Mark Reynolds, Simon Pichugin, William Brown, Viktor Ashirov diff --git a/dirsrvtests/tests/suites/acl/conftest.py b/dirsrvtests/tests/suites/acl/conftest.py new file mode 100644 index 000000000..b0a7241f4 --- /dev/null +++ b/dirsrvtests/tests/suites/acl/conftest.py @@ -0,0 +1,125 @@ +# --- BEGIN COPYRIGHT BLOCK --- +# Copyright (C) 2019 Red Hat, Inc. +# All rights reserved. +# +# License: GPL (version 3 or any later version). +# See LICENSE for details. +# --- END COPYRIGHT BLOCK ---- + +""" +This is the config file for keywords test scripts. + +""" + +import pytest + +from lib389._constants import DEFAULT_SUFFIX, PW_DM +from lib389.idm.user import UserAccounts +from lib389.idm.organizationalunit import OrganizationalUnit, OrganizationalUnits +from lib389.topologies import topology_st as topo +from lib389.idm.domain import Domain + + [email protected](scope="function") +def aci_of_user(request, topo): + """ + Removes and Restores ACIs after the test. + """ + aci_list = Domain(topo.standalone, DEFAULT_SUFFIX).get_attr_vals_utf8('aci') + + def finofaci(): + """ + Removes and Restores ACIs after the test. + """ + domain = Domain(topo.standalone, DEFAULT_SUFFIX) + domain.remove_all('aci') + for aci in aci_list: + domain.add("aci", aci) + + request.addfinalizer(finofaci) + + [email protected](scope="module") +def add_user(request, topo): + """ + This function will create user for the test and in the end entries will be deleted . + """ + ous_origin = OrganizationalUnits(topo.standalone, DEFAULT_SUFFIX) + ou_origin = ous_origin.create(properties={'ou': 'Keywords'}) + + ous_next = OrganizationalUnits(topo.standalone, ou_origin.dn) + for ou in ['Authmethod', 'Dayofweek', 'DNS', 'IP', 'Timeofday']: + ous_next.create(properties={'ou': ou}) + + users_day_of_week = UserAccounts(topo.standalone, f"ou=Dayofweek,ou=Keywords,{DEFAULT_SUFFIX}", rdn=None) + for user in ['EVERYDAY_KEY', 'TODAY_KEY', 'NODAY_KEY']: + users_day_of_week.create(properties={ + 'uid': user, + 'cn': user, + 'sn': 'user', + 'uidNumber': '1000', + 'gidNumber': '2000', + 'homeDirectory': '/home/' + user, + 'userPassword': PW_DM + }) + + users_ip = UserAccounts(topo.standalone, f"ou=IP,ou=Keywords,{DEFAULT_SUFFIX}", rdn=None) + for user in ['FULLIP_KEY', 'NETSCAPEIP_KEY', 'NOIP_KEY']: + users_ip.create(properties={ + 'uid': user, + 'cn': user, + 'sn': 'user', + 'uidNumber': '1000', + 'gidNumber': '2000', + 'homeDirectory': '/home/' + user, + 'userPassword': PW_DM + }) + + users_timeof_day = UserAccounts(topo.standalone, f"ou=Timeofday,ou=Keywords,{DEFAULT_SUFFIX}", rdn=None) + for user in ['FULLWORKER_KEY', 'DAYWORKER_KEY', 'NOWORKER_KEY', 'NIGHTWORKER_KEY']: + users_timeof_day.create(properties={ + 'uid': user, + 'cn': user, + 'sn': 'user', + 'uidNumber': '1000', + 'gidNumber': '2000', + 'homeDirectory': '/home/' + user, + 'userPassword': PW_DM + }) + + users_authmethod = UserAccounts(topo.standalone, f"ou=Authmethod,ou=Keywords,{DEFAULT_SUFFIX}", rdn=None) + for user in ['NONE_1_KEY', 'NONE_2_KEY', 'SIMPLE_1_KEY']: + users_authmethod.create(properties={ + 'uid': user, + 'cn': user, + 'sn': 'user', + 'uidNumber': '1000', + 'gidNumber': '2000', + 'homeDirectory': '/home/' + user, + 'userPassword': PW_DM + }) + + users_dns = UserAccounts(topo.standalone, f"ou=DNS,ou=Keywords,{DEFAULT_SUFFIX}", rdn=None) + for user in ['FULLDNS_KEY', 'SUNDNS_KEY', 'NODNS_KEY', 'NETSCAPEDNS_KEY']: + users_dns.create(properties={ + 'uid': user, + 'cn': user, + 'sn': 'user', + 'uidNumber': '1000', + 'gidNumber': '2000', + 'homeDirectory': '/home/' + user, + 'userPassword': PW_DM + }) + + def fin(): + """ + Deletes entries after the test. + """ + for user in users_day_of_week.list() + users_ip.list() + users_timeof_day.list() + \ + users_authmethod.list() + users_dns.list(): + user.delete() + + for ou in sorted(ous_next.list(), key=lambda x: len(x.dn), reverse=True): + ou.delete() + + request.addfinalizer(fin) diff --git a/dirsrvtests/tests/suites/acl/keywords_part2_test.py b/dirsrvtests/tests/suites/acl/keywords_part2_test.py new file mode 100644 index 000000000..b456c5785 --- /dev/null +++ b/dirsrvtests/tests/suites/acl/keywords_part2_test.py @@ -0,0 +1,386 @@ +# --- BEGIN COPYRIGHT BLOCK --- +# Copyright (C) 2019 Red Hat, Inc. +# All rights reserved. +# +# License: GPL (version 3 or any later version). +# See LICENSE for details. +# --- END COPYRIGHT BLOCK ---- + + +""" +This test script will test wrong/correct key value with ACIs. +""" + +import os +import time +from datetime import datetime +import pytest + +from lib389._constants import DEFAULT_SUFFIX, PW_DM +from lib389.idm.domain import Domain +from lib389.idm.organizationalunit import OrganizationalUnit +from lib389.idm.user import UserAccount + +import ldap + + +KEYWORDS_OU_KEY = "ou=Keywords,{}".format(DEFAULT_SUFFIX) +DAYOFWEEK_OU_KEY = "ou=Dayofweek,{}".format(KEYWORDS_OU_KEY) +IP_OU_KEY = "ou=IP,{}".format(KEYWORDS_OU_KEY) +TIMEOFDAY_OU_KEY = "ou=Timeofday,{}".format(KEYWORDS_OU_KEY) +EVERYDAY_KEY = "uid=EVERYDAY_KEY,{}".format(DAYOFWEEK_OU_KEY) +TODAY_KEY = "uid=TODAY_KEY,{}".format(DAYOFWEEK_OU_KEY) +NODAY_KEY = "uid=NODAY_KEY,{}".format(DAYOFWEEK_OU_KEY) +FULLIP_KEY = "uid=FULLIP_KEY,{}".format(IP_OU_KEY) +NETSCAPEIP_KEY = "uid=NETSCAPEIP_KEY,{}".format(IP_OU_KEY) +NOIP_KEY = "uid=NOIP_KEY,{}".format(IP_OU_KEY) +FULLWORKER_KEY = "uid=FULLWORKER_KEY,{}".format(TIMEOFDAY_OU_KEY) +DAYWORKER_KEY = "uid=DAYWORKER_KEY,{}".format(TIMEOFDAY_OU_KEY) +NIGHTWORKER_KEY = "uid=NIGHTWORKER_KEY,{}".format(TIMEOFDAY_OU_KEY) +NOWORKER_KEY = "uid=NOWORKER_KEY,{}".format(TIMEOFDAY_OU_KEY) + + +def test_access_from_certain_network_only_ip(topo, add_user, aci_of_user): + """ + User can access the data when connecting from certain network only as per the ACI. + + :id:4ec38296-7ac5-11e8-9816-8c16451d917b + :setup: Standalone Server + :steps: + 1. Add test entry + 2. Add ACI + 3. User should follow ACI role + :expectedresults: + 1. Entry should be added + 2. Operation should succeed + 3. Operation should succeed + """ + # Turn access log buffering off to make less time consuming + topo.standalone.config.set('nsslapd-accesslog-logbuffering', 'off') + + # Find the ip from ds logs , as we need to know the exact ip used by ds to run the instances. + # Wait till Access Log is generated + topo.standalone.restart() + + ip_ip = topo.standalone.ds_access_log.match('.* connection from ')[0].split()[-1] + + # Add ACI + domain = Domain(topo.standalone, DEFAULT_SUFFIX) + domain.add("aci", f'(target = "ldap:///{IP_OU_KEY}")(targetattr=*)(version 3.0; aci "IP aci"; ' + f'allow(all)userdn = "ldap:///{NETSCAPEIP_KEY}" and ip = "{ip_ip}" ;)') + + # create a new connection for the test + conn = UserAccount(topo.standalone, NETSCAPEIP_KEY).bind(PW_DM) + # Perform Operation + org = OrganizationalUnit(conn, IP_OU_KEY) + org.replace("seeAlso", "cn=1") + # remove the aci + domain.ensure_removed("aci", f'(target = "ldap:///{IP_OU_KEY}")(targetattr=*)(version 3.0; aci ' + f'"IP aci"; allow(all)userdn = "ldap:///{NETSCAPEIP_KEY}" and ' + f'ip = "{ip_ip}" ;)') + # Now add aci with new ip + domain.add("aci", f'(target = "ldap:///{IP_OU_KEY}")(targetattr=*)(version 3.0; aci "IP aci"; ' + f'allow(all)userdn = "ldap:///{NETSCAPEIP_KEY}" and ip = "100.1.1.1" ;)') + + # After changing the ip user cant access data + with pytest.raises(ldap.INSUFFICIENT_ACCESS): + org.replace("seeAlso", "cn=1") + + +def test_connectin_from_an_unauthorized_network(topo, add_user, aci_of_user): + """ + User cannot access the data when connectin from an unauthorized network as per the ACI. + + :id:52d1ecce-7ac5-11e8-9ad9-8c16451d917b + :setup: Standalone Server + :steps: + 1. Add test entry + 2. Add ACI + 3. User should follow ACI role + :expectedresults: + 1. Entry should be added + 2. Operation should succeed + 3. Operation should succeed + """ + # Find the ip from ds logs , as we need to know the exact ip used by ds to run the instances. + ip_ip = topo.standalone.ds_access_log.match('.* connection from ')[0].split()[-1] + # Add ACI + domain = Domain(topo.standalone, DEFAULT_SUFFIX) + domain.add("aci", f'(target = "ldap:///{IP_OU_KEY}")' + f'(targetattr=*)(version 3.0; aci "IP aci"; ' + f'allow(all) userdn = "ldap:///{NETSCAPEIP_KEY}" ' + f'and ip != "{ip_ip}" ;)') + + # create a new connection for the test + conn = UserAccount(topo.standalone, NETSCAPEIP_KEY).bind(PW_DM) + # Perform Operation + org = OrganizationalUnit(conn, IP_OU_KEY) + with pytest.raises(ldap.INSUFFICIENT_ACCESS): + org.replace("seeAlso", "cn=1") + # Remove the ACI + domain.ensure_removed('aci', domain.get_attr_vals('aci')[-1]) + # Add new ACI + domain.add('aci', f'(target = "ldap:///{IP_OU_KEY}")(targetattr=*)' + f'(version 3.0; aci "IP aci"; allow(all) ' + f'userdn = "ldap:///{NETSCAPEIP_KEY}" and ip = "{ip_ip}" ;)') + + # now user can access data + org.replace("seeAlso", "cn=1") + + +def test_ip_keyword_test_noip_cannot(topo, add_user, aci_of_user): + """ + User NoIP cannot assess the data as per the ACI. + + :id:570bc7f6-7ac5-11e8-88c1-8c16451d917b + :setup: Standalone Server + :steps: + 1. Add test entry + 2. Add ACI + 3. User should follow ACI role + :expectedresults: + 1. Entry should be added + 2. Operation should succeed + 3. Operation should succeed + """ + # Add ACI + Domain(topo.standalone, + DEFAULT_SUFFIX).add("aci", f'(target ="ldap:///{IP_OU_KEY}")' + f'(targetattr=*)(version 3.0; aci "IP aci"; allow(all) ' + f'userdn = "ldap:///{FULLIP_KEY}" and ip = "*" ;)') + + # Create a new connection for this test. + conn = UserAccount(topo.standalone, NOIP_KEY).bind(PW_DM) + # Perform Operation + org = OrganizationalUnit(conn, IP_OU_KEY) + with pytest.raises(ldap.INSUFFICIENT_ACCESS): + org.replace("seeAlso", "cn=1") + + +def test_user_can_access_the_data_at_any_time(topo, add_user, aci_of_user): + """ + User can access the data at any time as per the ACI. + + :id:5b4da91a-7ac5-11e8-bbda-8c16451d917b + :setup: Standalone Server + :steps: + 1. Add test entry + 2. Add ACI + 3. User should follow ACI role + :expectedresults: + 1. Entry should be added + 2. Operation should succeed + 3. Operation should succeed + """ + # Add ACI + Domain(topo.standalone, + DEFAULT_SUFFIX).add("aci", f'(target = "ldap:///{TIMEOFDAY_OU_KEY}")' + f'(targetattr=*)(version 3.0; aci "Timeofday aci"; ' + f'allow(all) userdn ="ldap:///{FULLWORKER_KEY}" and ' + f'(timeofday >= "0000" and timeofday <= "2359") ;)') + + # Create a new connection for this test. + conn = UserAccount(topo.standalone, FULLWORKER_KEY).bind(PW_DM) + # Perform Operation + org = OrganizationalUnit(conn, TIMEOFDAY_OU_KEY) + org.replace("seeAlso", "cn=1") + + +def test_user_can_access_the_data_only_in_the_morning(topo, add_user, aci_of_user): + """ + User can access the data only in the morning as per the ACI. + + :id:5f7d380c-7ac5-11e8-8124-8c16451d917b + :setup: Standalone Server + :steps: + 1. Add test entry + 2. Add ACI + 3. User should follow ACI role + :expectedresults: + 1. Entry should be added + 2. Operation should succeed + 3. Operation should succeed + """ + # Add ACI + Domain(topo.standalone, + DEFAULT_SUFFIX).add("aci", f'(target = "ldap:///{TIMEOFDAY_OU_KEY}")' + f'(targetattr=*)(version 3.0; aci "Timeofday aci"; ' + f'allow(all) userdn = "ldap:///{DAYWORKER_KEY}" ' + f'and timeofday < "1200" ;)') + + # Create a new connection for this test. + conn = UserAccount(topo.standalone, DAYWORKER_KEY).bind(PW_DM) + # Perform Operation + org = OrganizationalUnit(conn, TIMEOFDAY_OU_KEY) + if datetime.now().hour >= 12: + with pytest.raises(ldap.INSUFFICIENT_ACCESS): + org.replace("seeAlso", "cn=1") + else: + org.replace("seeAlso", "cn=1") + + +def test_user_can_access_the_data_only_in_the_afternoon(topo, add_user, aci_of_user): + """ + User can access the data only in the afternoon as per the ACI. + + :id:63eb5b1c-7ac5-11e8-bd46-8c16451d917b + :setup: Standalone Server + :steps: + 1. Add test entry + 2. Add ACI + 3. User should follow ACI role + :expectedresults: + 1. Entry should be added + 2. Operation should succeed + 3. Operation should succeed + """ + # Add ACI + Domain(topo.standalone, + DEFAULT_SUFFIX).add("aci", f'(target = "ldap:///{TIMEOFDAY_OU_KEY}")' + f'(targetattr=*)(version 3.0; aci "Timeofday aci"; ' + f'allow(all) userdn = "ldap:///{NIGHTWORKER_KEY}" ' + f'and timeofday > \'1200\' ;)') + + # create a new connection for the test + conn = UserAccount(topo.standalone, NIGHTWORKER_KEY).bind(PW_DM) + # Perform Operation + org = OrganizationalUnit(conn, TIMEOFDAY_OU_KEY) + if datetime.now().hour < 12: + with pytest.raises(ldap.INSUFFICIENT_ACCESS): + org.replace("seeAlso", "cn=1") + else: + org.replace("seeAlso", "cn=1") + + +def test_timeofday_keyword(topo, add_user, aci_of_user): + """ + User NOWORKER_KEY can access the data as per the ACI after removing + ACI it cant. + + :id:681dd58e-7ac5-11e8-bed1-8c16451d917b + :setup: Standalone Server + :steps: + 1. Add test entry + 2. Add ACI + 3. User should follow ACI role + :expectedresults: + 1. Entry should be added + 2. Operation should succeed + 3. Operation should succeed + """ + now = time.strftime("%c") + now_1 = "".join(now.split()[3].split(":"))[:4] + # Add ACI + domain = Domain(topo.standalone, DEFAULT_SUFFIX) + domain.add("aci", f'(target = "ldap:///{TIMEOFDAY_OU_KEY}")' + f'(targetattr=*)(version 3.0; aci "Timeofday aci"; ' + f'allow(all) userdn = "ldap:///{NOWORKER_KEY}" ' + f'and timeofday = \'{now_1}\' ;)') + + # Create a new connection for this test. + conn = UserAccount(topo.standalone, NOWORKER_KEY).bind(PW_DM) + # Perform Operation + org = OrganizationalUnit(conn, TIMEOFDAY_OU_KEY) + org.replace("seeAlso", "cn=1") + # Remove ACI + aci = domain.get_attr_vals_utf8('aci')[-1] + domain.ensure_removed('aci', aci) + assert aci not in domain.get_attr_vals_utf8('aci') + # after removing the ACI user cannot access the data + time.sleep(1) + with pytest.raises(ldap.INSUFFICIENT_ACCESS): + org.replace("seeAlso", "cn=1") + + +def test_dayofweek_keyword_test_everyday_can_access(topo, add_user, aci_of_user): + """ + User can access the data EVERYDAY_KEY as per the ACI. + + :id:6c5922ca-7ac5-11e8-8f01-8c16451d917b + :setup: Standalone Server + :steps: + 1. Add test entry + 2. Add ACI + 3. User should follow ACI role + :expectedresults: + 1. Entry should be added + 2. Operation should succeed + 3. Operation should succeed + """ + # Add ACI + Domain(topo.standalone, + DEFAULT_SUFFIX).add("aci", f'(target = "ldap:///{DAYOFWEEK_OU_KEY}")' + f'(targetattr=*)(version 3.0; aci "Dayofweek aci"; ' + f'allow(all) userdn = "ldap:///{EVERYDAY_KEY}" and ' + f'dayofweek = "Sun, Mon, Tue, Wed, Thu, Fri, Sat" ;)') + + # Create a new connection for this test. + conn = UserAccount(topo.standalone, EVERYDAY_KEY).bind(PW_DM) + # Perform Operation + org = OrganizationalUnit(conn, DAYOFWEEK_OU_KEY) + org.replace("seeAlso", "cn=1") + + +def test_dayofweek_keyword_today_can_access(topo, add_user, aci_of_user): + """ + User can access the data one day per week as per the ACI. + + :id:7131dc88-7ac5-11e8-acc2-8c16451d917b + :setup: Standalone Server + :steps: + 1. Add test entry + 2. Add ACI + 3. User should follow ACI role + :expectedresults: + 1. Entry should be added + 2. Operation should succeed + 3. Operation should succeed + """ + today_1 = time.strftime("%c").split()[0] + # Add ACI + Domain(topo.standalone, + DEFAULT_SUFFIX).add("aci", f'(target = "ldap:///{DAYOFWEEK_OU_KEY}")' + f'(targetattr=*)(version 3.0; aci "Dayofweek aci"; ' + f'allow(all) userdn = "ldap:///{TODAY_KEY}" ' + f'and dayofweek = \'{today_1}\' ;)') + + # Create a new connection for this test. + conn = UserAccount(topo.standalone, TODAY_KEY).bind(PW_DM) + # Perform Operation + org = OrganizationalUnit(conn, DAYOFWEEK_OU_KEY) + org.replace("seeAlso", "cn=1") + + +def test_user_cannot_access_the_data_at_all(topo, add_user, aci_of_user): + """ + User cannot access the data at all as per the ACI. + + :id:75cdac5e-7ac5-11e8-968a-8c16451d917b + :setup: Standalone Server + :steps: + 1. Add test entry + 2. Add ACI + 3. User should follow ACI role + :expectedresults: + 1. Entry should be added + 2. Operation should succeed + 3. Operation should succeed + """ + # Add ACI + Domain(topo.standalone, + DEFAULT_SUFFIX).add("aci", f'(target = "ldap:///{DAYOFWEEK_OU_KEY}")' + f'(targetattr=*)(version 3.0; aci "Dayofweek aci"; ' + f'allow(all) userdn = "ldap:///{TODAY_KEY}" ' + f'and dayofweek = "$NEW_DATE" ;)') + + # Create a new connection for this test. + conn = UserAccount(topo.standalone, NODAY_KEY).bind(PW_DM) + # Perform Operation + org = OrganizationalUnit(conn, DAYOFWEEK_OU_KEY) + with pytest.raises(ldap.INSUFFICIENT_ACCESS): + org.replace("seeAlso", "cn=1") + + +if __name__ == "__main__": + CURRENT_FILE = os.path.realpath(__file__) + pytest.main("-s -v %s" % CURRENT_FILE) diff --git a/dirsrvtests/tests/suites/acl/keywords_test.py b/dirsrvtests/tests/suites/acl/keywords_test.py new file mode 100644 index 000000000..9c00d429d --- /dev/null +++ b/dirsrvtests/tests/suites/acl/keywords_test.py @@ -0,0 +1,462 @@ +# --- BEGIN COPYRIGHT BLOCK --- +# Copyright (C) 2019 Red Hat, Inc. +# All rights reserved. +# +# License: GPL (version 3 or any later version). +# See LICENSE for details. +# --- END COPYRIGHT BLOCK ---- + +""" +This test script will test wrong/correct key value with ACIs. +""" + +import os +import socket +import pytest + +from lib389.idm.account import Anonymous +from lib389._constants import DEFAULT_SUFFIX, PW_DM +from lib389.idm.domain import Domain +from lib389.idm.organizationalunit import OrganizationalUnit +from lib389.idm.user import UserAccount + +import ldap + + +KEYWORDS_OU_KEY = "ou=Keywords,{}".format(DEFAULT_SUFFIX) +DNS_OU_KEY = "ou=DNS,{}".format(KEYWORDS_OU_KEY) +IP_OU_KEY = "ou=IP,{}".format(KEYWORDS_OU_KEY) +FULLIP_KEY = "uid=FULLIP_KEY,{}".format(IP_OU_KEY) +AUTHMETHOD_OU_KEY = "ou=Authmethod,{}".format(KEYWORDS_OU_KEY) +SIMPLE_1_KEY = "uid=SIMPLE_1_KEY,{}".format(AUTHMETHOD_OU_KEY) +FULLDNS_KEY = "uid=FULLDNS_KEY,{}".format(DNS_OU_KEY) +SUNDNS_KEY = "uid=SUNDNS_KEY,{}".format(DNS_OU_KEY) +NODNS_KEY = "uid=NODNS_KEY,{}".format(DNS_OU_KEY) +NETSCAPEDNS_KEY = "uid=NETSCAPEDNS_KEY,{}".format(DNS_OU_KEY) +NONE_1_KEY = "uid=NONE_1_KEY,{}".format(AUTHMETHOD_OU_KEY) +NONE_2_KEY = "uid=NONE_2_KEY,{}".format(AUTHMETHOD_OU_KEY) + + +NONE_ACI_KEY = f'(target = "ldap:///{AUTHMETHOD_OU_KEY}")' \ + f'(targetattr=*)(version 3.0; aci "Authmethod aci"; ' \ + f'allow(all) userdn = "ldap:///{NONE_1_KEY}" and authmethod = "none" ;)' + +SIMPLE_ACI_KEY = f'(target = "ldap:///{AUTHMETHOD_OU_KEY}")' \ + f'(targetattr=*)(version 3.0; aci "Authmethod aci"; ' \ + f'allow(all) userdn = "ldap:///{SIMPLE_1_KEY}" and authmethod = "simple" ;)' + + +def _add_aci(topo, name): + """ + This function will add ACI to DEFAULT_SUFFIX + """ + Domain(topo.standalone, DEFAULT_SUFFIX).add("aci", name) + + +def test_user_binds_with_a_password_and_can_access_the_data(topo, add_user, aci_of_user): + """ + User binds with a password and can access the data as per the ACI. + + :id:f6c4b6f0-7ac4-11e8-a517-8c16451d917b + :setup: Standalone Server + :steps: + 1. Add test entry + 2. Add ACI + 3. User should follow ACI role + :expectedresults: + 1. Entry should be added + 2. Operation should succeed + 3. Operation should succeed + """ + # Add ACI + _add_aci(topo, NONE_ACI_KEY) + # Create a new connection for this test. + conn = UserAccount(topo.standalone, NONE_1_KEY).bind(PW_DM) + # Perform Operation + OrganizationalUnit(conn, AUTHMETHOD_OU_KEY).replace("seeAlso", "cn=1") + + +def test_user_binds_with_a_bad_password_and_cannot_access_the_data(topo, add_user, aci_of_user): + """ + User binds with a BAD password and cannot access the data . + + :id:0397744e-7ac5-11e8-bfb1-8c16451d917b + :setup: Standalone Server + :steps: + 1. Add test entry + 2. Add ACI + 3. User should follow ACI role + :expectedresults: + 1. Entry should be added + 2. Operation should succeed + 3. Operation should succeed + """ + # User binds with a bad password and cannot access the data + with pytest.raises(ldap.UNWILLING_TO_PERFORM): + UserAccount(topo.standalone, NONE_1_KEY).bind("") + + +def test_anonymous_user_cannot_access_the_data(topo, add_user, aci_of_user): + """ + Anonymous user cannot access the data + + :id:0821a55c-7ac5-11e8-b214-8c16451d917b + :setup: Standalone Server + :steps: + 1. Add test entry + 2. Add ACI + 3. User should follow ACI role + :expectedresults: + 1. Entry should be added + 2. Operation should succeed + 3. Operation should succeed + """ + # Add ACI + _add_aci(topo, NONE_ACI_KEY) + + # Create a new connection for this test. + conn = Anonymous(topo.standalone).bind() + # Perform Operation + org = OrganizationalUnit(conn, AUTHMETHOD_OU_KEY) + with pytest.raises(ldap.INSUFFICIENT_ACCESS): + org.replace("seeAlso", "cn=1") + + +def test_authenticated_but_has_no_rigth_on_the_data(topo, add_user, aci_of_user): + """ + User has a password. He is authenticated but has no rigth on the data. + + :id:11be7ebe-7ac5-11e8-b754-8c16451d917b + :setup: Standalone Server + :steps: + 1. Add test entry + 2. Add ACI + 3. User should follow ACI role + :expectedresults: + 1. Entry should be added + 2. Operation should succeed + 3. Operation should succeed + """ + # Add ACI + _add_aci(topo, NONE_ACI_KEY) + + # Create a new connection for this test. + conn = UserAccount(topo.standalone, SIMPLE_1_KEY).bind(PW_DM) + # Perform Operation + org = OrganizationalUnit(conn, AUTHMETHOD_OU_KEY) + with pytest.raises(ldap.INSUFFICIENT_ACCESS): + org.replace("seeAlso", "cn=1") + + +def test_the_bind_client_is_accessing_the_directory(topo, add_user, aci_of_user): + """ + The bind rule is evaluated to be true if the client is accessing the directory as per the ACI. + + :id:1715bfb2-7ac5-11e8-8f2c-8c16451d917b + :setup: Standalone Server + :steps: + 1. Add test entry + 2. Add ACI + 3. User should follow ACI role + :expectedresults: + 1. Entry should be added + 2. Operation should succeed + 3. Operation should succeed + """ + # Add ACI + _add_aci(topo, SIMPLE_ACI_KEY) + + # Create a new connection for this test. + conn = UserAccount(topo.standalone, SIMPLE_1_KEY).bind(PW_DM) + # Perform Operation + OrganizationalUnit(conn, AUTHMETHOD_OU_KEY).replace("seeAlso", "cn=1") + + +def test_users_binds_with_a_password_and_can_access_the_data( + topo, add_user, aci_of_user): + """ + User binds with a password and can access the data as per the ACI. + + :id:1bd01cb4-7ac5-11e8-a2f1-8c16451d917b + :setup: Standalone Server + :steps: + 1. Add test entry + 2. Add ACI + 3. User should follow ACI role + :expectedresults: + 1. Entry should be added + 2. Operation should succeed + 3. Operation should succeed + """ + # Add ACI + _add_aci(topo, SIMPLE_ACI_KEY) + + # Create a new connection for this test. + conn = UserAccount(topo.standalone, SIMPLE_1_KEY).bind(PW_DM) + # Perform Operation + OrganizationalUnit(conn, AUTHMETHOD_OU_KEY).replace("seeAlso", "cn=1") + + +def test_user_binds_without_any_password_and_cannot_access_the_data(topo, add_user, aci_of_user): + """ + User binds without any password and cannot access the data + + :id:205777fa-7ac5-11e8-ba2f-8c16451d917b + :setup: Standalone Server + :steps: + 1. Add test entry + 2. Add ACI + 3. User should follow ACI role + :expectedresults: + 1. Entry should be added + 2. Operation should succeed + 3. Operation should succeed + """ + # Add ACI + _add_aci(topo, SIMPLE_ACI_KEY) + + # Create a new connection for this test. + conn = Anonymous(topo.standalone).bind() + # Perform Operation + org = OrganizationalUnit(conn, AUTHMETHOD_OU_KEY) + with pytest.raises(ldap.INSUFFICIENT_ACCESS): + org.replace("seeAlso", "cn=1") + + +def test_user_can_access_the_data_when_connecting_from_any_machine( + topo, add_user, aci_of_user +): + """ + User can access the data when connecting from any machine as per the ACI. + + :id:28cbc008-7ac5-11e8-934e-8c16451d917b + :setup: Standalone Server + :steps: + 1. Add test entry + 2. Add ACI + 3. User should follow ACI role + :expectedresults: + 1. Entry should be added + 2. Operation should succeed + 3. Operation should succeed + """ + # Add ACI + Domain(topo.standalone, DEFAULT_SUFFIX)\ + .add("aci", f'(target ="ldap:///{DNS_OU_KEY}")' + f'(targetattr=*)(version 3.0; aci "DNS aci"; allow(all) ' + f'userdn = "ldap:///{FULLDNS_KEY}" and dns = "*" ;)') + + # Create a new connection for this test. + conn = UserAccount(topo.standalone, FULLDNS_KEY).bind(PW_DM) + # Perform Operation + OrganizationalUnit(conn, DNS_OU_KEY).replace("seeAlso", "cn=1") + + +def test_user_can_access_the_data_when_connecting_from_internal_ds_network_only( + topo, add_user, aci_of_user +): + """ + User can access the data when connecting from internal ICNC network only as per the ACI. + :id:2cac2136-7ac5-11e8-8328-8c16451d917b + :setup: Standalone Server + :steps: + 1. Add test entry + 2. Add ACI + 3. User should follow ACI role + :expectedresults: + 1. Entry should be added + 2. Operation should succeed + 3. Operation should succeed + """ + dns_name = socket.getfqdn() + # Add ACI + Domain(topo.standalone, DEFAULT_SUFFIX).\ + add("aci", [f'(target = "ldap:///{DNS_OU_KEY}")' + f'(targetattr=*)(version 3.0; aci "DNS aci"; ' + f'allow(all) userdn = "ldap:///{SUNDNS_KEY}" and dns = "*redhat.com" ;)', + f'(target = "ldap:///{DNS_OU_KEY}")(targetattr=*)' + f'(version 3.0; aci "DNS aci"; allow(all) ' + f'userdn = "ldap:///{SUNDNS_KEY}" and dns = "{dns_name}" ;)']) + + # Create a new connection for this test. + conn = UserAccount(topo.standalone, SUNDNS_KEY).bind(PW_DM) + # Perform Operation + OrganizationalUnit(conn, DNS_OU_KEY).replace("seeAlso", "cn=1") + + +def test_user_can_access_the_data_when_connecting_from_some_network_only( + topo, add_user, aci_of_user +): + """ + User can access the data when connecting from some network only as per the ACI. + + :id:3098512a-7ac5-11e8-af85-8c16451d917b + :setup: Standalone Server + :steps: + 1. Add test entry + 2. Add ACI + 3. User should follow ACI role + :expectedresults: + 1. Entry should be added + 2. Operation should succeed + 3. Operation should succeed + """ + dns_name = socket.getfqdn() + # Add ACI + Domain(topo.standalone, DEFAULT_SUFFIX)\ + .add("aci", f'(target = "ldap:///{DNS_OU_KEY}")' + f'(targetattr=*)(version 3.0; aci "DNS aci"; allow(all) ' + f'userdn = "ldap:///{NETSCAPEDNS_KEY}" ' + f'and dns = "{dns_name}" ;)') + + # Create a new connection for this test. + conn = UserAccount(topo.standalone, NETSCAPEDNS_KEY).bind(PW_DM) + # Perform Operation + OrganizationalUnit(conn, DNS_OU_KEY).replace("seeAlso", "cn=1") + + +def test_from_an_unauthorized_network(topo, add_user, aci_of_user): + """ + User cannot access the data when connecting from an unauthorized network as per the ACI. + + :id:34cf9726-7ac5-11e8-bc12-8c16451d917b + :setup: Standalone Server + :steps: + 1. Add test entry + 2. Add ACI + 3. User should follow ACI role + :expectedresults: + 1. Entry should be added + 2. Operation should succeed + 3. Operation should succeed + """ + # Add ACI + Domain(topo.standalone, DEFAULT_SUFFIX).\ + add("aci", f'(target = "ldap:///{DNS_OU_KEY}")' + f'(targetattr=*)(version 3.0; aci "DNS aci"; allow(all) ' + f'userdn = "ldap:///{NETSCAPEDNS_KEY}" and dns != "red.iplanet.com" ;)') + + # Create a new connection for this test. + conn = UserAccount(topo.standalone, NETSCAPEDNS_KEY).bind(PW_DM) + # Perform Operation + OrganizationalUnit(conn, DNS_OU_KEY).replace("seeAlso", "cn=1") + + +def test_user_cannot_access_the_data_when_connecting_from_an_unauthorized_network_2( + topo, add_user, aci_of_user): + """ + User cannot access the data when connecting from an unauthorized network as per the ACI. + + :id:396bdd44-7ac5-11e8-8014-8c16451d917b + :setup: Standalone Server + :steps: + 1. Add test entry + 2. Add ACI + 3. User should follow ACI role + :expectedresults: + 1. Entry should be added + 2. Operation should succeed + 3. Operation should succeed + """ + # Add ACI + Domain(topo.standalone, DEFAULT_SUFFIX).\ + add("aci", f'(target = "ldap:///{DNS_OU_KEY}")' + f'(targetattr=*)(version 3.0; aci "DNS aci"; allow(all) ' + f'userdn = "ldap:///{NETSCAPEDNS_KEY}" ' + f'and dnsalias != "www.redhat.com" ;)') + + # Create a new connection for this test. + conn = UserAccount(topo.standalone, NETSCAPEDNS_KEY).bind(PW_DM) + # Perform Operation + OrganizationalUnit(conn, DNS_OU_KEY).replace("seeAlso", "cn=1") + + +def test_user_cannot_access_the_data_if_not_from_a_certain_domain(topo, add_user, aci_of_user): + """ + User cannot access the data if not from a certain domain as per the ACI. + :id:3d658972-7ac5-11e8-930f-8c16451d917b + :setup: Standalone Server + :steps: + 1. Add test entry + 2. Add ACI + 3. User should follow ACI role + :expectedresults: + 1. Entry should be added + 2. Operation should succeed + 3. Operation should succeed + """ + # Add ACI + Domain(topo.standalone, DEFAULT_SUFFIX).\ + add("aci", f'(target = "ldap:///{DNS_OU_KEY}")(targetattr=*)' + f'(version 3.0; aci "DNS aci"; allow(all) ' + f'userdn = "ldap:///{NODNS_KEY}" ' + f'and dns = "RAP.rock.SALSA.house.COM" ;)') + + # Create a new connection for this test. + conn = UserAccount(topo.standalone, NODNS_KEY).bind(PW_DM) + # Perform Operation + org = OrganizationalUnit(conn, AUTHMETHOD_OU_KEY) + with pytest.raises(ldap.INSUFFICIENT_ACCESS): + org.replace("seeAlso", "cn=1") + + +def test_dnsalias_keyword_test_nodns_cannot(topo, add_user, aci_of_user): + """ + Dnsalias Keyword NODNS_KEY cannot assess data as per the ACI. + + :id:41b467be-7ac5-11e8-89a3-8c16451d917b + :setup: Standalone Server + :steps: + 1. Add test entry + 2. Add ACI + 3. User should follow ACI role + :expectedresults: + 1. Entry should be added + 2. Operation should succeed + 3. Operation should succeed + """ + # Add ACI + Domain(topo.standalone, DEFAULT_SUFFIX).\ + add("aci", f'(target = "ldap:///{DNS_OU_KEY}")(targetattr=*)' + f'(version 3.0; aci "DNS aci"; allow(all) ' + f'userdn = "ldap:///{NODNS_KEY}" and ' + f'dnsalias = "RAP.rock.SALSA.house.COM" ;)') + + # Create a new connection for this test. + conn = UserAccount(topo.standalone, NODNS_KEY).bind(PW_DM) + # Perform Operation + org = OrganizationalUnit(conn, DNS_OU_KEY) + with pytest.raises(ldap.INSUFFICIENT_ACCESS): + org.replace("seeAlso", "cn=1") + + +def test_user_can_access_the_data_when_connecting_from_any_machine_2(topo, add_user, aci_of_user): + """ + User can access the data when connecting from any machine as per the ACI. + + :id:461e761e-7ac5-11e8-9ae4-8c16451d917b + :setup: Standalone Server + :steps: + 1. Add test entry + 2. Add ACI + 3. User should follow ACI role + :expectedresults: + 1. Entry should be added + 2. Operation should succeed + 3. Operation should succeed + """ + # Add ACI + Domain(topo.standalone, DEFAULT_SUFFIX).\ + add("aci", f'(target ="ldap:///{IP_OU_KEY}")(targetattr=*)' + f'(version 3.0; aci "IP aci"; allow(all) ' + f'userdn = "ldap:///{FULLIP_KEY}" and ip = "*" ;)') + + # Create a new connection for this test. + conn = UserAccount(topo.standalone, FULLIP_KEY).bind(PW_DM) + # Perform Operation + OrganizationalUnit(conn, IP_OU_KEY).replace("seeAlso", "cn=1") + + +if __name__ == "__main__": + CURRENT_FILE = os.path.realpath(__file__) + pytest.main("-s -v %s" % CURRENT_FILE)
0
b9901f14706138cc0e4a53ee96bbbb26c74ce069
389ds/389-ds-base
Ticket 47740 - Fix coverity issues - Part 5 12494 - resource leak - /ldap/servers/slapd/saslbind.c 12487 - resource leak - /ldap/servers/plugins/replication/urp.c 12486 - resource leak - /ldap/servers/plugins/acl/acleffectiverights.c 12480 - resource leak - lib/ldaputil/certmap.c 12478 - resource leak - lib/ldaputil/certmap.c 12477 - resource leak - lib/ldaputil/certmap.c https://fedorahosted.org/389/ticket/47740 Reviewed by: rmeggins(Thanks!)
commit b9901f14706138cc0e4a53ee96bbbb26c74ce069 Author: Mark Reynolds <[email protected]> Date: Thu Mar 13 14:07:49 2014 -0400 Ticket 47740 - Fix coverity issues - Part 5 12494 - resource leak - /ldap/servers/slapd/saslbind.c 12487 - resource leak - /ldap/servers/plugins/replication/urp.c 12486 - resource leak - /ldap/servers/plugins/acl/acleffectiverights.c 12480 - resource leak - lib/ldaputil/certmap.c 12478 - resource leak - lib/ldaputil/certmap.c 12477 - resource leak - lib/ldaputil/certmap.c https://fedorahosted.org/389/ticket/47740 Reviewed by: rmeggins(Thanks!) diff --git a/ldap/servers/plugins/acl/acleffectiverights.c b/ldap/servers/plugins/acl/acleffectiverights.c index e4537afd5..dc22451b7 100644 --- a/ldap/servers/plugins/acl/acleffectiverights.c +++ b/ldap/servers/plugins/acl/acleffectiverights.c @@ -132,6 +132,7 @@ _ger_g_permission_granted ( } else { + slapi_ch_free_string(&proxydn); /* this could still have been set - free it */ requestor_sdn = &(pb->pb_op->o_sdn); } if ( slapi_sdn_get_dn (requestor_sdn) == NULL ) diff --git a/ldap/servers/plugins/replication/urp.c b/ldap/servers/plugins/replication/urp.c index 471bf8d5f..b6fe2ffc4 100644 --- a/ldap/servers/plugins/replication/urp.c +++ b/ldap/servers/plugins/replication/urp.c @@ -1280,6 +1280,7 @@ get_dn_plus_uniqueid(char *sessionid, const Slapi_DN *oldsdn, const char *unique * parentdn is normalized by slapi_sdn_get_dn. */ newdn = slapi_ch_smprintf("%s,%s", slapi_rdn_get_rdn(rdn), parentdn); + slapi_ch_free_string(&parentdn); } slapi_rdn_free(&rdn); return newdn; diff --git a/ldap/servers/slapd/saslbind.c b/ldap/servers/slapd/saslbind.c index ba606eb96..6f53aea25 100644 --- a/ldap/servers/slapd/saslbind.c +++ b/ldap/servers/slapd/saslbind.c @@ -522,6 +522,7 @@ static int ids_sasl_getpluginpath(sasl_conn_t *conn, const char **path) */ char *pluginpath = config_get_saslpath(); if ((!pluginpath) || (*pluginpath == '\0')) { + slapi_ch_free_string(&pluginpath); pluginpath = ldaputil_get_saslpath(); } *path = pluginpath; diff --git a/lib/ldaputil/certmap.c b/lib/ldaputil/certmap.c index e27633c7b..aa5bafa10 100644 --- a/lib/ldaputil/certmap.c +++ b/lib/ldaputil/certmap.c @@ -500,13 +500,13 @@ static int process_certinfo (LDAPUCertMapInfo_t *certinfo) char *searchAttr = 0; if (!ldapu_strcasecmp(certinfo->issuerName, "default")) { - default_certmap_info = certinfo; + default_certmap_info = certinfo; } else if (!certinfo->issuerDN) { - return LDAPU_ERR_NO_ISSUERDN_IN_CONFIG_FILE; + return LDAPU_ERR_NO_ISSUERDN_IN_CONFIG_FILE; } else { - rv = ldapu_list_add_info(certmap_listinfo, certinfo); + rv = ldapu_list_add_info(certmap_listinfo, certinfo); } if (rv != LDAPU_SUCCESS) return rv; @@ -515,21 +515,21 @@ static int process_certinfo (LDAPUCertMapInfo_t *certinfo) rv = ldapu_certmap_info_attrval (certinfo, LDAPU_ATTR_DNCOMPS, &dncomps); if (rv == LDAPU_SUCCESS && dncomps) { - certinfo->dncompsState = COMPS_HAS_ATTRS; - tolower_string(dncomps); + certinfo->dncompsState = COMPS_HAS_ATTRS; + tolower_string(dncomps); } else if (rv == LDAPU_FAILED) { - certinfo->dncompsState = COMPS_COMMENTED_OUT; - rv = LDAPU_SUCCESS; + certinfo->dncompsState = COMPS_COMMENTED_OUT; + rv = LDAPU_SUCCESS; } else if (rv == LDAPU_SUCCESS && !dncomps) { - certinfo->dncompsState = COMPS_EMPTY; - dncomps = ""; /* present but empty */ + certinfo->dncompsState = COMPS_EMPTY; + dncomps = ""; /* present but empty */ } rv = parse_into_bitmask (dncomps, &certinfo->dncomps, -1); - if (dncomps && *dncomps) free(dncomps); + free(dncomps); dncomps = NULL; if (rv != LDAPU_SUCCESS) return rv; @@ -538,21 +538,21 @@ static int process_certinfo (LDAPUCertMapInfo_t *certinfo) &filtercomps); if (rv == LDAPU_SUCCESS && filtercomps) { - certinfo->filtercompsState = COMPS_HAS_ATTRS; - tolower_string(filtercomps); + certinfo->filtercompsState = COMPS_HAS_ATTRS; + tolower_string(filtercomps); } else if (rv == LDAPU_FAILED) { - certinfo->filtercompsState = COMPS_COMMENTED_OUT; - rv = LDAPU_SUCCESS; + certinfo->filtercompsState = COMPS_COMMENTED_OUT; + rv = LDAPU_SUCCESS; } else if (rv == LDAPU_SUCCESS && !filtercomps) { - certinfo->filtercompsState = COMPS_EMPTY; - filtercomps = ""; /* present but empty */ + certinfo->filtercompsState = COMPS_EMPTY; + filtercomps = ""; /* present but empty */ } rv = parse_into_bitmask (filtercomps, &certinfo->filtercomps, 0); - if (filtercomps && *filtercomps) free(filtercomps); + if (filtercomps) free(filtercomps); if (rv != LDAPU_SUCCESS) return rv; @@ -560,15 +560,15 @@ static int process_certinfo (LDAPUCertMapInfo_t *certinfo) rv = ldapu_certmap_info_attrval(certinfo, LDAPU_ATTR_CERTMAP_LDAP_ATTR, &searchAttr); - if (rv == LDAPU_FAILED || !searchAttr || !*searchAttr) - rv = LDAPU_SUCCESS; - else { - certinfo->searchAttr = searchAttr ? strdup(searchAttr) : 0; + if (rv == LDAPU_FAILED || !searchAttr){ + rv = LDAPU_SUCCESS; + } else { + certinfo->searchAttr = searchAttr; - if (searchAttr && !certinfo->searchAttr) - rv = LDAPU_ERR_OUT_OF_MEMORY; - else - rv = LDAPU_SUCCESS; + if (searchAttr && !certinfo->searchAttr) + rv = LDAPU_ERR_OUT_OF_MEMORY; + else + rv = LDAPU_SUCCESS; } if (rv != LDAPU_SUCCESS) return rv; @@ -578,73 +578,69 @@ static int process_certinfo (LDAPUCertMapInfo_t *certinfo) rv = ldapu_certmap_info_attrval(certinfo, LDAPU_ATTR_VERIFYCERT, &verify); if (rv == LDAPU_SUCCESS) { - if (!ldapu_strcasecmp(verify, "on")) - certinfo->verifyCert = 1; - else if (!ldapu_strcasecmp(verify, "off")) - certinfo->verifyCert = 0; - else if (!verify || !*verify) /* for mail/news backward compatibilty */ - certinfo->verifyCert = 1; /* otherwise, this should be an error */ - else - rv = LDAPU_ERR_MISSING_VERIFYCERT_VAL; + if (!ldapu_strcasecmp(verify, "on")) + certinfo->verifyCert = 1; + else if (!ldapu_strcasecmp(verify, "off")) + certinfo->verifyCert = 0; + else if (!verify || !*verify) /* for mail/news backward compatibilty */ + certinfo->verifyCert = 1; /* otherwise, this should be an error */ + else + rv = LDAPU_ERR_MISSING_VERIFYCERT_VAL; } else if (rv == LDAPU_FAILED) rv = LDAPU_SUCCESS; - if (verify && *verify) free(verify); + if (verify) free(verify); if (rv != LDAPU_SUCCESS) return rv; { - PRLibrary *lib = 0; + PRLibrary *lib = 0; - /* look for the library property and load it */ - rv = ldapu_certmap_info_attrval(certinfo, LDAPU_ATTR_LIBRARY, &libname); + /* look for the library property and load it */ + rv = ldapu_certmap_info_attrval(certinfo, LDAPU_ATTR_LIBRARY, &libname); - if (rv == LDAPU_SUCCESS) { - if (libname && *libname) { - lib = PR_LoadLibrary(libname); - if (!lib) rv = LDAPU_ERR_UNABLE_TO_LOAD_PLUGIN; - } - else { - rv = LDAPU_ERR_MISSING_LIBNAME; - } - } - else if (rv == LDAPU_FAILED) rv = LDAPU_SUCCESS; + if (rv == LDAPU_SUCCESS) { + if (libname && *libname) { + lib = PR_LoadLibrary(libname); + if (!lib) rv = LDAPU_ERR_UNABLE_TO_LOAD_PLUGIN; + } else { + rv = LDAPU_ERR_MISSING_LIBNAME; + } + } else if (rv == LDAPU_FAILED) rv = LDAPU_SUCCESS; - if (libname) free(libname); - if (rv != LDAPU_SUCCESS) return rv; + if (libname) free(libname); + if (rv != LDAPU_SUCCESS) return rv; - /* look for the InitFn property, find it in the libray and call it */ - rv = ldapu_certmap_info_attrval(certinfo, LDAPU_ATTR_INITFN, &fname); + /* look for the InitFn property, find it in the libray and call it */ + rv = ldapu_certmap_info_attrval(certinfo, LDAPU_ATTR_INITFN, &fname); - if (rv == LDAPU_SUCCESS) { - if (fname && *fname) { - /* If lib is NULL, PR_FindSymbol will search all libs loaded - * through PR_LoadLibrary. - */ - CertMapInitFn_t fn = (CertMapInitFn_t)PR_FindSymbol(lib, fname); + if (rv == LDAPU_SUCCESS) { + if (fname && *fname) { + /* If lib is NULL, PR_FindSymbol will search all libs loaded + * through PR_LoadLibrary. + */ + CertMapInitFn_t fn = (CertMapInitFn_t)PR_FindSymbol(lib, fname); - if (!fn) { - rv = LDAPU_ERR_MISSING_INIT_FN_IN_LIB; - } - else { - rv = (*fn)(certinfo, certinfo->issuerName, - certinfo->issuerDN, this_dllname); - } - } - else { - rv = LDAPU_ERR_MISSING_INIT_FN_NAME; - } - } - else if (lib) { - /* If library is specified, init function must be specified */ - /* If init fn is specified, library may not be specified */ - rv = LDAPU_ERR_MISSING_INIT_FN_IN_CONFIG; - } - else if (rv == LDAPU_FAILED) rv = LDAPU_SUCCESS; - - if (fname) free(fname); + if (!fn) { + rv = LDAPU_ERR_MISSING_INIT_FN_IN_LIB; + } else { + rv = (*fn)(certinfo, certinfo->issuerName, + certinfo->issuerDN, this_dllname); + } + } else { + rv = LDAPU_ERR_MISSING_INIT_FN_NAME; + } + } else if (lib) { + /* If library is specified, init function must be specified */ + /* If init fn is specified, library may not be specified */ + rv = LDAPU_ERR_MISSING_INIT_FN_IN_CONFIG; + } else if (rv == LDAPU_FAILED){ + rv = LDAPU_SUCCESS; + } + + if (fname) free(fname); - if (rv != LDAPU_SUCCESS) return rv; + if (rv != LDAPU_SUCCESS) return rv; } return rv;
0
5a5ff2640d6e66c925550498211743a8f78a8477
389ds/389-ds-base
modify operations without values need to be written to the changelog reviewed by Mark, Thanks
commit 5a5ff2640d6e66c925550498211743a8f78a8477 Author: Ludwig Krispenz <[email protected]> Date: Wed Mar 13 10:53:44 2013 +0100 modify operations without values need to be written to the changelog reviewed by Mark, Thanks diff --git a/ldap/servers/plugins/replication/cl5_api.c b/ldap/servers/plugins/replication/cl5_api.c index 934761bdf..af4e606e3 100644 --- a/ldap/servers/plugins/replication/cl5_api.c +++ b/ldap/servers/plugins/replication/cl5_api.c @@ -2538,11 +2538,15 @@ _cl5WriteMod (LDAPMod *mod, char **buff) memcpy (pos, &count, sizeof (count)); pos += sizeof (PRInt32); + /* if the mod has no values, eg delete attr or replace attr without values + * do not reset buffer + */ + rc = 0; + bv = slapi_mod_get_first_value (&smod); while (bv) { encbv = NULL; - rc = 0; rc = clcrypt_encrypt_value(s_cl5Desc.clcrypt_handle, bv, &encbv); if (rc > 0) {
0
0f2b46ea7077ff9bc3fae5b1b092b105ad625b0d
389ds/389-ds-base
Issue 4169 - UI - port charts to PF4 Description: Ported the charts under the monitor tab to use PF4 sparkline charts and provide realtime stats on the the caches. Relates: https://github.com/389ds/389-ds-base/issues/4169 Reviewed by: spichugi(Thanks!)
commit 0f2b46ea7077ff9bc3fae5b1b092b105ad625b0d Author: Mark Reynolds <[email protected]> Date: Wed Feb 17 18:35:24 2021 -0500 Issue 4169 - UI - port charts to PF4 Description: Ported the charts under the monitor tab to use PF4 sparkline charts and provide realtime stats on the the caches. Relates: https://github.com/389ds/389-ds-base/issues/4169 Reviewed by: spichugi(Thanks!) diff --git a/src/cockpit/389-console/package-lock.json b/src/cockpit/389-console/package-lock.json index 5883e7786..c34ad0a20 100644 --- a/src/cockpit/389-console/package-lock.json +++ b/src/cockpit/389-console/package-lock.json @@ -2792,6 +2792,59 @@ "resolved": "https://registry.npmjs.org/@patternfly/patternfly/-/patternfly-2.71.7.tgz", "integrity": "sha512-JjgBJcPOiZhEyixc6mY781eMmVL+qm5gs/h7IipVfps3IoadEZVlvOjffBCfqOVWug0DJbv6APqrZqOQmzISMA==" }, + "@patternfly/react-charts": { + "version": "6.13.8", + "resolved": "https://registry.npmjs.org/@patternfly/react-charts/-/react-charts-6.13.8.tgz", + "integrity": "sha512-IEQBtUCNMAA6JnLBcWj4RUQ5a80n/uBw3a8FzeL5x90Fp6pR6nc5wVjVH8WcO7minw3QMRwxtcu5itW/v+Ga0g==", + "requires": { + "@patternfly/patternfly": "4.80.3", + "@patternfly/react-styles": "^4.7.29", + "@patternfly/react-tokens": "^4.9.26", + "hoist-non-react-statics": "^3.3.0", + "lodash": "^4.17.19", + "tslib": "1.13.0", + "victory-area": "^35.4.4", + "victory-axis": "^35.4.4", + "victory-bar": "^35.4.4", + "victory-chart": "^35.4.4", + "victory-core": "^35.4.4", + "victory-create-container": "^35.4.4", + "victory-group": "^35.4.4", + "victory-legend": "^35.4.4", + "victory-line": "^35.4.4", + "victory-pie": "^35.4.4", + "victory-scatter": "^35.4.4", + "victory-stack": "^35.4.4", + "victory-tooltip": "^35.4.4", + "victory-voronoi-container": "^35.4.4", + "victory-zoom-container": "^35.4.4" + }, + "dependencies": { + "@patternfly/patternfly": { + "version": "4.80.3", + "resolved": "https://registry.npmjs.org/@patternfly/patternfly/-/patternfly-4.80.3.tgz", + "integrity": "sha512-YLUk4L6iCBXql92YP6zHg0FdlnEkd5/3V+uz/A3UoBuuDdEoyDpx4M/Tf56R7IXmYiRaHE1mToJHPDYypIlnmw==" + }, + "hoist-non-react-statics": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/hoist-non-react-statics/-/hoist-non-react-statics-3.3.2.tgz", + "integrity": "sha512-/gGivxi8JPKWNm/W0jSmzcMPpfpPLc3dY/6GxhX2hQ9iGj3aDfklV4ET7NjKpSinLpJ5vafa9iiGIEZg10SfBw==", + "requires": { + "react-is": "^16.7.0" + } + }, + "react-is": { + "version": "16.13.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", + "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==" + }, + "tslib": { + "version": "1.13.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.13.0.tgz", + "integrity": "sha512-i/6DQjL8Xf3be4K/E6Wgpekn5Qasl1usyw++dAA35Ue5orEn65VIxOA+YvNNl9HV3qv70T7CNwjODHZrLwvd1Q==" + } + } + }, "@patternfly/react-core": { "version": "4.90.2", "resolved": "https://registry.npmjs.org/@patternfly/react-core/-/react-core-4.90.2.tgz", @@ -6349,6 +6402,84 @@ "resolved": "https://registry.npmjs.org/d3/-/d3-3.5.17.tgz", "integrity": "sha1-vEZ0gAQ3iyGjYMn8fPUjF5B2L7g=" }, + "d3-array": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-1.2.4.tgz", + "integrity": "sha512-KHW6M86R+FUPYGb3R5XiYjXPq7VzwxZ22buHhAEVG5ztoEcZZMLov530mmccaqA1GghZArjQV46fuc8kUqhhHw==" + }, + "d3-collection": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/d3-collection/-/d3-collection-1.0.7.tgz", + "integrity": "sha512-ii0/r5f4sjKNTfh84Di+DpztYwqKhEyUlKoPrzUFfeSkWxjW49xU2QzO9qrPrNkpdI0XJkfzvmTu8V2Zylln6A==" + }, + "d3-color": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/d3-color/-/d3-color-1.4.1.tgz", + "integrity": "sha512-p2sTHSLCJI2QKunbGb7ocOh7DgTAn8IrLx21QRc/BSnodXM4sv6aLQlnfpvehFMLZEfBc6g9pH9SWQccFYfJ9Q==" + }, + "d3-ease": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-1.0.7.tgz", + "integrity": "sha512-lx14ZPYkhNx0s/2HX5sLFUI3mbasHjSSpwO/KaaNACweVwxUruKyWVcb293wMv1RqTPZyZ8kSZ2NogUZNcLOFQ==" + }, + "d3-format": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/d3-format/-/d3-format-1.4.5.tgz", + "integrity": "sha512-J0piedu6Z8iB6TbIGfZgDzfXxUFN3qQRMofy2oPdXzQibYGqPB/9iMcxr/TGalU+2RsyDO+U4f33id8tbnSRMQ==" + }, + "d3-interpolate": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-1.4.0.tgz", + "integrity": "sha512-V9znK0zc3jOPV4VD2zZn0sDhZU3WAE2bmlxdIwwQPPzPjvyLkd8B3JUVdS1IDUFDkWZ72c9qnv1GK2ZagTZ8EA==", + "requires": { + "d3-color": "1" + } + }, + "d3-path": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/d3-path/-/d3-path-1.0.9.tgz", + "integrity": "sha512-VLaYcn81dtHVTjEHd8B+pbe9yHWpXKZUC87PzoFmsFrJqgFwDe/qxfp5MlfsfM1V5E/iVt0MmEbWQ7FVIXh/bg==" + }, + "d3-scale": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-1.0.7.tgz", + "integrity": "sha512-KvU92czp2/qse5tUfGms6Kjig0AhHOwkzXG0+PqIJB3ke0WUv088AHMZI0OssO9NCkXt4RP8yju9rpH8aGB7Lw==", + "requires": { + "d3-array": "^1.2.0", + "d3-collection": "1", + "d3-color": "1", + "d3-format": "1", + "d3-interpolate": "1", + "d3-time": "1", + "d3-time-format": "2" + } + }, + "d3-shape": { + "version": "1.3.7", + "resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-1.3.7.tgz", + "integrity": "sha512-EUkvKjqPFUAZyOlhY5gzCxCeI0Aep04LwIRpsZ/mLFelJiUfnK56jo5JMDSE7yyP2kLSb6LtF+S5chMk7uqPqw==", + "requires": { + "d3-path": "1" + } + }, + "d3-time": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/d3-time/-/d3-time-1.1.0.tgz", + "integrity": "sha512-Xh0isrZ5rPYYdqhAVk8VLnMEidhz5aP7htAADH6MfzgmmicPkTo8LhkLxci61/lCB7n7UmE3bN0leRt+qvkLxA==" + }, + "d3-time-format": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-2.3.0.tgz", + "integrity": "sha512-guv6b2H37s2Uq/GefleCDtbe0XZAuy7Wa49VGkPVPMfLL9qObgBST3lEHJBMUp8S7NdLQAGIvr2KXk8Hc98iKQ==", + "requires": { + "d3-time": "1" + } + }, + "d3-timer": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-1.0.10.tgz", + "integrity": "sha512-B1JDm0XDaQC+uvo4DT79H0XmBskgS3l6Ve+1SBCfxgmtIb1AVrPIoqd+nPSv+loMX8szQ0sVUhGngL7D5QPiXw==" + }, "dashdash": { "version": "1.14.1", "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz", @@ -6525,6 +6656,19 @@ } } }, + "delaunator": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/delaunator/-/delaunator-4.0.1.tgz", + "integrity": "sha512-WNPWi1IRKZfCt/qIDMfERkDp93+iZEmOxN2yy4Jg+Xhv8SLk2UTqqbe1sfiipn0and9QrE914/ihdx82Y/Giag==" + }, + "delaunay-find": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/delaunay-find/-/delaunay-find-0.0.5.tgz", + "integrity": "sha512-7yAJ/wmKWj3SgqjtkGqT/RCwI0HWAo5YnHMoF5nYXD8cdci+YSo23iPmgrZUNOpDxRWN91PqxUvMMr2lKpjr+w==", + "requires": { + "delaunator": "^4.0.0" + } + }, "delayed-stream": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", @@ -15688,6 +15832,11 @@ "uuid": "^3.1.0" } }, + "react-fast-compare": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/react-fast-compare/-/react-fast-compare-2.0.4.tgz", + "integrity": "sha512-suNP+J1VU1MWFKcyt7RtjiSWUjvidmQSlqu+eHslq+342xCbGTYmC0mEhPCOHxlW0CywylOC1u2DFAT+bv4dBw==" + }, "react-fontawesome": { "version": "1.7.1", "resolved": "https://registry.npmjs.org/react-fontawesome/-/react-fontawesome-1.7.1.tgz", @@ -18579,6 +18728,233 @@ "extsprintf": "^1.2.0" } }, + "victory-area": { + "version": "35.4.8", + "resolved": "https://registry.npmjs.org/victory-area/-/victory-area-35.4.8.tgz", + "integrity": "sha512-eNr6ZFonAhCHoCetA9g5fJxFn+g+5YpgBmlbxwzE7kgKg+jH7+ViD/R2aNcY6aoljiRyE6DbSVAxDiksPp0q1A==", + "requires": { + "d3-shape": "^1.2.0", + "lodash": "^4.17.19", + "prop-types": "^15.5.8", + "victory-core": "^35.4.8" + } + }, + "victory-axis": { + "version": "35.4.8", + "resolved": "https://registry.npmjs.org/victory-axis/-/victory-axis-35.4.8.tgz", + "integrity": "sha512-+DcevVoIL6tjbTHwGZ2DzZiRl+Pwwowuf99mL10ECRzY+Iuc+s+x4o3gpw/HWJ/dGOyD+kPKPcwilmaQLnEOhQ==", + "requires": { + "lodash": "^4.17.19", + "prop-types": "^15.5.8", + "victory-core": "^35.4.8" + } + }, + "victory-bar": { + "version": "35.4.8", + "resolved": "https://registry.npmjs.org/victory-bar/-/victory-bar-35.4.8.tgz", + "integrity": "sha512-9EUxHoX2R7t/iOZEWDtpypX13V2+Pngo2V3I9uW7lHtg+SCKTjGjHP1sJSbwLP3WxHl7dHg3Jg+ok04cych6XQ==", + "requires": { + "d3-shape": "^1.2.0", + "lodash": "^4.17.19", + "prop-types": "^15.5.8", + "victory-core": "^35.4.8" + } + }, + "victory-brush-container": { + "version": "35.4.8", + "resolved": "https://registry.npmjs.org/victory-brush-container/-/victory-brush-container-35.4.8.tgz", + "integrity": "sha512-/nTpCijvLfCr86M5P3sr8umLsRJM7GaYODqagRChcPIS5O4oEzRZsgEVhOYmWZZiS56PIjMoLAzMBvgsiwBsDg==", + "requires": { + "lodash": "^4.17.19", + "prop-types": "^15.5.8", + "react-fast-compare": "^2.0.0", + "victory-core": "^35.4.8" + } + }, + "victory-chart": { + "version": "35.4.9", + "resolved": "https://registry.npmjs.org/victory-chart/-/victory-chart-35.4.9.tgz", + "integrity": "sha512-OM8LFjBdzc2iujPlNj7WuwygMdCFjKLGWPN9dxzkpPhGaqQnH+k1rQaEz/DQC42x83QRlU93VwVcRTl9h3MzeA==", + "requires": { + "lodash": "^4.17.19", + "prop-types": "^15.5.8", + "react-fast-compare": "^2.0.0", + "victory-axis": "^35.4.8", + "victory-core": "^35.4.8", + "victory-polar-axis": "^35.4.8", + "victory-shared-events": "^35.4.9" + } + }, + "victory-core": { + "version": "35.4.8", + "resolved": "https://registry.npmjs.org/victory-core/-/victory-core-35.4.8.tgz", + "integrity": "sha512-4yhNeeyttEe24mAG4DUPP3RvditQU+364WTnUS05ZHPrACyDWYTOfN5+L0GzmvkJ3kbteQkfX3UJgpHwwqVmug==", + "requires": { + "d3-ease": "^1.0.0", + "d3-interpolate": "^1.1.1", + "d3-scale": "^1.0.0", + "d3-shape": "^1.2.0", + "d3-timer": "^1.0.0", + "lodash": "^4.17.19", + "prop-types": "^15.5.8", + "react-fast-compare": "^2.0.0" + } + }, + "victory-create-container": { + "version": "35.4.8", + "resolved": "https://registry.npmjs.org/victory-create-container/-/victory-create-container-35.4.8.tgz", + "integrity": "sha512-1qYRi+npvvWurDjdrC2IthxvTWeKcP1nw8bw2OpL+oG21k/mQBrPGT2GtAmUBGp3e8LDr6BwrCx32FGd01PWYw==", + "requires": { + "lodash": "^4.17.19", + "victory-brush-container": "^35.4.8", + "victory-core": "^35.4.8", + "victory-cursor-container": "^35.4.8", + "victory-selection-container": "^35.4.8", + "victory-voronoi-container": "^35.4.8", + "victory-zoom-container": "^35.4.8" + } + }, + "victory-cursor-container": { + "version": "35.4.8", + "resolved": "https://registry.npmjs.org/victory-cursor-container/-/victory-cursor-container-35.4.8.tgz", + "integrity": "sha512-KLQug3j4dY8nkcL5CrPqO/pz48hH9chLS86eFiN56gUzLCHx81lEujc01YrsFxQat1cOyC3LghyM+pnexLMWEQ==", + "requires": { + "lodash": "^4.17.19", + "prop-types": "^15.5.8", + "victory-core": "^35.4.8" + } + }, + "victory-group": { + "version": "35.4.9", + "resolved": "https://registry.npmjs.org/victory-group/-/victory-group-35.4.9.tgz", + "integrity": "sha512-JhJYD/ykPVKFq8ZATTpj8zA1Y8f6pXVoD9o/qBcRMggyfjPglV4rGdg6NnFCTV5bK/YMV5jYiSvZpdJlBtQpPQ==", + "requires": { + "lodash": "^4.17.19", + "prop-types": "^15.5.8", + "react-fast-compare": "^2.0.0", + "victory-core": "^35.4.8", + "victory-shared-events": "^35.4.9" + } + }, + "victory-legend": { + "version": "35.4.8", + "resolved": "https://registry.npmjs.org/victory-legend/-/victory-legend-35.4.8.tgz", + "integrity": "sha512-QI8zZLm8JipzzlAfJjpJm1MHl6FVcXWJOqU2XMl18RCkwDesukIiBO4dU8UAvNRkqxLRmkJzywFXSp3LFEah0Q==", + "requires": { + "lodash": "^4.17.19", + "prop-types": "^15.5.8", + "victory-core": "^35.4.8" + } + }, + "victory-line": { + "version": "35.4.8", + "resolved": "https://registry.npmjs.org/victory-line/-/victory-line-35.4.8.tgz", + "integrity": "sha512-RJ/Wqon7PS07NRZnlku2C8+cJ48ruunizvKtl7HVv15e1hybo/dCg3dD2IizrO6vF/ja8Iv/RZ2YBDe/nWywrg==", + "requires": { + "d3-shape": "^1.2.0", + "lodash": "^4.17.19", + "prop-types": "^15.5.8", + "victory-core": "^35.4.8" + } + }, + "victory-pie": { + "version": "35.4.8", + "resolved": "https://registry.npmjs.org/victory-pie/-/victory-pie-35.4.8.tgz", + "integrity": "sha512-1+FnHdlqYqQzuiA/Psa77dsXcK1sKbXEUjNgnwfEZSUY2HX5v3fQ0sk4AiZhnVVsz6Rp+Wl4We/cca1PHp7i/w==", + "requires": { + "d3-shape": "^1.0.0", + "lodash": "^4.17.19", + "prop-types": "^15.5.8", + "victory-core": "^35.4.8" + } + }, + "victory-polar-axis": { + "version": "35.4.8", + "resolved": "https://registry.npmjs.org/victory-polar-axis/-/victory-polar-axis-35.4.8.tgz", + "integrity": "sha512-rhNGYUj7A70ZoHyta0ma3WD12Kv162Mf0AmFLvfxC6W+4eh2uwgGE8j+CJBW+/HbzLhFoeDY+aTe0FqJPLiO4A==", + "requires": { + "lodash": "^4.17.19", + "prop-types": "^15.5.8", + "victory-core": "^35.4.8" + } + }, + "victory-scatter": { + "version": "35.4.8", + "resolved": "https://registry.npmjs.org/victory-scatter/-/victory-scatter-35.4.8.tgz", + "integrity": "sha512-UWyYgUhvdMFBkzBrgvN5WFCFX1E7tG6EjLNvAhsMoGK2eVH69QzC7Aiun+hLeXUXcssg2Gi1+f/w4rrxpdpZzw==", + "requires": { + "lodash": "^4.17.19", + "prop-types": "^15.5.8", + "victory-core": "^35.4.8" + } + }, + "victory-selection-container": { + "version": "35.4.8", + "resolved": "https://registry.npmjs.org/victory-selection-container/-/victory-selection-container-35.4.8.tgz", + "integrity": "sha512-2I2pEoUwjEltm0hJO+EwTlcrVhfvchph3OlcGp3N/Kw9q5veS/gfvcQMwur0FjS2GNwwCSjW/Gbv8zv31B/xFg==", + "requires": { + "lodash": "^4.17.19", + "prop-types": "^15.5.8", + "victory-core": "^35.4.8" + } + }, + "victory-shared-events": { + "version": "35.4.9", + "resolved": "https://registry.npmjs.org/victory-shared-events/-/victory-shared-events-35.4.9.tgz", + "integrity": "sha512-AW6iYsZn+2kmRNb+RKzAze6z8/u5uQakBpkKsVl/AI43uzlWNEQELIfJOcFfTbM2Qo1vkwJCSz0S9mrbt2meAw==", + "requires": { + "json-stringify-safe": "^5.0.1", + "lodash": "^4.17.19", + "prop-types": "^15.5.8", + "react-fast-compare": "^2.0.0", + "victory-core": "^35.4.8" + } + }, + "victory-stack": { + "version": "35.4.9", + "resolved": "https://registry.npmjs.org/victory-stack/-/victory-stack-35.4.9.tgz", + "integrity": "sha512-fePjKUM5zfp3+5lJPtow/6HAglwcVb1JBDNIsrpChn78G3NvbpTZUlMlNdbSmE1+xDLFEWBGJ9oUI/gjjWynGA==", + "requires": { + "lodash": "^4.17.19", + "prop-types": "^15.5.8", + "react-fast-compare": "^2.0.0", + "victory-core": "^35.4.8", + "victory-shared-events": "^35.4.9" + } + }, + "victory-tooltip": { + "version": "35.4.8", + "resolved": "https://registry.npmjs.org/victory-tooltip/-/victory-tooltip-35.4.8.tgz", + "integrity": "sha512-CZLsLgfxUA6PdaIxUgIk4DJfoo5DRM70OLTZFekctQkvwt2S6Fc7DSv47ZvFw7nL6SEVaNjwsDmTZnabUJb+4Q==", + "requires": { + "lodash": "^4.17.19", + "prop-types": "^15.5.8", + "victory-core": "^35.4.8" + } + }, + "victory-voronoi-container": { + "version": "35.4.8", + "resolved": "https://registry.npmjs.org/victory-voronoi-container/-/victory-voronoi-container-35.4.8.tgz", + "integrity": "sha512-+rQRr2SwdixwxvUSF4NUsPj7yWpkeQcQZWcPz8NNNpaCBxN1HNVQ41W7DmAZ98Spta2gkrk6888Q31zQeiGDXw==", + "requires": { + "delaunay-find": "0.0.5", + "lodash": "^4.17.19", + "prop-types": "^15.5.8", + "react-fast-compare": "^2.0.0", + "victory-core": "^35.4.8", + "victory-tooltip": "^35.4.8" + } + }, + "victory-zoom-container": { + "version": "35.4.8", + "resolved": "https://registry.npmjs.org/victory-zoom-container/-/victory-zoom-container-35.4.8.tgz", + "integrity": "sha512-jLHm0/wttiRIzCEdxK3SL/emNUkfc9Rt64I2Yp+9OuP+YJP+5/MkuavjjnYaVowBD3sbn6ByGBMkJ8e+Q/U7dA==", + "requires": { + "lodash": "^4.17.19", + "prop-types": "^15.5.8", + "victory-core": "^35.4.8" + } + }, "vm-browserify": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/vm-browserify/-/vm-browserify-1.1.2.tgz", diff --git a/src/cockpit/389-console/package.json b/src/cockpit/389-console/package.json index 3301b2eda..857474f2e 100644 --- a/src/cockpit/389-console/package.json +++ b/src/cockpit/389-console/package.json @@ -46,6 +46,7 @@ "@fortawesome/free-solid-svg-icons": "^5.15.2", "@fortawesome/react-fontawesome": "^0.1.14", "@patternfly/patternfly": "^2.71.7", + "@patternfly/react-charts": "^6.13.8", "@patternfly/react-core": "^4.90.2", "@patternfly/react-icons": "^4.8.4", "@restart/hooks": "^0.3.26", diff --git a/src/cockpit/389-console/src/css/ds.css b/src/cockpit/389-console/src/css/ds.css index 8b52baee0..0f124fd03 100644 --- a/src/cockpit/389-console/src/css/ds.css +++ b/src/cockpit/389-console/src/css/ds.css @@ -474,10 +474,6 @@ textarea { margin-left: 40px !important; } -.ds-margin-left-piechart { - margin-left: 140px !important; -} - .ds-margin-right-sm { margin-left: 5px !important; } @@ -698,6 +694,12 @@ h4 { padding-left: 0px !important; } -.pf-c-form__group-label { - text-align: right !important; +.chart-container { + height: 100px; + width: 400px; +} +.chart-label-container { + margin-left: 50px; + margin-top: 50px; + height: 135px; } diff --git a/src/cockpit/389-console/src/lib/monitor/dbMonitor.jsx b/src/cockpit/389-console/src/lib/monitor/dbMonitor.jsx index f874d3efc..8e62645e1 100644 --- a/src/cockpit/389-console/src/lib/monitor/dbMonitor.jsx +++ b/src/cockpit/389-console/src/lib/monitor/dbMonitor.jsx @@ -1,330 +1,465 @@ +import cockpit from "cockpit"; import React from "react"; import PropTypes from "prop-types"; +import { log_cmd } from "../tools.jsx"; import { - DonutChart, - PieChart, - Nav, - NavItem, - TabContent, - TabPane, - TabContainer, - Row, - Col, - ControlLabel, - Form, - Icon, - noop, -} from "patternfly-react"; -import d3 from "d3"; + Card, + CardBody, + Grid, + GridItem, + Spinner, + Tab, + Tabs, + TabTitleText, + noop +} from "@patternfly/react-core"; +import { + Chart, + ChartArea, + ChartAxis, + ChartGroup, + ChartThemeColor, + ChartVoronoiContainer +} from '@patternfly/react-charts'; export class DatabaseMonitor extends React.Component { constructor (props) { super(props); this.state = { - activeKey: 1, - disableTabs: false, + activeTabKey: 0, + data: {}, + loading: true, + // refresh charts + cache_refresh: "", + count: 10, + dbCacheList: [], + ndnCacheList: [], + ndnCacheUtilList: [] + }; + + // Toggle currently active tab + this.handleNavSelect = (event, tabIndex) => { + this.setState({ + activeTabKey: tabIndex + }); }; - this.handleNavSelect = this.handleNavSelect.bind(this); + + this.startCacheRefresh = this.startCacheRefresh.bind(this); + this.refreshCache = this.refreshCache.bind(this); } componentDidMount() { + this.resetChartData(); + this.refreshCache(); + this.startCacheRefresh(); this.props.enableTree(); } - handleNavSelect(key) { - this.setState({ activeKey: key }); + componentWillUnmount() { + this.stopCacheRefresh(); + } + + resetChartData() { + this.setState({ + data: { + dbcachehitratio: [0], + dbcachetries: [0], + dbcachehits: [0], + dbcachepagein: [0], + dbcachepageout: [0], + dbcacheroevict: [0], + dbcacherwevict: [0], + normalizeddncachehitratio: [0], + maxnormalizeddncachesize: [0], + currentnormalizeddncachesize: [0], + normalizeddncachetries: [0], + normalizeddncachehits: [0], + normalizeddncacheevictions: [0], + currentnormalizeddncachecount: [0], + normalizeddncachethreadsize: [0], + normalizeddncachethreadslots: [0], + }, + dbCacheList: [ + {name: "", x: "1", y: 0}, + {name: "", x: "2", y: 0}, + {name: "", x: "3", y: 0}, + {name: "", x: "4", y: 0}, + {name: "", x: "5", y: 0}, + {name: "", x: "6", y: 0}, + {name: "", x: "7", y: 0}, + {name: "", x: "8", y: 0}, + {name: "", x: "9", y: 0}, + {name: "", x: "10", y: 0}, + ], + ndnCacheList: [ + {name: "", x: "1", y: 0}, + {name: "", x: "2", y: 0}, + {name: "", x: "3", y: 0}, + {name: "", x: "4", y: 0}, + {name: "", x: "5", y: 0}, + ], + ndnCacheUtilList: [ + {name: "", x: "1", y: 0}, + {name: "", x: "2", y: 0}, + {name: "", x: "3", y: 0}, + {name: "", x: "4", y: 0}, + {name: "", x: "5", y: 0}, + ], + }); + } + + refreshCache() { + // Search for db cache stat and update state + let cmd = [ + "dsconf", "-j", "ldapi://%2fvar%2frun%2fslapd-" + this.props.serverId + ".socket", + "monitor", "ldbm" + ]; + log_cmd("refreshCache", "Load database monitor", cmd); + cockpit + .spawn(cmd, { superuser: true, err: "message" }) + .done(content => { + let config = JSON.parse(content); + let count = this.state.count + 1; // This is used by all the charts + if (count > 100) { + // Keep progress count in check + count = 1; + } + + // Build up the DB Cache chart data + let dbratio = config.attrs.dbcachehitratio[0]; + let chart_data = this.state.dbCacheList; + chart_data.shift(); + chart_data.push({name: "Cache Hit Ratio", x: count.toString(), y: parseInt(dbratio)}); + + // Build up the NDN Cache chart data + let ndnratio = config.attrs.normalizeddncachehitratio[0]; + let ndn_chart_data = this.state.ndnCacheList; + ndn_chart_data.shift(); + ndn_chart_data.push({name: "Cache Hit Ratio", x: count.toString(), y: parseInt(ndnratio)}); + + // Build up the DB Cache Util chart data + let ndn_util_chart_data = this.state.ndnCacheUtilList; + let currNDNSize = parseInt(config.attrs.currentnormalizeddncachesize[0]); + let maxNDNSize = parseInt(config.attrs.maxnormalizeddncachesize[0]); + let ndn_utilization = (currNDNSize / maxNDNSize) * 100; + ndn_util_chart_data.shift(); + ndn_util_chart_data.push({name: "Cache Utilization", x: count.toString(), y: parseInt(ndn_utilization)}); + + this.setState({ + data: config.attrs, + loading: false, + dbCacheList: chart_data, + ndnCacheList: ndn_chart_data, + ndnCacheUtilList: ndn_util_chart_data, + count: count + }); + }) + .fail(() => { + this.resetChartData(); + }); + } + + startCacheRefresh() { + this.state.cache_refresh = setInterval(this.refreshCache, 2000); + } + + stopCacheRefresh() { + clearInterval(this.state.cache_refresh); } render() { - let badColor = "#d01c8b"; - let warningColor = "#ffc107"; - let goodColor = "#4dac26"; - let emptyColor = "#d3d3d3"; - let donutColorDB = goodColor; - let donutColorNDN = goodColor; - let donutColorNDNUtil = goodColor; - let donutColorNDNMiss = emptyColor; - let donutColorDBMiss = emptyColor; - let dbcachehit = parseInt(this.props.data.dbcachehitratio[0]); - let ndncachehit = parseInt(this.props.data.normalizeddncachehitratio[0]); - let ndncachemax = parseInt(this.props.data.maxnormalizeddncachesize[0]); - let ndncachecurr = parseInt(this.props.data.currentnormalizeddncachesize[0]); - let utilratio = Math.round((ndncachecurr / ndncachemax) * 100); + let chartColor = ChartThemeColor.green; + let ndnChartColor = ChartThemeColor.green; + let ndnUtilColor = ChartThemeColor.green; + let dbcachehit = 0; + let ndncachehit = 0; + let ndncachemax = 0; + let ndncachecurr = 0; + let utilratio = 0; + let content = + <div className="ds-margin-top-xlg ds-center"> + <h4>Loading database monitor information ...</h4> + <Spinner className="ds-margin-top-lg" size="xl" /> + </div>; + + if (!this.state.loading) { + dbcachehit = parseInt(this.state.data.dbcachehitratio[0]); + ndncachehit = parseInt(this.state.data.normalizeddncachehitratio[0]); + ndncachemax = parseInt(this.state.data.maxnormalizeddncachesize[0]); + ndncachecurr = parseInt(this.state.data.currentnormalizeddncachesize[0]); + utilratio = Math.round((ndncachecurr / ndncachemax) * 100); + if (utilratio == 0) { + // Just round up to 1 + utilratio = 1; + } - // Database cache - if (dbcachehit > 89) { - donutColorDB = goodColor; - } else if (dbcachehit > 74) { - donutColorDB = warningColor; - } else { - if (dbcachehit < 50) { - // Pie chart shows higher catagory, so we need to highlight the misses - donutColorDBMiss = badColor; + // Database cache + if (dbcachehit > 89) { + chartColor = ChartThemeColor.green; + } else if (dbcachehit > 74) { + chartColor = ChartThemeColor.orange; } else { - donutColorDB = badColor; + chartColor = ChartThemeColor.purple; } - } - // NDN cache ratio - if (ndncachehit > 89) { - donutColorNDN = goodColor; - } else if (ndncachehit > 74) { - donutColorNDN = warningColor; - } else { - if (ndncachehit < 50) { - // Pie chart shows higher catagory, so we need to highlight the misses - donutColorNDNMiss = badColor; + // NDN cache ratio + if (ndncachehit > 89) { + ndnChartColor = ChartThemeColor.green; + } else if (ndncachehit > 74) { + ndnChartColor = ChartThemeColor.orange; } else { - donutColorNDN = badColor; + ndnChartColor = ChartThemeColor.purple; } - } - // NDN cache utilization - if (ndncachehit < 90) { + // NDN cache utilization if (utilratio > 95) { - donutColorNDNUtil = badColor; + ndnUtilColor = ChartThemeColor.purple; } else if (utilratio > 90) { - donutColorNDNUtil = warningColor; + ndnUtilColor = ChartThemeColor.orange; + } else { + ndnUtilColor = ChartThemeColor.green; } - } - - return ( - <div id="db-content"> - <Row> - <Col sm={12} className="ds-word-wrap"> - <ControlLabel className="ds-suffix-header"> - Database Performance Statistics - <Icon className="ds-left-margin ds-refresh" - type="fa" name="refresh" title="Refresh database monitor" - onClick={this.props.reload} - /> - </ControlLabel> - </Col> - </Row> - <TabContainer className="ds-margin-top-lg" id="basic-tabs-pf" onSelect={this.handleNavSelect} activeKey={this.state.activeKey}> - <div> - <Nav bsClass="nav nav-tabs nav-tabs-pf"> - <NavItem eventKey={1}> - <div dangerouslySetInnerHTML={{__html: 'Database Cache'}} /> - </NavItem> - <NavItem eventKey={2}> - <div dangerouslySetInnerHTML={{__html: 'Normalized DN Cache'}} /> - </NavItem> - </Nav> - <TabContent> - <TabPane eventKey={1}> - <div className="ds-margin-top-lg ds-margin-left-piechart"> - <DonutChart - id="monitor-db-cache-hitratio-chart" - size={{width: 180, height: 120}} - data={{ - columns: [['miss', 100 - dbcachehit], ['hit', dbcachehit]], - colors: { - 'hit': donutColorDB, - 'miss': donutColorDBMiss, - }, - order: null, - }} - title={{type: 'percent'}} - legend={{show: true, position: 'right'}} - /> - <b className="ds-left-margin">DB Cache Hit Ratio</b> - </div> - <hr /> - <Form horizontal> - <Row className="ds-margin-top"> - <Col componentClass={ControlLabel} sm={3}> - Database Cache Hit Ratio - </Col> - <Col sm={3}> - <input type="text" value={this.props.data.dbcachehitratio} size="28" readOnly /> - </Col> - </Row> - <Row className="ds-margin-top"> - <Col componentClass={ControlLabel} sm={3}> - Database Cache Tries - </Col> - <Col sm={3}> - <input type="text" value={this.props.data.dbcachetries} size="28" readOnly /> - </Col> - </Row> - <Row className="ds-margin-top"> - <Col componentClass={ControlLabel} sm={3}> - Database Cache Hits - </Col> - <Col sm={3}> - <input type="text" value={this.props.data.dbcachehits} size="28" readOnly /> - </Col> - </Row> - <Row className="ds-margin-top"> - <Col componentClass={ControlLabel} sm={3}> - Cache Pages Read - </Col> - <Col sm={3}> - <input type="text" value={this.props.data.dbcachepagein} size="28" readOnly /> - </Col> - </Row> - <Row className="ds-margin-top"> - <Col componentClass={ControlLabel} sm={3}> - Cache Pages Written - </Col> - <Col sm={3}> - <input type="text" value={this.props.data.dbcachepageout} size="28" readOnly /> - </Col> - </Row> - <Row className="ds-margin-top"> - <Col componentClass={ControlLabel} sm={3}> - Read-Only Page Evictions - </Col> - <Col sm={3}> - <input type="text" value={this.props.data.dbcacheroevict} size="28" readOnly /> - </Col> - </Row> - <Row className="ds-margin-top"> - <Col componentClass={ControlLabel} sm={3}> - Read-Write Page Evictions - </Col> - <Col sm={3}> - <input type="text" value={this.props.data.dbcacherwevict} size="28" readOnly /> - </Col> - </Row> - </Form> - </TabPane> - - <TabPane eventKey={2}> - <div className="ds-margin-top-lg"> + content = + <Tabs activeKey={this.state.activeTabKey} onSelect={this.handleNavSelect}> + <Tab eventKey={0} title={<TabTitleText><b>Database Cache</b></TabTitleText>}> + <div className="ds-margin-top"> + <Card> + <CardBody> <div className="ds-container"> - <div className="ds-divider" /> - <div className="ds-left-margin"> - <DonutChart - id="monitor-db-cache-ndn-hitratio-chart" - size={{width: 180, height: 120}} - data={{ - columns: [['miss', 100 - ndncachehit], ['hit', ndncachehit]], - colors: { - 'hit': donutColorNDN, - 'miss': donutColorNDNMiss, - }, - order: null, - }} - title={{type: 'percent'}} - legend={{show: true, position: 'right'}} - /> - <b>NDN Cache Hit Ratio</b> + <div className="ds-center"> + <h4 className="ds-margin-top-xlg">Cache Hit Ratio</h4> + <h3><b>{dbcachehit}%</b></h3> </div> - <div className="ds-divider" /> - <div className="ds-divider" /> - <div className="ds-chart-right"> - <PieChart - id="monitor-db-cache-ndn-util-chart" - size={{width: 180, height: 120}} - data={{ - columns: [ - ['Used', utilratio], - ['Unused', 100 - utilratio], - ], - colors: { - 'Used': donutColorNDNUtil, - 'Unused': emptyColor, - }, - order: null, - }} - pie={{ - label: { - format: function (value, ratio, id) { - return d3.format(',%')(value / 100); - } - } + <div className="ds-margin-left" style={{ height: '200px', width: '500px' }}> + <Chart + ariaDesc="Database Cache" + ariaTitle="Live Database Cache Statistics" + containerComponent={<ChartVoronoiContainer labels={({ datum }) => `${datum.name}: ${datum.y}`} constrainToVisibleArea />} + height={200} + maxDomain={{y: 100}} + minDomain={{y: 0}} + padding={{ + bottom: 30, + left: 40, + top: 10, + right: 10, }} - title={{type: 'pie'}} - legend={{show: true, position: 'right'}} - unloadBeforeLoad - /> - <b>NDN Cache Utilization</b> - <div> - (DN's in cache: <b>{this.props.data.currentnormalizeddncachecount}</b>) - </div> + width={500} + themeColor={chartColor} + > + <ChartAxis /> + <ChartAxis dependentAxis showGrid tickValues={[25, 50, 75, 100]} /> + <ChartGroup> + <ChartArea + data={this.state.dbCacheList} + /> + </ChartGroup> + </Chart> </div> </div> - <hr /> - <Form horizontal> - <Row className="ds-margin-top"> - <Col componentClass={ControlLabel} sm={3}> - NDN Cache Hit Ratio - </Col> - <Col sm={3}> - <input type="text" value={this.props.data.normalizeddncachehitratio} size="28" readOnly /> - </Col> - </Row> - <Row className="ds-margin-top"> - <Col componentClass={ControlLabel} sm={3}> - NDN Cache Tries - </Col> - <Col sm={3}> - <input type="text" value={this.props.data.normalizeddncachetries} size="28" readOnly /> - </Col> - </Row> - <Row className="ds-margin-top"> - <Col componentClass={ControlLabel} sm={3}> - NDN Cache Hits - </Col> - <Col sm={3}> - <input type="text" value={this.props.data.normalizeddncachehits} size="28" readOnly /> - </Col> - </Row> - <Row className="ds-margin-top"> - <Col componentClass={ControlLabel} sm={3}> - NDN Cache Evictions - </Col> - <Col sm={3}> - <input type="text" value={this.props.data.normalizeddncacheevictions} size="28" readOnly /> - </Col> - </Row> - <Row className="ds-margin-top"> - <Col componentClass={ControlLabel} sm={3}> - NDN Cache Max Size - </Col> - <Col sm={3}> - <input type="text" value={this.props.data.maxnormalizeddncachesize} size="28" readOnly /> - </Col> - </Row> - <Row className="ds-margin-top"> - <Col componentClass={ControlLabel} sm={3}> - NDN Current Cache Size - </Col> - <Col sm={3}> - <input type="text" value={this.props.data.currentnormalizeddncachesize} size="28" readOnly /> - </Col> - </Row> - <Row className="ds-margin-top"> - <Col componentClass={ControlLabel} sm={3}> - NDN Cache DN Count - </Col> - <Col sm={3}> - <input type="text" value={this.props.data.currentnormalizeddncachecount} size="28" readOnly /> - </Col> - </Row> - <Row className="ds-margin-top"> - <Col componentClass={ControlLabel} sm={3}> - NDN Cache Thread Size - </Col> - <Col sm={3}> - <input type="text" value={this.props.data.normalizeddncachethreadsize} size="28" readOnly /> - </Col> - </Row> - <Row className="ds-margin-top"> - <Col componentClass={ControlLabel} sm={3}> - NDN Cache Thread Slots - </Col> - <Col sm={3}> - <input type="text" value={this.props.data.normalizeddncachethreadslots} size="28" readOnly /> - </Col> - </Row> - </Form> - </div> - </TabPane> - </TabContent> - </div> - </TabContainer> + </CardBody> + </Card> + </div> + + <Grid hasGutter className="ds-margin-top-xlg"> + <GridItem span={3}> + Database Cache Hit Ratio: + </GridItem> + <GridItem span={2}> + <b>{this.state.data.dbcachehitratio}</b> + </GridItem> + <GridItem span={3}> + Database Cache Tries: + </GridItem> + <GridItem span={2}> + <b>{this.state.data.dbcachetries}</b> + </GridItem> + <GridItem span={3}> + Database Cache Hits: + </GridItem> + <GridItem span={2}> + <b>{this.state.data.dbcachehits}</b> + </GridItem> + <GridItem span={3}> + Cache Pages Read: + </GridItem> + <GridItem span={2}> + <b>{this.state.data.dbcachepagein}</b> + </GridItem> + <GridItem span={3}> + Cache Pages Written: + </GridItem> + <GridItem span={2}> + <b>{this.state.data.dbcachepageout}</b> + </GridItem> + <GridItem span={3}> + Read-Only Page Evictions: + </GridItem> + <GridItem span={2}> + <b>{this.state.data.dbcacheroevict}</b> + </GridItem> + <GridItem span={3}> + Read-Write Page Evictions: + </GridItem> + <GridItem span={2}> + <b>{this.state.data.dbcacherwevict}</b> + </GridItem> + </Grid> + </Tab> + + <Tab eventKey={1} title={<TabTitleText><b>Normalized DN Cache</b></TabTitleText>}> + <div className="ds-margin-top-lg"> + <Grid hasGutter> + <GridItem span={6}> + <Card> + <CardBody> + <div className="ds-container"> + <div className="ds-center"> + <h4 className="ds-margin-top-lg">Cache Hit Ratio</h4> + <h3><b>{ndncachehit}%</b></h3> + </div> + <div className="ds-margin-left" style={{ height: '200px', width: '350px' }}> + <Chart + ariaDesc="NDN Cache" + ariaTitle="Live Normalized DN Cache Statistics" + containerComponent={<ChartVoronoiContainer labels={({ datum }) => `${datum.name}: ${datum.y}`} constrainToVisibleArea />} + height={200} + maxDomain={{y: 100}} + minDomain={{y: 0}} + padding={{ + bottom: 40, + left: 60, + top: 10, + right: 15, + }} + width={350} + themeColor={ndnChartColor} + > + <ChartAxis /> + <ChartAxis dependentAxis showGrid tickValues={[25, 50, 75, 100]} /> + <ChartGroup> + <ChartArea + data={this.state.ndnCacheList} + /> + </ChartGroup> + </Chart> + </div> + </div> + </CardBody> + </Card> + </GridItem> + <GridItem span={6}> + <Card> + <CardBody> + <div className="ds-container"> + <div className="ds-center"> + <h4 className="ds-margin-top-lg">Cache Utilization</h4> + <h3><b>{utilratio}%</b></h3> + <h6 className="ds-margin-top-xlg">Cached DN's</h6> + <b>{this.state.data.currentnormalizeddncachecount[0]}</b> + </div> + <div className="ds-margin-left" style={{ height: '200px', width: '350px' }}> + <Chart + ariaDesc="NDN Cache Utilization" + ariaTitle="Live Normalized DN Cache Utilization Statistics" + containerComponent={<ChartVoronoiContainer labels={({ datum }) => `${datum.name}: ${datum.y}`} constrainToVisibleArea />} + height={200} + maxDomain={{y: 100}} + minDomain={{y: 0}} + padding={{ + bottom: 40, + left: 60, + top: 10, + right: 15, + }} + width={350} + themeColor={ndnUtilColor} + > + <ChartAxis /> + <ChartAxis dependentAxis showGrid tickValues={[25, 50, 75, 100]} /> + <ChartGroup> + <ChartArea + data={this.state.ndnCacheUtilList} + /> + </ChartGroup> + </Chart> + </div> + </div> + </CardBody> + </Card> + </GridItem> + </Grid> + + <Grid hasGutter className="ds-margin-top-xlg"> + <GridItem span={3}> + NDN Cache Hit Ratio: + </GridItem> + <GridItem span={2}> + <b>{this.state.data.normalizeddncachehitratio}</b> + </GridItem> + <GridItem span={3}> + NDN Cache Max Size: + </GridItem> + <GridItem span={2}> + <b>{this.state.data.maxnormalizeddncachesize}</b> + </GridItem> + + <GridItem span={3}> + NDN Cache Tries: + </GridItem> + <GridItem span={2}> + <b>{this.state.data.normalizeddncachetries}</b> + </GridItem> + <GridItem span={3}> + NDN Current Cache Size: + </GridItem> + <GridItem span={2}> + <b>{this.state.data.currentnormalizeddncachesize}</b> + </GridItem> + <GridItem span={3}> + NDN Cache Hits: + </GridItem> + <GridItem span={2}> + <b>{this.state.data.normalizeddncachehits}</b> + </GridItem> + <GridItem span={3}> + NDN Cache DN Count: + </GridItem> + <GridItem span={2}> + <b>{this.state.data.currentnormalizeddncachecount}</b> + </GridItem> + <GridItem span={3}> + NDN Cache Evictions: + </GridItem> + <GridItem span={2}> + <b>{this.state.data.normalizeddncacheevictions}</b> + </GridItem> + <GridItem span={3}> + NDN Cache Thread Size: + </GridItem> + <GridItem span={2}> + <b>{this.state.data.normalizeddncachethreadsize}</b> + </GridItem> + <GridItem span={3}> + NDN Cache Thread Slots: + </GridItem> + <GridItem span={2}> + <b>{this.state.data.normalizeddncachethreadslots}</b> + </GridItem> + </Grid> + </div> + </Tab> + </Tabs>; + } + + return ( + <div id="db-content"> + <h3> + Database Performance Statistics + </h3> + <div className="ds-margin-top-xlg"> + {content} + </div> + </div> ); } @@ -333,14 +468,12 @@ export class DatabaseMonitor extends React.Component { // Prop types and defaults DatabaseMonitor.propTypes = { - data: PropTypes.object, - reload: PropTypes.func, + serverId: PropTypes.string, enableTree: PropTypes.func, }; DatabaseMonitor.defaultProps = { - data: {}, - reload: noop, + serverId: "", enableTree: noop, }; diff --git a/src/cockpit/389-console/src/lib/monitor/suffixMonitor.jsx b/src/cockpit/389-console/src/lib/monitor/suffixMonitor.jsx index 6fd20d988..40f3453cc 100644 --- a/src/cockpit/389-console/src/lib/monitor/suffixMonitor.jsx +++ b/src/cockpit/389-console/src/lib/monitor/suffixMonitor.jsx @@ -1,404 +1,575 @@ +import cockpit from "cockpit"; import React from "react"; import PropTypes from "prop-types"; +import { log_cmd } from "../tools.jsx"; import { - DonutChart, - PieChart, - ControlLabel, - Row, - Col, - Form, - Icon, - Nav, - NavItem, - TabContent, - TabPane, - TabContainer, + Card, + CardBody, + Grid, + GridItem, + Spinner, + Tab, + Tabs, + TabTitleText, noop -} from "patternfly-react"; -import d3 from "d3"; +} from "@patternfly/react-core"; +import { + Chart, + ChartArea, + ChartAxis, + ChartGroup, + ChartThemeColor, + ChartVoronoiContainer +} from '@patternfly/react-charts'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; +import { + faLeaf, + faTree, +} from '@fortawesome/free-solid-svg-icons'; export class SuffixMonitor extends React.Component { constructor (props) { super(props); this.state = { - activeKey: 1, + activeTabKey: 0, + data: {}, + loading: true, + // refresh charts + cache_refresh: "", + count: 10, + entryCacheList: [], + entryUtilCacheList: [], + dnCacheList: [], + dnCacheUtilList: [] }; - this.handleNavSelect = this.handleNavSelect.bind(this); + + // Toggle currently active tab + this.handleNavSelect = (event, tabIndex) => { + this.setState({ + activeTabKey: tabIndex + }); + }; + + this.startCacheRefresh = this.startCacheRefresh.bind(this); + this.refreshSuffixCache = this.refreshSuffixCache.bind(this); } componentDidMount() { + this.resetChartData(); + this.refreshSuffixCache(); + this.startCacheRefresh(); this.props.enableTree(); } - handleNavSelect(key) { - this.setState({ activeKey: key }); + componentWillUnmount() { + this.stopCacheRefresh(); } - render() { - let badColor = "#d01c8b"; - let warningColor = "#ffc107"; - let goodColor = "#4dac26"; - let emptyColor = "#d3d3d3"; - let donutColorEC = goodColor; - let donutColorECMiss = emptyColor; - let donutColorECUtil = goodColor; - let donutColorDN = goodColor; - let donutColorDNMiss = emptyColor; - let donutColorDNUtil = goodColor; + resetChartData() { + this.setState({ + data: { + // Entry cache + entrycachehitratio: [0], + entrycachetries: [0], + entrycachehits: [0], + maxentrycachesize: [0], + currententrycachesize: [0], + maxentrycachecount: [0], + currententrycachecount: [0], + // DN cache + dncachehitratio: [0], + dncachetries: [0], + dncachehits: [0], + maxdncachesize: [0], + currentdncachesize: [0], + maxdncachecount: [0], + currentdncachecount: [0], + }, + entryCacheList: [ + {name: "", x: "1", y: 0}, + {name: "", x: "2", y: 0}, + {name: "", x: "3", y: 0}, + {name: "", x: "4", y: 0}, + {name: "", x: "5", y: 0}, + {name: "", x: "6", y: 0}, + {name: "", x: "7", y: 0}, + {name: "", x: "8", y: 0}, + {name: "", x: "9", y: 0}, + {name: "", x: "10", y: 0}, + ], + entryUtilCacheList: [ + {name: "", x: "1", y: 0}, + {name: "", x: "2", y: 0}, + {name: "", x: "3", y: 0}, + {name: "", x: "4", y: 0}, + {name: "", x: "5", y: 0}, + ], + dnCacheList: [ + {name: "", x: "1", y: 0}, + {name: "", x: "2", y: 0}, + {name: "", x: "3", y: 0}, + {name: "", x: "4", y: 0}, + {name: "", x: "5", y: 0}, + {name: "", x: "6", y: 0}, + {name: "", x: "7", y: 0}, + {name: "", x: "8", y: 0}, + {name: "", x: "9", y: 0}, + {name: "", x: "10", y: 0}, + ], + dnCacheUtilList: [ + {name: "", x: "1", y: 0}, + {name: "", x: "2", y: 0}, + {name: "", x: "3", y: 0}, + {name: "", x: "4", y: 0}, + {name: "", x: "5", y: 0}, + ], + }); + } + + refreshSuffixCache() { + // Search for db cache stat and update state + let cmd = [ + "dsconf", "-j", "ldapi://%2fvar%2frun%2fslapd-" + this.props.serverId + ".socket", + "monitor", "backend", this.props.suffix + ]; + log_cmd("refreshSuffixCache", "Load backend monitor", cmd); + cockpit + .spawn(cmd, { superuser: true, err: "message" }) + .done(content => { + let config = JSON.parse(content); + let count = this.state.count + 1; // This is used by all the charts + if (count > 100) { + // Keep progress count in check + count = 1; + } + + // Build up the Entry Cache chart data + let entryRatio = config.attrs.entrycachehitratio[0]; + let entry_data = this.state.entryCacheList; + entry_data.shift(); + entry_data.push({name: "Cache Hit Ratio", x: count.toString(), y: parseInt(entryRatio)}); + + // Build up the Entry Util chart data + let entry_util_data = this.state.entryUtilCacheList; + let maxsize = config.attrs.maxentrycachesize[0]; + let currsize = config.attrs.currententrycachesize[0]; + let utilratio = Math.round((currsize / maxsize) * 100); + if (utilratio == 0) { + utilratio = 1; + } + entry_util_data.shift(); + entry_util_data.push({name: "Cache Utilization", x: count.toString(), y: parseInt(utilratio)}); - // Entry cache - let cachehit = parseInt(this.props.data.entrycachehitratio[0]); - let cachemax = parseInt(this.props.data.maxentrycachesize[0]); - let cachecurr = parseInt(this.props.data.currententrycachesize[0]); - let cachecount = parseInt(this.props.data.currententrycachecount[0]); - let utilratio = Math.round((cachecurr / cachemax) * 100); + // Build up the DN Cache chart data + let dnratio = config.attrs.dncachehitratio[0]; + let dn_data = this.state.dnCacheList; + dn_data.shift(); + dn_data.push({name: "Cache Hit Ratio", x: count.toString(), y: parseInt(dnratio)}); + + // Build up the DN Cache Util chart data + let dn_util_data = this.state.dnCacheUtilList; + currsize = parseInt(config.attrs.currentdncachesize[0]); + maxsize = parseInt(config.attrs.maxdncachesize[0]); + utilratio = (currsize / maxsize) * 100; + if (utilratio == 0) { + utilratio = 1; + } + dn_util_data.shift(); + dn_util_data.push({name: "Cache Utilization", x: count.toString(), y: parseInt(utilratio)}); + + this.setState({ + data: config.attrs, + loading: false, + entryCacheList: entry_data, + entryUtilCacheList: entry_util_data, + dnCacheList: dn_data, + dnCacheUtilList: dn_util_data, + count: count + }); + }) + .fail(() => { + this.resetChartData(); + }); + } + + startCacheRefresh() { + this.state.cache_refresh = setInterval(this.refreshSuffixCache, 2000); + } + + stopCacheRefresh() { + clearInterval(this.state.cache_refresh); + } + + render() { + let entryChartColor = ChartThemeColor.green; + let entryUtilChartColor = ChartThemeColor.green; + let dnChartColor = ChartThemeColor.green; + let dnUtilChartColor = ChartThemeColor.green; + let cachehit = 1; + let cachemax = 0; + let cachecurr = 0; + let cachecount = 0; + let utilratio = 1; // DN cache - let dncachehit = parseInt(this.props.data.dncachehitratio[0]); - let dncachemax = parseInt(this.props.data.maxdncachesize[0]); - let dncachecurr = parseInt(this.props.data.currentdncachesize[0]); - let dncachecount = parseInt(this.props.data.currentdncachecount[0]); - let dnutilratio = Math.round((dncachecurr / dncachemax) * 100); + let dncachehit = 0; + let dncachemax = 0; + let dncachecurr = 0; + let dncachecount = 0; + let dnutilratio = 1; + let suffixIcon = faTree; - // Adjust ratios if needed - if (utilratio == 0) { - utilratio = 1; - } - if (dnutilratio == 0) { - dnutilratio = 1; + if (this.props.dbtype == "subsuffix") { + suffixIcon = faLeaf; } - // Entry Cache - if (cachehit > 89) { - donutColorEC = goodColor; - } else if (cachehit > 74) { - donutColorEC = warningColor; - } else { - if (cachehit < 50) { - // Pie chart shows higher catagory, so we need to highlight the misses - donutColorECMiss = badColor; + let content = + <div className="ds-margin-top-xlg ds-center"> + <h4>Loading suffix monitor information ...</h4> + <Spinner className="ds-margin-top-lg" size="xl" /> + </div>; + + if (!this.state.loading) { + // Entry cache + cachehit = parseInt(this.state.data.entrycachehitratio[0]); + cachemax = parseInt(this.state.data.maxentrycachesize[0]); + cachecurr = parseInt(this.state.data.currententrycachesize[0]); + cachecount = parseInt(this.state.data.currententrycachecount[0]); + utilratio = Math.round((cachecurr / cachemax) * 100); + // DN cache + dncachehit = parseInt(this.state.data.dncachehitratio[0]); + dncachemax = parseInt(this.state.data.maxdncachesize[0]); + dncachecurr = parseInt(this.state.data.currentdncachesize[0]); + dncachecount = parseInt(this.state.data.currentdncachecount[0]); + dnutilratio = Math.round((dncachecurr / dncachemax) * 100); + + // Adjust ratios if needed + if (utilratio == 0) { + utilratio = 1; + } + if (dnutilratio == 0) { + dnutilratio = 1; + } + + // Entry cache chart color + if (cachehit > 89) { + entryChartColor = ChartThemeColor.green; + } else if (cachehit > 74) { + entryChartColor = ChartThemeColor.orange; } else { - donutColorEC = badColor; + entryChartColor = ChartThemeColor.purple; } - } - // Entry cache utilization - if (cachehit < 90) { + // Entry cache utilization if (utilratio > 95) { - donutColorECUtil = badColor; + entryUtilChartColor = ChartThemeColor.purple; } else if (utilratio > 90) { - donutColorECUtil = warningColor; + entryUtilChartColor = ChartThemeColor.orange; + } else { + entryUtilChartColor = ChartThemeColor.green; } - } - // DN cache ratio - if (dncachehit > 89) { - donutColorDN = goodColor; - } else if (dncachehit > 74) { - donutColorDN = warningColor; - } else { - if (dncachehit < 50) { - // Pie chart shows higher catagory, so we need to highlight the misses - donutColorDNMiss = badColor; + // DN cache chart color + if (dncachehit > 89) { + dnChartColor = ChartThemeColor.green; + } else if (dncachehit > 74) { + dnChartColor = ChartThemeColor.orange; } else { - donutColorDN = badColor; + dnChartColor = ChartThemeColor.purple; } - } - // DN cache utilization - if (dncachehit < 90) { + // DN cache utilization if (dnutilratio > 95) { - donutColorDNUtil = badColor; + dnUtilChartColor = ChartThemeColor.purple; } else if (dnutilratio > 90) { - donutColorDNUtil = warningColor; + dnUtilChartColor = ChartThemeColor.orange; + } else { + dnUtilChartColor = ChartThemeColor.green; } - } - let suffixIcon = "tree"; - if (this.props.dbtype == "subsuffix") { - suffixIcon = "leaf"; + content = + <div id="monitor-suffix-page"> + <Tabs activeKey={this.state.activeTabKey} onSelect={this.handleNavSelect}> + <Tab eventKey={0} title={<TabTitleText><b>Entry Cache</b></TabTitleText>}> + <div className="ds-margin-top"> + <Grid hasGutter> + <GridItem span={6}> + <Card> + <CardBody> + <div className="ds-container"> + <div className="ds-center"> + <h4 className="ds-margin-top">Cache Hit Ratio</h4> + <h3><b>{cachehit}%</b></h3> + </div> + <div className="ds-margin-left" style={{ height: '200px', width: '350px' }}> + <Chart + ariaDesc="Entry Cache" + ariaTitle="Live Entry Cache Statistics" + containerComponent={<ChartVoronoiContainer labels={({ datum }) => `${datum.name}: ${datum.y}`} constrainToVisibleArea />} + height={200} + maxDomain={{y: 100}} + minDomain={{y: 0}} + padding={{ + bottom: 40, + left: 60, + top: 10, + right: 15, + }} + width={350} + themeColor={entryChartColor} + > + <ChartAxis /> + <ChartAxis dependentAxis showGrid tickValues={[25, 50, 75, 100]} /> + <ChartGroup> + <ChartArea + data={this.state.entryCacheList} + /> + </ChartGroup> + </Chart> + </div> + </div> + </CardBody> + </Card> + </GridItem> + <GridItem span={6}> + <Card> + <CardBody> + <div className="ds-container"> + <div className="ds-center"> + <h4 className="ds-margin-top">Cache Utilization</h4> + <h3><b>{utilratio}%</b></h3> + <h6 className="ds-margin-top-xlg">Cached Entries</h6> + <b>{cachecount}</b> + </div> + <div className="ds-margin-left" style={{ height: '200px', width: '350px' }}> + <Chart + ariaDesc="Entry Cache Utilization" + ariaTitle="Live Entry Cache Utilization Statistics" + containerComponent={<ChartVoronoiContainer labels={({ datum }) => `${datum.name}: ${datum.y}`} constrainToVisibleArea />} + height={200} + maxDomain={{y: 100}} + minDomain={{y: 0}} + padding={{ + bottom: 40, + left: 60, + top: 10, + right: 15, + }} + width={350} + themeColor={entryUtilChartColor} + > + <ChartAxis /> + <ChartAxis dependentAxis showGrid tickValues={[25, 50, 75, 100]} /> + <ChartGroup> + <ChartArea + data={this.state.entryUtilCacheList} + /> + </ChartGroup> + </Chart> + </div> + </div> + </CardBody> + </Card> + </GridItem> + </Grid> + </div> + <Grid hasGutter className="ds-margin-top-xlg"> + <GridItem span={3}> + Entry Cache Hit Ratio: + </GridItem> + <GridItem span={2}> + <b>{this.state.data.entrycachehitratio}</b> + </GridItem> + <GridItem span={3}> + Entry Cache Tries: + </GridItem> + <GridItem span={2}> + <b>{this.state.data.entrycachetries}</b> + </GridItem> + <GridItem span={3}> + Entry Cache Hits: + </GridItem> + <GridItem span={2}> + <b>{this.state.data.entrycachehits}</b> + </GridItem> + <GridItem span={3}> + Entry Cache Max Size: + </GridItem> + <GridItem span={2}> + <b>{this.state.data.maxentrycachesize}</b> + </GridItem> + <GridItem span={3}> + Entry Cache Current Size: + </GridItem> + <GridItem span={2}> + <b>{this.state.data.currententrycachesize}</b> + </GridItem> + <GridItem span={3}> + Entry Cache Max Entries: + </GridItem> + <GridItem span={2}> + <b>{this.state.data.maxentrycachecount}</b> + </GridItem> + <GridItem span={3}> + Entry Cache Count: + </GridItem> + <GridItem span={2}> + <b>{this.state.data.currententrycachecount}</b> + </GridItem> + </Grid> + </Tab> + <Tab eventKey={1} title={<TabTitleText><b>DN Cache</b></TabTitleText>}> + <div className="ds-margin-top"> + <Grid hasGutter> + <GridItem span={6}> + <Card> + <CardBody> + <div className="ds-container"> + <div className="ds-center"> + <h4 className="ds-margin-top">Cache Hit Ratio</h4> + <h3><b>{dncachehit}%</b></h3> + </div> + <div className="ds-margin-left" style={{ height: '200px', width: '350px' }}> + <Chart + ariaDesc="DN Cache" + ariaTitle="Live DN Cache Statistics" + containerComponent={<ChartVoronoiContainer labels={({ datum }) => `${datum.name}: ${datum.y}`} constrainToVisibleArea />} + height={200} + maxDomain={{y: 100}} + minDomain={{y: 0}} + padding={{ + bottom: 40, + left: 60, + top: 10, + right: 15, + }} + width={350} + themeColor={dnChartColor} + > + <ChartAxis /> + <ChartAxis dependentAxis showGrid tickValues={[25, 50, 75, 100]} /> + <ChartGroup> + <ChartArea + data={this.state.dnCacheList} + /> + </ChartGroup> + </Chart> + </div> + </div> + </CardBody> + </Card> + </GridItem> + <GridItem span={6}> + <Card> + <CardBody> + <div className="ds-container"> + <div className="ds-center"> + <h4 className="ds-margin-top">Cache Utilization</h4> + <h3><b>{dnutilratio}%</b></h3> + <h6 className="ds-margin-top-lg">Cached DN's</h6> + <b>{dncachecount}</b> + </div> + <div className="ds-margin-left" style={{ height: '200px', width: '350px' }}> + <Chart + ariaDesc="DN Cache Utilization" + ariaTitle="Live DN Cache Utilization Statistics" + containerComponent={<ChartVoronoiContainer labels={({ datum }) => `${datum.name}: ${datum.y}`} constrainToVisibleArea />} + height={200} + maxDomain={{y: 100}} + minDomain={{y: 0}} + padding={{ + bottom: 40, + left: 60, + top: 10, + right: 15, + }} + width={350} + themeColor={dnUtilChartColor} + > + <ChartAxis /> + <ChartAxis dependentAxis showGrid tickValues={[25, 50, 75, 100]} /> + <ChartGroup> + <ChartArea + data={this.state.dnCacheUtilList} + /> + </ChartGroup> + </Chart> + </div> + </div> + </CardBody> + </Card> + </GridItem> + </Grid> + </div> + <Grid hasGutter className="ds-margin-top-xlg"> + <GridItem span={3}> + DN Cache Hit Ratio: + </GridItem> + <GridItem span={2}> + <b>{this.state.data.dncachehitratio}</b> + </GridItem> + <GridItem span={3}> + DN Cache Tries: + </GridItem> + <GridItem span={2}> + <b>{this.state.data.dncachetries}</b> + </GridItem> + <GridItem span={3}> + DN Cache Hits: + </GridItem> + <GridItem span={2}> + <b>{this.state.data.dncachehits}</b> + </GridItem> + <GridItem span={3}> + DN Cache Max Size: + </GridItem> + <GridItem span={2}> + <b>{this.state.data.maxdncachesize}</b> + </GridItem> + <GridItem span={3}> + DN Cache Current Size: + </GridItem> + <GridItem span={2}> + <b>{this.state.data.currentdncachesize}</b> + </GridItem> + <GridItem span={3}> + DN Cache Max Count: + </GridItem> + <GridItem span={2}> + <b>{this.state.data.maxdncachecount}</b> + </GridItem> + <GridItem span={3}> + DN Cache Current Count: + </GridItem> + <GridItem span={2}> + <b>{this.state.data.currentdncachecount}</b> + </GridItem> + </Grid> + </Tab> + </Tabs> + </div>; } return ( - <div id="monitor-suffix-page"> - <Row> - <Col sm={12} className="ds-word-wrap"> - <ControlLabel className="ds-suffix-header"> - <Icon type="fa" name={suffixIcon} /> {this.props.suffix} (<i>{this.props.bename}</i>) - <Icon className="ds-left-margin ds-refresh" - type="fa" name="refresh" title="Refresh suffix monitor" - onClick={() => this.props.reload(this.props.suffix)} - /> - </ControlLabel> - </Col> - </Row> - <TabContainer className="ds-margin-top-lg" id="basic-tabs-pf" onSelect={this.handleNavSelect} activeKey={this.state.activeKey}> - <div> - <Nav bsClass="nav nav-tabs nav-tabs-pf"> - <NavItem eventKey={1}> - <div dangerouslySetInnerHTML={{__html: 'Entry Cache'}} /> - </NavItem> - <NavItem eventKey={2}> - <div dangerouslySetInnerHTML={{__html: 'DN Cache'}} /> - </NavItem> - </Nav> - <TabContent> - - <TabPane eventKey={1}> - <div className="ds-margin-top-lg"> - <div className="ds-container"> - <div className="ds-divider" /> - <div className="ds-left-margin" title="The entry cache hit ratio. If the chart is RED then the hit ratio is below 90% and might require further cache tuning"> - <DonutChart - id="monitor-entry-cache-pie" - size={{width: 180, height: 120}} - data={{ - columns: [['miss', 100 - cachehit], ['hit', cachehit]], - colors: { - 'hit': donutColorEC, - 'miss': donutColorECMiss, - }, - order: null, - unload: true - }} - title={{type: 'percent'}} - legend={{show: true, position: 'right'}} - /> - <b>Entry Cache Hit Ratio</b> - </div> - <div className="ds-divider" /> - <div className="ds-divider" /> - <div className="ds-chart-right" title="How much of the allocated cache space is used (max size vs current size). If the chart is RED then you should to increase the max cache size because the cache hit ratio is below 90%"> - <PieChart - id="monitor-entry-util-pie" - size={{width: 180, height: 120}} - data={{ - columns: [ - ['Used', utilratio], - ['Unused', 100 - utilratio], - ], - colors: { - 'Used': donutColorECUtil, - 'Unused': emptyColor, - }, - order: null, - type: 'pie' - }} - pie={{ - label: { - format: function (value, ratio, id) { - return d3.format(',%')(value / 100); - } - } - }} - title={{type: 'pie'}} - legend={{show: true, position: 'right'}} - unloadBeforeLoad - /> - <b>Entry Cache Utilization</b> - <div> - (Entries in cache: <b>{cachecount}</b>) - </div> - </div> - </div> - <hr /> - <Form horizontal> - <Row className="ds-margin-top"> - <Col componentClass={ControlLabel} sm={3}> - Entry Cache Hit Ratio - </Col> - <Col sm={3}> - <input type="text" value={this.props.data.entrycachehitratio} size="35" readOnly /> - </Col> - </Row> - <Row className="ds-margin-top"> - <Col componentClass={ControlLabel} sm={3}> - Entry Cache Tries - </Col> - <Col sm={3}> - <input type="text" value={this.props.data.entrycachetries} size="35" readOnly /> - </Col> - </Row> - <Row className="ds-margin-top"> - <Col componentClass={ControlLabel} sm={3}> - Entry Cache Hits - </Col> - <Col sm={3}> - <input type="text" value={this.props.data.entrycachehits} size="35" readOnly /> - </Col> - </Row> - <Row className="ds-margin-top"> - <Col componentClass={ControlLabel} sm={3}> - Entry Cache Max Size - </Col> - <Col sm={3}> - <input type="text" value={this.props.data.maxentrycachesize} size="35" readOnly /> - </Col> - </Row> - <Row className="ds-margin-top"> - <Col componentClass={ControlLabel} sm={3}> - Entry Cache Current Size - </Col> - <Col sm={3}> - <input type="text" value={this.props.data.currententrycachesize} size="35" readOnly /> - </Col> - </Row> - <Row className="ds-margin-top"> - <Col componentClass={ControlLabel} sm={3}> - Entry Cache Max Entries - </Col> - <Col sm={3}> - <input type="text" value={this.props.data.maxentrycachecount} size="35" readOnly /> - </Col> - </Row> - <Row className="ds-margin-top"> - <Col componentClass={ControlLabel} sm={3}> - Entry Cache Count - </Col> - <Col sm={3}> - <input type="text" value={this.props.data.currententrycachecount} size="35" readOnly /> - </Col> - </Row> - </Form> - </div> - </TabPane> - - <TabPane eventKey={2}> - <div className="ds-margin-top-lg"> - <div className="ds-container"> - <div className="ds-divider" /> - <div className="ds-left-margin" title="The DN cache hit ratio. If the chart is RED then the hit ratio is below 90% and might require further cache tuning"> - <DonutChart - id="monitor-entry-cache-pie" - size={{width: 180, height: 120}} - data={{ - columns: [['miss', 100 - dncachehit], ['hit', dncachehit]], - colors: { - 'hit': donutColorDN, - 'miss': donutColorDNMiss, - }, - order: null, - }} - title={{type: 'percent'}} - legend={{show: true, position: 'right'}} - /> - <b className="ds-left-margin">DN Cache Hit Ratio</b> - </div> - <div className="ds-divider" /> - <div className="ds-divider" /> - <div className="ds-chart-right" title="How much of the allocated cache space is used (max size vs current size). If the chart is RED then you should to increase the max cache size because the cache hit ratio is below 90%"> - <PieChart - id="monitor-entry-util-pie" - size={{width: 180, height: 120}} - data={{ - columns: [ - ['Used', dnutilratio], - ['Unused', 100 - dnutilratio], - ], - colors: { - 'Used': donutColorDNUtil, - 'Unused': emptyColor, - }, - order: null, - type: 'pie' - }} - pie={{ - label: { - format: function (value, ratio, id) { - return d3.format(',%')(value / 100); - } - } - }} - title={{type: 'pie'}} - legend={{show: true, position: 'right'}} - unloadBeforeLoad - /> - <div className="ds-left-margin"> - <b>DN Cache Utilization</b> - <div> - (DN's in cache: <b>{dncachecount}</b>) - </div> - </div> - </div> - </div> - <hr /> - <Form horizontal> - <Row className="ds-margin-top"> - <Col componentClass={ControlLabel} sm={3}> - DN Cache Hit Ratio - </Col> - <Col sm={3}> - <input type="text" value={this.props.data.dncachehitratio} size="35" readOnly /> - </Col> - </Row> - <Row className="ds-margin-top"> - <Col componentClass={ControlLabel} sm={3}> - DN Cache Tries - </Col> - <Col sm={3}> - <input type="text" value={this.props.data.dncachetries} size="35" readOnly /> - </Col> - </Row> - <Row className="ds-margin-top"> - <Col componentClass={ControlLabel} sm={3}> - DN Cache Hits - </Col> - <Col sm={3}> - <input type="text" value={this.props.data.dncachehits} size="35" readOnly /> - </Col> - </Row> - <Row className="ds-margin-top"> - <Col componentClass={ControlLabel} sm={3}> - DN Cache Max Size - </Col> - <Col sm={3}> - <input type="text" value={this.props.data.maxdncachesize} size="35" readOnly /> - </Col> - </Row> - <Row className="ds-margin-top"> - <Col componentClass={ControlLabel} sm={3}> - DN Cache Current Size - </Col> - <Col sm={3}> - <input type="text" value={this.props.data.currentdncachesize} size="35" readOnly /> - </Col> - </Row> - <Row className="ds-margin-top"> - <Col componentClass={ControlLabel} sm={3}> - DN Cache Max Count - </Col> - <Col sm={3}> - <input type="text" value={this.props.data.maxdncachecount} size="35" readOnly /> - </Col> - </Row> - <Row className="ds-margin-top"> - <Col componentClass={ControlLabel} sm={3}> - DN Cache Current Count - </Col> - <Col sm={3}> - <input type="text" value={this.props.data.currentdncachecount} size="35" readOnly /> - </Col> - </Row> - </Form> - </div> - </TabPane> - </TabContent> - </div> - </TabContainer> + <div> + <h3> + <FontAwesomeIcon size="sm" icon={suffixIcon} /> {this.props.suffix} (<i>{this.props.bename}</i>) + </h3> + <div className="ds-margin-top-xlg"> + {content} + </div> </div> ); } } SuffixMonitor.propTypes = { + serverId: PropTypes.string, suffix: PropTypes.string, - data: PropTypes.object, bename: PropTypes.string, - reload: PropTypes.func, enableTree: PropTypes.func, }; SuffixMonitor.defaultProps = { + serverId: "", suffix: "", - data: {}, bename: "", - reload: noop, enableTree: noop, }; diff --git a/src/cockpit/389-console/src/lib/tools.jsx b/src/cockpit/389-console/src/lib/tools.jsx index 1a41058f2..6d9b88709 100644 --- a/src/cockpit/389-console/src/lib/tools.jsx +++ b/src/cockpit/389-console/src/lib/tools.jsx @@ -75,7 +75,7 @@ export function get_date_string(timestamp) { parseInt(minute), parseInt(sec) ); - return date.toLocaleString(); + return date.toLocaleString('en-ZA'); } // Take two directory server tiemstamps and get the elapsed time diff --git a/src/cockpit/389-console/src/monitor.jsx b/src/cockpit/389-console/src/monitor.jsx index 47953361f..3f5fa2c62 100644 --- a/src/cockpit/389-console/src/monitor.jsx +++ b/src/cockpit/389-console/src/monitor.jsx @@ -86,10 +86,8 @@ export class Monitor extends React.Component { this.enableTree = this.enableTree.bind(this); this.update_tree_nodes = this.update_tree_nodes.bind(this); this.onTreeClick = this.onTreeClick.bind(this); - this.loadMonitorSuffix = this.loadMonitorSuffix.bind(this); this.disableSuffixLoading = this.disableSuffixLoading.bind(this); this.loadMonitorLDBM = this.loadMonitorLDBM.bind(this); - this.reloadLDBM = this.reloadLDBM.bind(this); this.loadMonitorSNMP = this.loadMonitorSNMP.bind(this); this.reloadSNMP = this.reloadSNMP.bind(this); this.loadMonitorServer = this.loadMonitorServer.bind(this); @@ -324,9 +322,6 @@ export class Monitor extends React.Component { if (treeViewItem.type == "dblink") { // Chaining this.loadMonitorChaining(treeViewItem.id); - } else { - // Suffix - this.loadMonitorSuffix(treeViewItem.id); } this.setState(prevState => { return { @@ -427,26 +422,6 @@ export class Monitor extends React.Component { }, this.loadMonitorServer()); } - reloadLDBM() { - this.setState({ - ldbmLoading: true - }); - let cmd = [ - "dsconf", "-j", "ldapi://%2fvar%2frun%2fslapd-" + this.props.serverId + ".socket", - "monitor", "ldbm" - ]; - log_cmd("reloadLDBM", "Load database monitor", cmd); - cockpit - .spawn(cmd, { superuser: true, err: "message" }) - .done(content => { - let config = JSON.parse(content); - this.setState({ - ldbmLoading: false, - ldbmData: config.attrs - }); - }); - } - loadMonitorServer() { let cmd = [ "dsconf", "-j", "ldapi://%2fvar%2frun%2fslapd-" + this.props.serverId + ".socket", @@ -593,35 +568,6 @@ export class Monitor extends React.Component { }); } - loadMonitorSuffix(suffix) { - this.setState({ - suffixLoading: true - }); - - let cmd = [ - "dsconf", "-j", "ldapi://%2fvar%2frun%2fslapd-" + this.props.serverId + ".socket", - "monitor", "backend", suffix - ]; - log_cmd("loadMonitorSuffix", "Load suffix monitor", cmd); - cockpit - .spawn(cmd, { superuser: true, err: "message" }) - .done(content => { - let config = JSON.parse(content); - this.setState({ - [suffix]: { - ...this.state[suffix], - suffixData: config.attrs, - }, - }, this.disableSuffixLoading); - }) - .fail(() => { - // Notification of failure (could only be server down) - this.setState({ - suffixLoading: false, - }); - }); - } - loadCleanTasks() { let cmd = ["dsconf", "-j", "ldapi://%2fvar%2frun%2fslapd-" + this.props.serverId + ".socket", "repl-tasks", "list-cleanruv-tasks", "--suffix=" + this.state.replSuffix]; @@ -850,8 +796,8 @@ export class Monitor extends React.Component { monitor_element = <DatabaseMonitor data={this.state.ldbmData} - reload={this.reloadLDBM} enableTree={this.enableTree} + serverId={this.props.serverId} />; } } else if (this.state.node_name == "server-monitor") { @@ -960,13 +906,7 @@ export class Monitor extends React.Component { } } else if (this.state.node_name != "") { // suffixes (example) - if (this.state.suffixLoading) { - monitor_element = - <div className="ds-margin-top-xlg ds-center"> - <h4>Loading suffix monitor information for <b>{this.state.node_text} ...</b></h4> - <Spinner className="ds-margin-top-lg" size="xl" /> - </div>; - } else if (this.state.chainingLoading) { + if (this.state.chainingLoading) { monitor_element = <div className="ds-margin-top-xlg ds-center"> <h4>Loading chaining monitor information for <b>{this.state.node_text} ...</b></h4> @@ -987,10 +927,9 @@ export class Monitor extends React.Component { // Suffix monitor_element = <SuffixMonitor + serverId={this.props.serverId} suffix={this.state.node_text} bename={this.state.bename} - reload={this.loadMonitorSuffix} - data={this.state[this.state.node_text].suffixData} enableTree={this.enableTree} key={this.state.node_text} />;
0
9709dba63345affe26583b6856c7b81336b187d4
389ds/389-ds-base
Issue 5859 - dbscan fails with AttributeError: 'list' object has no attribute 'extends' Bug Description: There is a typo in dbscan: ``` > cmd.extends(['-f', indexfile]) E AttributeError: 'list' object has no attribute 'extends' src/lib389/lib389/__init__.py:3057: AttributeError ``` Fix Description: Fix the typo and fix the test dirsrvtests/tests/suites/password/regression_test.py::test_unhashed_pw_switch Fixes: https://github.com/389ds/389-ds-base/issues/5859 Reviewed-by: @progier389 (Thanks!)
commit 9709dba63345affe26583b6856c7b81336b187d4 Author: Viktor Ashirov <[email protected]> Date: Tue Jul 25 11:37:23 2023 +0200 Issue 5859 - dbscan fails with AttributeError: 'list' object has no attribute 'extends' Bug Description: There is a typo in dbscan: ``` > cmd.extends(['-f', indexfile]) E AttributeError: 'list' object has no attribute 'extends' src/lib389/lib389/__init__.py:3057: AttributeError ``` Fix Description: Fix the typo and fix the test dirsrvtests/tests/suites/password/regression_test.py::test_unhashed_pw_switch Fixes: https://github.com/389ds/389-ds-base/issues/5859 Reviewed-by: @progier389 (Thanks!) diff --git a/dirsrvtests/tests/suites/password/regression_test.py b/dirsrvtests/tests/suites/password/regression_test.py index 24c24fbc5..357c0a921 100644 --- a/dirsrvtests/tests/suites/password/regression_test.py +++ b/dirsrvtests/tests/suites/password/regression_test.py @@ -13,7 +13,7 @@ from lib389._constants import SUFFIX, PASSWORD, DN_DM, DN_CONFIG, PLUGIN_RETRO_C from lib389 import Entry from lib389.topologies import topology_m1 as topo_supplier from lib389.idm.user import UserAccounts -from lib389.utils import ldap, os, logging, ensure_bytes, ds_is_newer, ds_supports_new_changelog +from lib389.utils import ldap, os, logging, ds_is_newer, ds_supports_new_changelog from lib389.topologies import topology_st as topo from lib389.idm.organizationalunit import OrganizationalUnits @@ -52,12 +52,12 @@ def _check_unhashed_userpw(inst, user_dn, is_present=False): log.info('Changelog dbfile file exist: {}'.format(changelog_dbfile)) dbscanOut = inst.dbscan(DEFAULT_CHANGELOG_DB, changelog_dbfile) - for entry in dbscanOut.split(b'dbid: '): - if ensure_bytes('operation: modify') in entry and ensure_bytes(user_dn) in entry and ensure_bytes('userPassword') in entry: + for entry in dbscanOut.split('dbid: '): + if 'operation: modify' in entry and user_dn in entry and 'userPassword' in entry: if is_present: - assert ensure_bytes(unhashed_pwd_attribute) in entry + assert unhashed_pwd_attribute in entry else: - assert ensure_bytes(unhashed_pwd_attribute) not in entry + assert unhashed_pwd_attribute not in entry @pytest.fixture(scope="module") def passw_policy(topo, request): @@ -217,8 +217,6 @@ def test_global_vs_local(topo, passw_policy, create_user, user_pasw): # reset password create_user.set('userPassword', PASSWORD) -#unstable or unstatus tests, skipped for now [email protected](max_runs=2, min_passes=1) @pytest.mark.ds49789 def test_unhashed_pw_switch(topo_supplier): """Check that nsslapd-unhashed-pw-switch works corrently @@ -290,6 +288,7 @@ def test_unhashed_pw_switch(topo_supplier): _check_unhashed_userpw(inst, user, is_present=False) else: _check_unhashed_userpw(inst, user, is_present=True) + inst.start() # Check with nolog that unhashed#user#password is not logged inst.modify_s(DN_CONFIG, @@ -303,6 +302,7 @@ def test_unhashed_pw_switch(topo_supplier): PASSWORD.encode())]) inst.stop() _check_unhashed_userpw(inst, user, is_present=False) + inst.start() # Check with value 'on' that unhashed#user#password is logged inst.modify_s(DN_CONFIG, diff --git a/src/lib389/lib389/__init__.py b/src/lib389/lib389/__init__.py index 9e67ac9a7..ce9f05507 100644 --- a/src/lib389/lib389/__init__.py +++ b/src/lib389/lib389/__init__.py @@ -3054,7 +3054,7 @@ class DirSrv(SimpleLDAPObject, object): # (we should also accept a version number for .db suffix) for f in glob.glob(f'{indexfile}*'): indexfile = f - cmd.extends(['-f', indexfile]) + cmd.extend(['-f', indexfile]) if 'id2entry' in index: if key and key.isdigit(): cmd.extend(['-K', key])
0
7b1144eadcf2dd66fba43ce6dc884940bc2771e8
389ds/389-ds-base
Issue 50711 - `dsconf security` lacks option for setting nsTLSAllowClientRenegotiation attribute Bug Description: dsconf security is not able to handle nsTLSAllowClientRenegotiation attribute. Fix Description: Add the respective option for dsconf. Relates https://pagure.io/389-ds-base/issue/50711 Author: Matus Honek <[email protected]> Review by: spichugin, mreynolds (thanks!)
commit 7b1144eadcf2dd66fba43ce6dc884940bc2771e8 Author: Matus Honek <[email protected]> Date: Tue Nov 12 18:26:29 2019 +0100 Issue 50711 - `dsconf security` lacks option for setting nsTLSAllowClientRenegotiation attribute Bug Description: dsconf security is not able to handle nsTLSAllowClientRenegotiation attribute. Fix Description: Add the respective option for dsconf. Relates https://pagure.io/389-ds-base/issue/50711 Author: Matus Honek <[email protected]> Review by: spichugin, mreynolds (thanks!) diff --git a/src/lib389/lib389/cli_conf/security.py b/src/lib389/lib389/cli_conf/security.py index 027381706..1d60a2f91 100644 --- a/src/lib389/lib389/cli_conf/security.py +++ b/src/lib389/lib389/cli_conf/security.py @@ -30,6 +30,9 @@ SECURITY_ATTRS_MAP = OrderedDict([ ('tls-client-auth', Props(Encryption, 'nsSSLClientAuth', 'Client authentication requirement', ('off', 'allowed', 'required'))), + ('tls-client-renegotiation', Props(Encryption, 'nsTLSAllowClientRenegotiation', + 'Allow client TLS renegotiation', + onoff)), ('require-secure-authentication', Props(Config, 'nsslapd-require-secure-binds', 'Require binds over LDAPS, StartTLS, or SASL', onoff)),
0
4b2f9ecd8b72668fb948507e0456a1d3471ae90b
389ds/389-ds-base
Issue 2375 - CLI - Healthcheck - revise and add new checks Description: Add check for - unauthorized binds are allowed - Access log buffering is disabled - Security log buffering is disabled - Make mapping tree check more robust for case relates: https://github.com/389ds/389-ds-base/issues/2375 Reviewed by: spichugi(Thanks!)
commit 4b2f9ecd8b72668fb948507e0456a1d3471ae90b Author: Mark Reynolds <[email protected]> Date: Thu Jun 22 16:33:55 2023 -0400 Issue 2375 - CLI - Healthcheck - revise and add new checks Description: Add check for - unauthorized binds are allowed - Access log buffering is disabled - Security log buffering is disabled - Make mapping tree check more robust for case relates: https://github.com/389ds/389-ds-base/issues/2375 Reviewed by: spichugi(Thanks!) diff --git a/dirsrvtests/tests/suites/healthcheck/health_config_test.py b/dirsrvtests/tests/suites/healthcheck/health_config_test.py index d51025236..dec3a6c4c 100644 --- a/dirsrvtests/tests/suites/healthcheck/health_config_test.py +++ b/dirsrvtests/tests/suites/healthcheck/health_config_test.py @@ -1,5 +1,5 @@ # --- BEGIN COPYRIGHT BLOCK --- -# Copyright (C) 2022 Red Hat, Inc. +# Copyright (C) 2023 Red Hat, Inc. # All rights reserved. # # License: GPL (version 3 or any later version). @@ -11,7 +11,7 @@ import pytest import os import subprocess -from lib389.backend import Backends +from lib389.backend import Backends, DatabaseConfig from lib389.cos import CosTemplates, CosPointerDefinitions from lib389.dbgen import dbgen_users from lib389.idm.account import Accounts @@ -112,6 +112,7 @@ def test_healthcheck_logging_format_should_be_revised(topology_st): log.info('Set nsslapd-logging-hr-timestamps-enabled to off') standalone.config.set('nsslapd-logging-hr-timestamps-enabled', 'off') + standalone.config.set("nsslapd-accesslog-logbuffering", "on") run_healthcheck_and_flush_log(topology_st, standalone, json=False, searched_code=RET_CODE) run_healthcheck_and_flush_log(topology_st, standalone, json=True, searched_code=RET_CODE) @@ -359,6 +360,7 @@ def test_healthcheck_low_disk_space(topology_st): RET_CODE = 'DSDSLE0001' standalone = topology_st.standalone + standalone.config.set("nsslapd-accesslog-logbuffering", "on") file = '{}/foo'.format(standalone.ds_paths.log_dir) log.info('Count the disk space to allocate') @@ -406,10 +408,13 @@ def test_healthcheck_notes_unindexed_search(topology_st, setup_ldif): standalone = topology_st.standalone log.info('Delete the previous access logs') - topology_st.standalone.deleteAccessLogs() + standalone.deleteAccessLogs() log.info('Set nsslapd-accesslog-logbuffering to off') standalone.config.set("nsslapd-accesslog-logbuffering", "off") + db_cfg = DatabaseConfig(standalone) + db_cfg.set([('nsslapd-idlistscanlimit', '100')]) + log.info('Stopping the server and running offline import...') standalone.stop() @@ -424,6 +429,8 @@ def test_healthcheck_notes_unindexed_search(topology_st, setup_ldif): log.info('Check that access log contains "notes=A"') assert standalone.ds_access_log.match(r'.*notes=A.*') + standalone.config.set("nsslapd-accesslog-logbuffering", "on") + run_healthcheck_and_flush_log(topology_st, standalone, RET_CODE, json=False) run_healthcheck_and_flush_log(topology_st, standalone, RET_CODE, json=True) @@ -459,6 +466,8 @@ def test_healthcheck_notes_unknown_attribute(topology_st, setup_ldif): log.info('Set nsslapd-accesslog-logbuffering to off') standalone.config.set("nsslapd-accesslog-logbuffering", "off") + db_cfg = DatabaseConfig(standalone) + db_cfg.set([('nsslapd-idlistscanlimit', '100')]) log.info('Stopping the server and running offline import...') standalone.stop() @@ -473,9 +482,106 @@ def test_healthcheck_notes_unknown_attribute(topology_st, setup_ldif): log.info('Check that access log contains "notes=F"') assert standalone.ds_access_log.match(r'.*notes=F.*') + standalone.config.set("nsslapd-accesslog-logbuffering", "on") run_healthcheck_and_flush_log(topology_st, standalone, RET_CODE, json=False) run_healthcheck_and_flush_log(topology_st, standalone, RET_CODE, json=True) +def test_healthcheck_unauth_binds(topology_st): + """Check if HealthCheck returns DSCLE0003 code when unauthorized binds are + allowed + + :id: 13b88a3b-0dc5-4ce9-9fbf-058ad072339b + :setup: Standalone instance + :steps: + 1. Create DS instance + 2. Set nsslapd-allow-unauthenticated-binds to on + 3. Use HealthCheck without --json option + 4. Use HealthCheck with --json option + :expectedresults: + 1. Success + 2. Success + 3. Healthcheck reports DSCLE0003 + 4. Healthcheck reports DSCLE0003 + """ + + RET_CODE = 'DSCLE0003' + + inst = topology_st.standalone + + log.info('nsslapd-allow-unauthenticated-binds to on') + inst.config.set("nsslapd-allow-unauthenticated-binds", "on") + + run_healthcheck_and_flush_log(topology_st, inst, RET_CODE, json=False) + run_healthcheck_and_flush_log(topology_st, inst, RET_CODE, json=True) + + # reset setting + log.info('Reset nsslapd-allow-unauthenticated-binds to off') + inst.config.set("nsslapd-allow-unauthenticated-binds", "off") + +def test_healthcheck_accesslog_buffering(topology_st): + """Check if HealthCheck returns DSCLE0004 code when acccess log biffering + is disabled + + :id: 5a6512fd-1c7b-4557-9278-45150423148b + :setup: Standalone instance + :steps: + 1. Create DS instance + 2. Set nsslapd-accesslog-logbuffering to off + 3. Use HealthCheck without --json option + 4. Use HealthCheck with --json option + :expectedresults: + 1. Success + 2. Success + 3. Healthcheck reports DSCLE0004 + 4. Healthcheck reports DSCLE0004 + """ + + RET_CODE = 'DSCLE0004' + + inst = topology_st.standalone + + log.info('nsslapd-accesslog-logbuffering to off') + inst.config.set("nsslapd-accesslog-logbuffering", "off") + + run_healthcheck_and_flush_log(topology_st, inst, RET_CODE, json=False) + run_healthcheck_and_flush_log(topology_st, inst, RET_CODE, json=True) + + # reset setting + log.info('Reset nsslapd-accesslog-logbuffering to on') + inst.config.set("nsslapd-accesslog-logbuffering", "on") + +def test_healthcheck_securitylog_buffering(topology_st): + """Check if HealthCheck returns DSCLE0005 code when security log biffering + is disabled + + :id: 9b84287a-e022-4bdc-8c65-2276b37371b5 + :setup: Standalone instance + :steps: + 1. Create DS instance + 2. Set nsslapd-securitylog-logbuffering to off + 3. Use HealthCheck without --json option + 4. Use HealthCheck with --json option + :expectedresults: + 1. Success + 2. Success + 3. Healthcheck reports DSCLE0005 + 4. Healthcheck reports DSCLE0005 + """ + + RET_CODE = 'DSCLE0005' + + inst = topology_st.standalone + + log.info('nsslapd-securitylog-logbuffering to off') + inst.config.set("nsslapd-securitylog-logbuffering", "off") + + run_healthcheck_and_flush_log(topology_st, inst, RET_CODE, json=False) + run_healthcheck_and_flush_log(topology_st, inst, RET_CODE, json=True) + + # reset setting + log.info('Reset nnsslapd-securitylog-logbuffering to on') + inst.config.set("nsslapd-securitylog-logbuffering", "on") + if __name__ == '__main__': # Run isolated diff --git a/dirsrvtests/tests/suites/healthcheck/healthcheck_test.py b/dirsrvtests/tests/suites/healthcheck/healthcheck_test.py index 7cbbe5f0d..7f6ccada2 100644 --- a/dirsrvtests/tests/suites/healthcheck/healthcheck_test.py +++ b/dirsrvtests/tests/suites/healthcheck/healthcheck_test.py @@ -1,5 +1,5 @@ # --- BEGIN COPYRIGHT BLOCK --- -# Copyright (C) 2020 Red Hat, Inc. +# Copyright (C) 2023 Red Hat, Inc. # All rights reserved. # # License: GPL (version 3 or any later version). @@ -87,6 +87,7 @@ def test_healthcheck_disabled_suffix(topology_st): mts = MappingTrees(topology_st.standalone) mt = mts.get(DEFAULT_SUFFIX) mt.replace("nsslapd-state", "disabled") + topology_st.standalone.config.set("nsslapd-accesslog-logbuffering", "on") run_healthcheck_and_flush_log(topology_st, topology_st.standalone, RET_CODE, json=False) run_healthcheck_and_flush_log(topology_st, topology_st.standalone, RET_CODE, json=True) @@ -184,6 +185,9 @@ def test_healthcheck_list_errors(topology_st): 'DSCERTLE0002 :: Certificate expired', 'DSCLE0001 :: Different log timestamp format', 'DSCLE0002 :: Weak passwordStorageScheme', + 'DSCLE0003 :: Unauthorized Binds Allowed', + 'DSCLE0004 :: Access Log buffering disabled', + 'DSCLE0005 :: Security Log buffering disabled', 'DSCLLE0001 :: Changelog trimming not configured', 'DSDSLE0001 :: Low disk space', 'DSELE0001 :: Weak TLS protocol version', @@ -228,6 +232,9 @@ def test_healthcheck_check_option(topology_st): output_list = ['config:hr_timestamp', 'config:passwordscheme', + # 'config:accesslog_buffering', Skip test access log buffering is disabled + 'config:securitylog_buffering', + 'config:unauth_binds', 'backends:userroot:cl_trimming', 'backends:userroot:mappingtree', 'backends:userroot:search', @@ -236,9 +243,11 @@ def test_healthcheck_check_option(topology_st): 'fschecks:file_perms', 'refint:attr_indexes', 'refint:update_delay', + 'memberof:member_attr_indexes', 'monitor-disk-space:disk_space', 'replication:agmts_status', 'replication:conflicts', + 'replication:no_ruv', 'dseldif:nsstate', 'tls:certificate_expiration', 'logs:notes'] @@ -306,6 +315,8 @@ def test_healthcheck_replication(topology_m2): # If we don't set changelog trimming, we will get error DSCLLE0001 set_changelog_trimming(M1) set_changelog_trimming(M2) + M1.config.set("nsslapd-accesslog-logbuffering", "on") + M2.config.set("nsslapd-accesslog-logbuffering", "on") log.info('Run healthcheck for supplier1') run_healthcheck_and_flush_log(topology_m2, M1, CMD_OUTPUT, json=False) @@ -345,6 +356,8 @@ def test_healthcheck_replication_tls(topology_m2): M2.enable_tls() log.info('Run healthcheck for supplier1') + M1.config.set("nsslapd-accesslog-logbuffering", "on") + M2.config.set("nsslapd-accesslog-logbuffering", "on") run_healthcheck_and_flush_log(topology_m2, M1, CMD_OUTPUT, json=False) run_healthcheck_and_flush_log(topology_m2, M1, JSON_OUTPUT, json=True) @@ -397,7 +410,7 @@ def test_healthcheck_backend_missing_mapping_tree(topology_st): mts.create(properties={ 'cn': DEFAULT_SUFFIX, 'nsslapd-state': 'backend', - 'nsslapd-backend': 'userRoot', + 'nsslapd-backend': 'USERROOT', }) run_healthcheck_and_flush_log(topology_st, standalone, CMD_OUTPUT, json=False) diff --git a/src/lib389/lib389/backend.py b/src/lib389/lib389/backend.py index fd41ba537..31e457627 100644 --- a/src/lib389/lib389/backend.py +++ b/src/lib389/lib389/backend.py @@ -498,11 +498,11 @@ class Backend(DSLdapObject): * missing indices if we are local and have log access? """ # Check for the missing mapping tree. - suffix = self.get_attr_val_utf8('nsslapd-suffix') + suffix = self.get_attr_val_utf8_l('nsslapd-suffix') bename = self.lint_uid() try: mt = self._mts.get(suffix) - if mt.get_attr_val_utf8('nsslapd-backend') != bename and mt.get_attr_val_utf8('nsslapd-state') != 'backend': + if mt.get_attr_val_utf8_l('nsslapd-backend') != bename.lower() and mt.get_attr_val_utf8('nsslapd-state') != 'backend': raise ldap.NO_SUCH_OBJECT("We have a matching suffix, but not a backend or correct database name.") except ldap.NO_SUCH_OBJECT: result = DSBLE0001 diff --git a/src/lib389/lib389/config.py b/src/lib389/lib389/config.py index a7f1b545e..47334b491 100644 --- a/src/lib389/lib389/config.py +++ b/src/lib389/lib389/config.py @@ -1,5 +1,5 @@ # --- BEGIN COPYRIGHT BLOCK --- -# Copyright (C) 2020 Red Hat, Inc. +# Copyright (C) 2023 Red Hat, Inc. # All rights reserved. # # License: GPL (version 3 or any later version). @@ -22,7 +22,9 @@ from lib389._constants import * from lib389 import Entry from lib389._mapped_object import DSLdapObject from lib389.utils import ensure_bytes, selinux_label_port, selinux_present -from lib389.lint import DSCLE0001, DSCLE0002, DSELE0001 +from lib389.lint import ( + DSCLE0001, DSCLE0002, DSCLE0003, DSCLE0004, DSCLE0005, DSELE0001 +) class Config(DSLdapObject): """ @@ -219,6 +221,34 @@ class Config(DSLdapObject): report['check'] = "config:passwordscheme" yield report + def _lint_unauth_binds(self): + # Allow unauthenticated binds + unauthbinds = self.get_attr_val_utf8_l('nsslapd-allow-unauthenticated-binds') + if unauthbinds == "on": + report = copy.deepcopy(DSCLE0003) + report['fix'] = report['fix'].replace('YOUR_INSTANCE', self._instance.serverid) + report['check'] = "config:unauthorizedbinds" + yield report + + def _lint_accesslog_buffering(self): + # access log buffering + buffering = self.get_attr_val_utf8_l('nsslapd-accesslog-logbuffering') + if buffering == "off": + report = copy.deepcopy(DSCLE0004) + report['fix'] = report['fix'].replace('YOUR_INSTANCE', self._instance.serverid) + report['check'] = "config:accesslogbuffering" + yield report + + + def _lint_securitylog_buffering(self): + # security log buffering + buffering = self.get_attr_val_utf8_l('nsslapd-securitylog-logbuffering') + if buffering == "off": + report = copy.deepcopy(DSCLE0005) + report['fix'] = report['fix'].replace('YOUR_INSTANCE', self._instance.serverid) + report['check'] = "config:securitylogbuffering" + yield report + def disable_plaintext_port(self): """ Configure the server to not-provide the plaintext port. diff --git a/src/lib389/lib389/lint.py b/src/lib389/lib389/lint.py index 0219801f4..cb467634a 100644 --- a/src/lib389/lib389/lint.py +++ b/src/lib389/lib389/lint.py @@ -1,5 +1,5 @@ # --- BEGIN COPYRIGHT BLOCK --- -# Copyright (C) 2022 Red Hat, Inc. +# Copyright (C) 2023 Red Hat, Inc. # All rights reserved. # # License: GPL (version 3 or any later version). @@ -113,6 +113,52 @@ You can also use 'dsconf' to replace these values. Here is an example: # dsconf slapd-YOUR_INSTANCE config replace passwordStorageScheme=PBKDF2-SHA512 nsslapd-rootpwstoragescheme=PBKDF2-SHA512""" } +DSCLE0003 = { + 'dsle': 'DSCLE0003', + 'severity': 'MEDIUM', + 'description': 'Unauthorized Binds Allowed', + 'items': ['cn=config', ], + 'detail': """nsslapd-allow-unauthenticated-binds is set to 'on' this can +lead to unexpected results with clients and potential security issues +""", + 'fix': """Set nsslapd-allow-unauthenticated-binds to off. +You can use 'dsconf' to set this attribute. Here is an example: + + # dsconf slapd-YOUR_INSTANCE config replace nsslapd-allow-unauthenticated-binds=off""" +} + +DSCLE0004 = { + 'dsle': 'DSCLE0004', + 'severity': 'LOW', + 'description': 'Access Log buffering disabled', + 'items': ['cn=config', ], + 'detail': """nsslapd-accesslog-logbuffering is set to 'off' this will cause high +disk IO and can significantly impact server performance. This should only be used +for debug purposes +""", + 'fix': """Set nsslapd-accesslog-logbuffering to 'on'. +You can use 'dsconf' to set this attribute. Here is an example: + + # dsconf slapd-YOUR_INSTANCE config replace nsslapd-accesslog-logbuffering=on +""" +} + +DSCLE0005 = { + 'dsle': 'DSCLE0005', + 'severity': 'LOW', + 'description': 'Security Log buffering disabled', + 'items': ['cn=config', ], + 'detail': """nsslapd-securitylog-logbuffering is set to 'off' this will cause high +disk IO and it will impact server performance. This should only be used +for debug purposes +""", + 'fix': """Set nsslapd-securitylog-logbuffering to 'on'. +You can use 'dsconf' to set this attribute. Here is an example: + + # dsconf slapd-YOUR_INSTANCE config replace nsslapd-securitylog-logbuffering=on +""" +} + # Security checks DSELE0001 = { 'dsle': 'DSELE0001',
0
c772157257d2e0bbe47df7d9a74d009b6f1fc831
389ds/389-ds-base
Bug 689537 - (cov#10608) Fix Coverity NULL pointer dereferences It is possible that we dereference a NULL pointer in memberOf for a MODRDN. We should fix this to be safe, though I think it is extremely unlikely that pre_dn and post_dn will be NULL. We should check if these variables are NULL before calling memberof_replace_dn_from_groups().
commit c772157257d2e0bbe47df7d9a74d009b6f1fc831 Author: Nathan Kinder <[email protected]> Date: Tue Mar 22 10:32:16 2011 -0700 Bug 689537 - (cov#10608) Fix Coverity NULL pointer dereferences It is possible that we dereference a NULL pointer in memberOf for a MODRDN. We should fix this to be safe, though I think it is extremely unlikely that pre_dn and post_dn will be NULL. We should check if these variables are NULL before calling memberof_replace_dn_from_groups(). diff --git a/ldap/servers/plugins/memberof/memberof.c b/ldap/servers/plugins/memberof/memberof.c index b21f880c0..96aa44a3e 100644 --- a/ldap/servers/plugins/memberof/memberof.c +++ b/ldap/servers/plugins/memberof/memberof.c @@ -583,7 +583,9 @@ int memberof_postop_modrdn(Slapi_PBlock *pb) /* It's possible that this is an entry who is a member * of other group entries. We need to update any member * attributes to refer to the new name. */ - memberof_replace_dn_from_groups(pb, &configCopy, pre_dn, post_dn); + if (pre_dn && post_dn) { + memberof_replace_dn_from_groups(pb, &configCopy, pre_dn, post_dn); + } memberof_unlock(); memberof_free_config(&configCopy);
0
8afc3ccec003aece45948304411c0a77386fa9f7
389ds/389-ds-base
[206724] Replacing PR_SetNetAddr with PRLDAP_SET_PORT for IPv6 support slapi-private.h: introduced PRLDAP_SET_PORT to set port to the port field in PRNetAddr. A copy of the same macro in LDAP C SDK (v6). Note: once NSPR provides an equivalent API, we may want to replace this macro with the one. (the NSPR compatibility issue remains, though.) connection.c, daemon.c: replaced PR_SetNetAddr with PRLDAP_SET_PORT.
commit 8afc3ccec003aece45948304411c0a77386fa9f7 Author: Noriko Hosoi <[email protected]> Date: Fri Sep 15 22:45:11 2006 +0000 [206724] Replacing PR_SetNetAddr with PRLDAP_SET_PORT for IPv6 support slapi-private.h: introduced PRLDAP_SET_PORT to set port to the port field in PRNetAddr. A copy of the same macro in LDAP C SDK (v6). Note: once NSPR provides an equivalent API, we may want to replace this macro with the one. (the NSPR compatibility issue remains, though.) connection.c, daemon.c: replaced PR_SetNetAddr with PRLDAP_SET_PORT. diff --git a/ldap/servers/slapd/connection.c b/ldap/servers/slapd/connection.c index ec9b65cb6..da217cf73 100644 --- a/ldap/servers/slapd/connection.c +++ b/ldap/servers/slapd/connection.c @@ -43,7 +43,6 @@ #include <sys/socket.h> #include <stdlib.h> #endif -#define TCPLEN_T int #include <signal.h> #include "slap.h" #include "prcvar.h" @@ -64,7 +63,6 @@ static void op_copy_identity(Connection *conn, Operation *op); static int is_ber_too_big(const Connection *conn, ber_len_t ber_len); static void log_ber_too_big_error(const Connection *conn, ber_len_t ber_len, ber_len_t maxbersize); -static int add_to_select_set(Connection *conn); /* * We maintain a global work queue of Slapi_PBlock's that have not yet @@ -206,11 +204,10 @@ void connection_reset(Connection* conn, int ns, PRNetAddr * from, int fromLen, int is_SSL) { char * pTmp = is_SSL ? "SSL " : ""; - TCPLEN_T addrlen, destaddrlen; - struct sockaddr_in addr, destaddr; - char *str_ip, *str_destip, buf_ip[ 256 ], buf_destip[ 256 ]; + char *str_ip = NULL, *str_destip; + char buf_ip[ 256 ], buf_destip[ 256 ]; char *str_unknown = "unknown"; - int in_referral_mode = config_check_referral_mode(); + int in_referral_mode = config_check_referral_mode(); LDAPDebug( LDAP_DEBUG_CONNS, "new %sconnection on %d\n", pTmp, conn->c_sd, 0 ); @@ -220,120 +217,127 @@ connection_reset(Connection* conn, int ns, PRNetAddr * from, int fromLen, int is PR_Unlock( num_conns_mutex ); if (! in_referral_mode) { - PR_AtomicIncrement(g_get_global_snmp_vars()->ops_tbl.dsConnectionSeq); - PR_AtomicIncrement(g_get_global_snmp_vars()->ops_tbl.dsConnections); + PR_AtomicIncrement(g_get_global_snmp_vars()->ops_tbl.dsConnectionSeq); + PR_AtomicIncrement(g_get_global_snmp_vars()->ops_tbl.dsConnections); } - /* get peer address (IP address of this client) */ - addrlen = sizeof( addr ); - memset( &addr, 0, addrlen ); - - if ( ((from->ipv6.ip.pr_s6_addr32[0] != 0) || + /* + * get peer address (IP address of this client) + */ + slapi_ch_free( (void**)&conn->cin_addr ); /* just to be conservative */ + if ( ((from->ipv6.ip.pr_s6_addr32[0] != 0) || /* from contains non zeros */ (from->ipv6.ip.pr_s6_addr32[1] != 0) || (from->ipv6.ip.pr_s6_addr32[2] != 0) || (from->ipv6.ip.pr_s6_addr32[3] != 0)) || ((conn->c_prfd != NULL) && (PR_GetPeerName( conn->c_prfd, from ) == 0)) ) { - conn->cin_addr = (PRNetAddr *) slapi_ch_malloc( sizeof( PRNetAddr ) ); - memcpy( conn->cin_addr, from, sizeof( PRNetAddr ) ); + conn->cin_addr = (PRNetAddr *) slapi_ch_malloc( sizeof( PRNetAddr ) ); + memcpy( conn->cin_addr, from, sizeof( PRNetAddr ) ); - if ( PR_IsNetAddrType( conn->cin_addr, PR_IpAddrV4Mapped ) ) { - PRNetAddr v4addr; - memset( &v4addr, 0, sizeof( v4addr ) ); - v4addr.inet.family = PR_AF_INET; - v4addr.inet.ip = conn->cin_addr->ipv6.ip.pr_s6_addr32[3]; - PR_NetAddrToString( &v4addr, buf_ip, sizeof( buf_ip ) ); - } else { - PR_NetAddrToString( conn->cin_addr, buf_ip, sizeof( buf_ip ) ); - } - buf_ip[ sizeof( buf_ip ) - 1 ] = '\0'; - str_ip = buf_ip; - - } else if ( (conn->c_prfd == NULL) && - (getpeername( conn->c_sd, (struct sockaddr*)&addr, &addrlen ) == 0) ) { - conn->cin_addr = (PRNetAddr *)slapi_ch_malloc( sizeof( PRNetAddr ) ); + if ( PR_IsNetAddrType( conn->cin_addr, PR_IpAddrV4Mapped ) ) { + PRNetAddr v4addr; + memset( &v4addr, 0, sizeof( v4addr ) ); + v4addr.inet.family = PR_AF_INET; + v4addr.inet.ip = conn->cin_addr->ipv6.ip.pr_s6_addr32[3]; + PR_NetAddrToString( &v4addr, buf_ip, sizeof( buf_ip ) ); + } else { + PR_NetAddrToString( conn->cin_addr, buf_ip, sizeof( buf_ip ) ); + } + buf_ip[ sizeof( buf_ip ) - 1 ] = '\0'; + str_ip = buf_ip; - if ( PR_SetNetAddr(PR_IpAddrNull, PR_AF_INET6, addr.sin_port, conn->cin_addr) - != PR_SUCCESS ) { - int oserr = PR_GetError(); - LDAPDebug( LDAP_DEBUG_ANY, "PR_SetNetAddr() failed, " - SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n", - oserr, slapd_pr_strerror(oserr), 0 ); - } else { - PR_ConvertIPv4AddrToIPv6(addr.sin_addr.s_addr, &(conn->cin_addr->ipv6.ip)); - } - - /* copy string equivalent of address into a buffer to use for - * logging since each call to inet_ntoa() returns a pointer to a - * single thread-specific buffer (which prevents us from calling - * inet_ntoa() twice in one call to slapi_log_access()). - */ - str_ip = inet_ntoa( addr.sin_addr ); - strncpy( buf_ip, str_ip, sizeof( buf_ip ) - 1 ); - buf_ip[ sizeof( buf_ip ) - 1 ] = '\0'; - str_ip = buf_ip; - } else { - str_ip = str_unknown; - } - + /* try syscall since "from" was not given and PR_GetPeerName failed */ + /* a corner case */ + struct sockaddr_in addr; /* assuming IPv4 */ + socklen_t addrlen; + + addrlen = sizeof( addr ); + memset( &addr, 0, addrlen ); + + if ( (conn->c_prfd == NULL) && + (getpeername( conn->c_sd, (struct sockaddr *)&addr, &addrlen ) + == 0) ) { + conn->cin_addr = (PRNetAddr *)slapi_ch_malloc( sizeof( PRNetAddr )); + memset( conn->cin_addr, 0, sizeof( PRNetAddr ) ); + PR_NetAddrFamily( conn->cin_addr ) = AF_INET6; + /* note: IPv4-mapped IPv6 addr does not work on Windows */ + PR_ConvertIPv4AddrToIPv6(addr.sin_addr.s_addr, &(conn->cin_addr->ipv6.ip)); + PRLDAP_SET_PORT(conn->cin_addr, addr.sin_port); + + /* copy string equivalent of address into a buffer to use for + * logging since each call to inet_ntoa() returns a pointer to a + * single thread-specific buffer (which prevents us from calling + * inet_ntoa() twice in one call to slapi_log_access()). + */ + str_ip = inet_ntoa( addr.sin_addr ); + strncpy( buf_ip, str_ip, sizeof( buf_ip ) - 1 ); + buf_ip[ sizeof( buf_ip ) - 1 ] = '\0'; + str_ip = buf_ip; + } else { + str_ip = str_unknown; + } + } /* * get destination address (server IP address this client connected to) */ - destaddrlen = sizeof( destaddr ); - memset( &destaddr, 0, destaddrlen ); - - + slapi_ch_free( (void**)&conn->cin_addr ); /* just to be conservative */ if ( conn->c_prfd != NULL ) { - conn->cin_destaddr = (PRNetAddr *) slapi_ch_malloc( sizeof( PRNetAddr ) ); - if (PR_GetSockName( conn->c_prfd, conn->cin_destaddr ) == 0) { - if ( PR_IsNetAddrType( conn->cin_destaddr, PR_IpAddrV4Mapped ) ) { - PRNetAddr v4destaddr; - memset( &v4destaddr, 0, sizeof( v4destaddr ) ); - v4destaddr.inet.family = PR_AF_INET; - v4destaddr.inet.ip = conn->cin_destaddr->ipv6.ip.pr_s6_addr32[3]; - PR_NetAddrToString( &v4destaddr, buf_destip, sizeof( buf_destip ) ); - } else { - PR_NetAddrToString( conn->cin_destaddr, buf_destip, sizeof( buf_destip ) ); - } - buf_destip[ sizeof( buf_destip ) - 1 ] = '\0'; - str_destip = buf_destip; - } else { - str_destip = str_unknown; - } - } else if ( (conn->c_prfd == NULL) && - (getsockname( conn->c_sd, (struct sockaddr*)&destaddr, &destaddrlen ) == 0) ) { - conn->cin_destaddr = (PRNetAddr *)slapi_ch_malloc( sizeof( PRNetAddr ) ); - - if ( PR_SetNetAddr(PR_IpAddrNull, PR_AF_INET6, destaddr.sin_port, conn->cin_destaddr) - != PR_SUCCESS ) { - int oserr = PR_GetError(); - LDAPDebug( LDAP_DEBUG_ANY, "PR_SetNetAddr() failed, " - SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n", - oserr, slapd_pr_strerror(oserr), 0 ); - } else { - PR_ConvertIPv4AddrToIPv6(destaddr.sin_addr.s_addr, &(conn->cin_destaddr->ipv6.ip)); - } - - /* copy string equivalent of address into a buffer to use for - * logging since each call to inet_ntoa() returns a pointer to a - * single thread-specific buffer (which prevents us from calling - * inet_ntoa() twice in one call to slapi_log_access()). - */ - str_destip = inet_ntoa( destaddr.sin_addr ); - strncpy( buf_destip, str_destip, sizeof( buf_destip ) - 1 ); - buf_destip[ sizeof( buf_destip ) - 1 ] = '\0'; - str_destip = buf_destip; - + conn->cin_destaddr = (PRNetAddr *) slapi_ch_malloc( sizeof( PRNetAddr ) ); + memset( conn->cin_destaddr, 0, sizeof( PRNetAddr )); + if (PR_GetSockName( conn->c_prfd, conn->cin_destaddr ) == 0) { + if ( PR_IsNetAddrType( conn->cin_destaddr, PR_IpAddrV4Mapped ) ) { + PRNetAddr v4destaddr; + memset( &v4destaddr, 0, sizeof( v4destaddr ) ); + v4destaddr.inet.family = PR_AF_INET; + v4destaddr.inet.ip = conn->cin_destaddr->ipv6.ip.pr_s6_addr32[3]; + PR_NetAddrToString( &v4destaddr, buf_destip, sizeof( buf_destip ) ); + } else { + PR_NetAddrToString( conn->cin_destaddr, buf_destip, sizeof( buf_destip ) ); + } + buf_destip[ sizeof( buf_destip ) - 1 ] = '\0'; + str_destip = buf_destip; + } else { + str_destip = str_unknown; + } } else { - str_destip = str_unknown; - } + /* try syscall since c_prfd == NULL */ + /* a corner case */ + struct sockaddr_in destaddr; /* assuming IPv4 */ + socklen_t destaddrlen; + + destaddrlen = sizeof( destaddr ); + memset( &destaddr, 0, destaddrlen ); + if ( (getsockname( conn->c_sd, (struct sockaddr *)&destaddr, + &destaddrlen ) == 0) ) { + conn->cin_destaddr = + (PRNetAddr *)slapi_ch_malloc( sizeof( PRNetAddr )); + memset( conn->cin_destaddr, 0, sizeof( PRNetAddr )); + PR_NetAddrFamily( conn->cin_destaddr ) = AF_INET6; + PRLDAP_SET_PORT( conn->cin_destaddr, destaddr.sin_port ); + /* note: IPv4-mapped IPv6 addr does not work on Windows */ + PR_ConvertIPv4AddrToIPv6(destaddr.sin_addr.s_addr, + &(conn->cin_destaddr->ipv6.ip)); + + /* copy string equivalent of address into a buffer to use for + * logging since each call to inet_ntoa() returns a pointer to a + * single thread-specific buffer (which prevents us from calling + * inet_ntoa() twice in one call to slapi_log_access()). + */ + str_destip = inet_ntoa( destaddr.sin_addr ); + strncpy( buf_destip, str_destip, sizeof( buf_destip ) - 1 ); + buf_destip[ sizeof( buf_destip ) - 1 ] = '\0'; + str_destip = buf_destip; + } else { + str_destip = str_unknown; + } + } - if ( !in_referral_mode ) { - /* create a sasl connection */ - ids_sasl_server_new(conn); - } + if ( !in_referral_mode ) { + /* create a sasl connection */ + ids_sasl_server_new(conn); + } /* log useful stuff to our access log */ slapi_log_access( LDAP_DEBUG_STATS, @@ -343,7 +347,7 @@ connection_reset(Connection* conn, int ns, PRNetAddr * from, int fromLen, int is /* initialize the remaining connection fields */ conn->c_ldapversion = LDAP_VERSION3; conn->c_starttime = current_time(); - conn->c_idlesince = conn->c_starttime; + conn->c_idlesince = conn->c_starttime; conn->c_flags = is_SSL ? CONN_FLAG_SSL : 0; conn->c_authtype = slapi_ch_strdup(SLAPD_AUTH_NONE); } @@ -624,6 +628,7 @@ Operation *get_current_op(Connection *conn); static int handle_read_data(Connection *conn,Operation **op, int * connection_referenced); int queue_pushed_back_data(Connection *conn); +static int add_to_select_set(Connection *conn); static void inc_op_count(Connection* conn) { diff --git a/ldap/servers/slapd/daemon.c b/ldap/servers/slapd/daemon.c index 1fe82b770..adefdd4aa 100644 --- a/ldap/servers/slapd/daemon.c +++ b/ldap/servers/slapd/daemon.c @@ -277,7 +277,7 @@ accept_and_configure(int s, PRFileDesc *pr_acceptfd, PRNetAddr *pr_netaddr, PRIntervalTime pr_timeout = PR_MillisecondsToInterval(slapd_wakeup_timer); -#if !defined( XP_WIN32 ) +#if !defined( XP_WIN32 ) /* UNIX */ (*pr_clonefd) = PR_Accept(pr_acceptfd, pr_netaddr, pr_timeout); if( !(*pr_clonefd) ) { PRErrorCode prerr = PR_GetError(); @@ -289,7 +289,7 @@ accept_and_configure(int s, PRFileDesc *pr_acceptfd, PRNetAddr *pr_netaddr, ns = configure_pr_socket( pr_clonefd, secure ); -#else +#else /* Windows */ if( secure ) { (*pr_clonefd) = PR_Accept(pr_acceptfd, pr_netaddr, pr_timeout); if( !(*pr_clonefd) ) { @@ -315,10 +315,10 @@ accept_and_configure(int s, PRFileDesc *pr_acceptfd, PRNetAddr *pr_netaddr, ns = configure_pr_socket( pr_clonefd, secure ); - } else { - struct sockaddr *addr; + } else { /* !secure */ + struct sockaddr *addr; /* NOT IPv6 enabled */ - addr = (struct sockaddr *) slapi_ch_malloc( sizeof(struct sockaddr) ); + addr = (struct sockaddr *) slapi_ch_malloc( sizeof(struct sockaddr) ); ns = accept (s, addr, (TCPLEN_T *)&addrlen); if (ns == SLAPD_INVALID_SOCKET) { @@ -329,25 +329,18 @@ accept_and_configure(int s, PRFileDesc *pr_acceptfd, PRNetAddr *pr_netaddr, s, oserr, slapd_system_strerror(oserr)); } - else if (syn_scan (ns)) - { - /* this is a work around for accept problem with SYN scan on NT. - See bug 391414 for more details */ - LDAPDebug(LDAP_DEBUG_ANY, "syn-scan request is received - ignored\n", 0, 0, 0); - closesocket (ns); - ns = SLAPD_INVALID_SOCKET; - } - - if ( PR_SetNetAddr(PR_IpAddrNull, PR_AF_INET6, ((struct sockaddr_in *)addr)->sin_port, pr_netaddr) - != PR_SUCCESS ) { - int oserr = PR_GetError(); - LDAPDebug( LDAP_DEBUG_ANY, "PR_SetNetAddr() failed, " - SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n", - oserr, slapd_pr_strerror(oserr), 0 ); - } else { - PR_ConvertIPv4AddrToIPv6(((struct sockaddr_in *)addr)->sin_addr.s_addr, &(pr_netaddr->ipv6.ip)); + else if (syn_scan (ns)) + { + /* this is a work around for accept problem with SYN scan on NT. + See bug 391414 for more details */ + LDAPDebug(LDAP_DEBUG_ANY, "syn-scan request is received - ignored\n", 0, 0, 0); + closesocket (ns); + ns = SLAPD_INVALID_SOCKET; } + PRLDAP_SET_PORT( pr_netaddr, ((struct sockaddr_in *)addr)->sin_port ); + PR_ConvertIPv4AddrToIPv6(((struct sockaddr_in *)addr)->sin_addr.s_addr, &(pr_netaddr->ipv6.ip)); + (*pr_clonefd) = NULL; slapi_ch_free( (void **)&addr ); @@ -2278,7 +2271,7 @@ suppressed: static PRFileDesc * -createprlistensocket(unsigned short port, const PRNetAddr *listenaddr, +createprlistensocket(PRUint16 port, const PRNetAddr *listenaddr, int secure) { PRFileDesc *sock; @@ -2313,15 +2306,7 @@ createprlistensocket(unsigned short port, const PRNetAddr *listenaddr, /* set up listener address, including port */ memcpy(&sa_server, listenaddr, sizeof(sa_server)); - if ( PR_SetNetAddr(PR_IpAddrNull, PR_AF_INET6, port, &sa_server) - != PR_SUCCESS ) { - prerr = PR_GetError(); - slapi_log_error(SLAPI_LOG_FATAL, logname, - "PR_SetNetAddr() failed: %s error %d (%s)\n", - SLAPI_COMPONENT_NAME_NSPR, - prerr, slapd_pr_strerror(prerr)); - goto failed; - } + PRLDAP_SET_PORT( &sa_server, port ); if ( PR_Bind(sock, &sa_server) == PR_FAILURE) { prerr = PR_GetError(); @@ -2354,8 +2339,7 @@ slapd_listenhost2addr(const char *listenhost, PRNetAddr *addr) { char *logname = "slapd_listenhost2addr"; PRErrorCode prerr = 0; - PRHostEnt hent; - char hbuf[ PR_NETDB_BUF_SIZE ]; + int rval = 0; PR_ASSERT( addr != NULL ); @@ -2366,37 +2350,33 @@ slapd_listenhost2addr(const char *listenhost, PRNetAddr *addr) slapi_log_error( SLAPI_LOG_FATAL, logname, "PR_SetNetAddr(PR_IpAddrAny) failed - %s error %d (%s)\n", SLAPI_COMPONENT_NAME_NSPR, prerr, slapd_pr_strerror(prerr)); - goto failed; + rval = -1; } } else if (PR_SUCCESS == PR_StringToNetAddr(listenhost, addr)) { - if (PR_AF_INET == PR_NetAddrFamily(addr)) { - PRUint32 ipv4ip = addr->inet.ip; - memset(addr, 0, sizeof(PRNetAddr)); - PR_ConvertIPv4AddrToIPv6(ipv4ip, &addr->ipv6.ip); - addr->ipv6.family = PR_AF_INET6; - } - } else if (PR_SUCCESS == PR_GetIPNodeByName(listenhost, - PR_AF_INET6, PR_AI_DEFAULT | PR_AI_ALL, - hbuf, sizeof(hbuf), &hent )) { - /* just use the first IP address returned */ - if (PR_EnumerateHostEnt(0, &hent, 0, addr) < 0) { + /* PR_StringNetAddr newer than NSPR v4.6.2 supports both IPv4&v6 */; + } else { + PRAddrInfo *infop = PR_GetAddrInfoByName( listenhost, + PR_AF_UNSPEC, (PR_AI_ADDRCONFIG|PR_AI_NOCANONNAME) ); + if ( NULL != infop ) { + memset( addr, 0, sizeof( PRNetAddr )); + if ( NULL == PR_EnumerateAddrInfo( NULL, infop, 0, addr )) { + slapi_log_error( SLAPI_LOG_FATAL, logname, + "PR_EnumerateAddrInfo for %s failed - %s error %d (%s)\n", + listenhost, SLAPI_COMPONENT_NAME_NSPR, prerr, + slapd_pr_strerror(prerr)); + rval = -1; + } + PR_FreeAddrInfo( infop ); + } else { slapi_log_error( SLAPI_LOG_FATAL, logname, - "PR_EnumerateHostEnt() failed - %s error %d (%s)\n", - SLAPI_COMPONENT_NAME_NSPR, prerr, slapd_pr_strerror(prerr)); - goto failed; + "PR_GetAddrInfoByName(%s) failed - %s error %d (%s)\n", + listenhost, SLAPI_COMPONENT_NAME_NSPR, prerr, + slapd_pr_strerror(prerr)); + rval = -1; } - } else { /* failure */ - slapi_log_error( SLAPI_LOG_FATAL, logname, - "PR_GetIPNodeByName(%s) failed - %s error %d (%s)\n", - listenhost, SLAPI_COMPONENT_NAME_NSPR, prerr, - slapd_pr_strerror(prerr)); - goto failed; } - return( 0 ); - -failed: - return( -1 ); + return rval; } diff --git a/ldap/servers/slapd/slapi-private.h b/ldap/servers/slapd/slapi-private.h index f666c260b..7cb6021c8 100644 --- a/ldap/servers/slapd/slapi-private.h +++ b/ldap/servers/slapd/slapi-private.h @@ -1236,6 +1236,22 @@ void DS_Sleep(PRIntervalTime ticks); #define SLAPI_UPGRADEDB_SKIPINIT 0x2 /* call upgradedb as part of other op */ #endif +/* + * Macro to set port to the 'port' field of a NSPR PRNetAddr union. + ** INPUTS: + ** PRNetAddr *myaddr A network address. + ** PRUint16 myport port to set to the 'port' field of 'addr'. + ** RETURN: none + * + * Note: Copy from ldappr-int.h in + * ldapcsdk:mozilla/directory/c-sdk/ldap/libraries/libprldap + * Introduced to avoid calling PR_SetNetAddr w/ PR_IpAddrNull just to set port. + * Once NSPR starts providing better function/macro to do the same job, + * this macro should be replaced with it. (newer than NSPR v4.6.2) + */ +#define PRLDAP_SET_PORT(myaddr,myport) \ + ((myaddr)->raw.family == PR_AF_INET6 ? ((myaddr)->ipv6.port = PR_htons(myport)) : ((myaddr)->inet.port = PR_htons(myport))) + #ifdef __cplusplus } #endif
0
e6e18004badac10c667e3a9d6b14c8d9a914e2d7
389ds/389-ds-base
Issue 49029 - [RFE] improve internal operations logging Description: Added test cases and fixtures to check correct internal log values of user operations (add, rename, delete) in access log when different access log level is set. https://pagure.io/389-ds-base/issue/49029 Reviewed by: spichugi, firstyear, mreynolds (Thanks!)
commit e6e18004badac10c667e3a9d6b14c8d9a914e2d7 Author: Barbora Smejkalová <[email protected]> Date: Thu Feb 7 15:39:34 2019 +0100 Issue 49029 - [RFE] improve internal operations logging Description: Added test cases and fixtures to check correct internal log values of user operations (add, rename, delete) in access log when different access log level is set. https://pagure.io/389-ds-base/issue/49029 Reviewed by: spichugi, firstyear, mreynolds (Thanks!) diff --git a/dirsrvtests/tests/suites/ds_logs/ds_logs_test.py b/dirsrvtests/tests/suites/ds_logs/ds_logs_test.py index cfea0d2da..be4d8f896 100644 --- a/dirsrvtests/tests/suites/ds_logs/ds_logs_test.py +++ b/dirsrvtests/tests/suites/ds_logs/ds_logs_test.py @@ -11,14 +11,17 @@ from random import sample import pytest from lib389.tasks import * from lib389.utils import * +from lib389.plugins import * from lib389.topologies import topology_st - from lib389.idm.user import UserAccounts +from lib389.idm.group import Groups +from lib389.idm.organizationalunit import OrganizationalUnits logging.getLogger(__name__).setLevel(logging.DEBUG) log = logging.getLogger(__name__) PLUGIN_TIMESTAMP = 'nsslapd-logging-hr-timestamps-enabled' +PLUGIN_LOGGING = 'nsslapd-plugin-logging' USER1_DN = 'uid=user1,' + DEFAULT_SUFFIX @@ -36,12 +39,99 @@ def add_users(topology_st, users_num): 'homeDirectory' : '/home/testuser%d' % uid }) + def search_users(topology_st): users = UserAccounts(topology_st, DEFAULT_SUFFIX) entries = users.list() # We just assert we got some data ... assert len(entries) > 0 + +def delete_obj(obj): + if obj.exists(): + obj.delete() + + +def add_group_and_perform_user_operations(topology_st): + topo = topology_st.standalone + + # Add the automember group + groups = Groups(topo, DEFAULT_SUFFIX) + group = groups.create(properties={'cn': 'group'}) + + ous = OrganizationalUnits(topo, DEFAULT_SUFFIX) + branch1 = ous.create(properties={'ou': 'branch1'}) + + # Add the automember config entry + am_configs = AutoMembershipDefinitions(topo) + am_config = am_configs.create(properties={'cn': 'config', + 'autoMemberScope': branch1.dn, + 'autoMemberFilter': 'objectclass=top', + 'autoMemberDefaultGroup': group.dn, + 'autoMemberGroupingAttr': 'member:dn'}) + + # Add a user that should get added to the group + users = UserAccounts(topo, DEFAULT_SUFFIX, rdn='ou={}'.format(branch1.rdn)) + test_user = users.create_test_user(uid=777) + + # Check if created user is group member + assert test_user.dn in group.list_members() + + log.info('Renaming user') + test_user.rename('uid=new_test_user_777', newsuperior=SUFFIX) + + log.info('Delete the user') + delete_obj(test_user) + + log.info('Delete automember entry, org. unit and group for the next test') + delete_obj(am_config) + delete_obj(branch1) + delete_obj(group) + + [email protected](scope="module") +def enable_plugins(topology_st): + topo = topology_st.standalone + + log.info("Enable automember plugin") + plugin = AutoMembershipPlugin(topo) + plugin.enable() + + log.info('Enable Referential Integrity plugin') + plugin = ReferentialIntegrityPlugin(topo) + plugin.enable() + + log.info('Set nsslapd-plugin-logging to on') + topo.config.set(PLUGIN_LOGGING, 'ON') + + log.info('Restart the server') + topo.restart() + + [email protected](scope="module") +def add_user_log_level_260(topology_st, enable_plugins): + log.info('Configure access log level to 260 (4 + 256)') + access_log_level = '260' + topology_st.standalone.config.set(LOG_ACCESS_LEVEL, access_log_level) + add_group_and_perform_user_operations(topology_st) + + [email protected](scope="module") +def add_user_log_level_516(topology_st, enable_plugins): + log.info('Configure access log level to 516 (4 + 512)') + access_log_level = '516' + topology_st.standalone.config.set(LOG_ACCESS_LEVEL, access_log_level) + add_group_and_perform_user_operations(topology_st) + + [email protected](scope="module") +def add_user_log_level_131076(topology_st, enable_plugins): + log.info('Configure access log level to 131076 (4 + 131072)') + access_log_level = '131076' + topology_st.standalone.config.set(LOG_ACCESS_LEVEL, access_log_level) + add_group_and_perform_user_operations(topology_st) + + @pytest.mark.bz1273549 def test_check_default(topology_st): """Check the default value of nsslapd-logging-hr-timestamps-enabled, @@ -67,6 +157,7 @@ def test_check_default(topology_st): assert (default == "on") log.debug(default) + @pytest.mark.bz1273549 def test_plugin_set_invalid(topology_st): """Try to set some invalid values for nsslapd-logging-hr-timestamps-enabled @@ -87,6 +178,7 @@ def test_plugin_set_invalid(topology_st): with pytest.raises(ldap.OPERATIONS_ERROR): result = topology_st.standalone.config.set(PLUGIN_TIMESTAMP, 'JUNK') + @pytest.mark.bz1273549 def test_log_plugin_on(topology_st): """Check access logs for millisecond, when @@ -122,6 +214,7 @@ def test_log_plugin_on(topology_st): assert len(access_log_lines) > 0 assert topology_st.standalone.ds_access_log.match('^\[.+\d{9}.+\].+') + @pytest.mark.bz1273549 def test_log_plugin_off(topology_st): """Milliseconds should be absent from access logs when @@ -171,6 +264,357 @@ def test_log_plugin_off(topology_st): assert not topology_st.standalone.ds_access_log.match('^\[.+\d{9}.+\].+') [email protected] [email protected] +def test_internal_log_server_level_0(topology_st): + """Tests server-initiated internal operations + :id: 798d06fe-92e8-4648-af66-21349c20638e + :setup: Standalone instance + :steps: + 1. Set nsslapd-plugin-logging to on + 2. Configure access log level to only 0 + 3. Check the access logs. + :expectedresults: + 1. Operation should be successful + 2. Operation should be successful + 3. Access log should not contain internal operations log formats + """ + + topo = topology_st.standalone + + log.info('Delete the previous access logs') + topo.deleteAccessLogs() + + log.info('Set nsslapd-plugin-logging to on') + topo.config.set(PLUGIN_LOGGING, 'ON') + + log.info('Configure access log level to 0') + access_log_level = '0' + topo.config.set(LOG_ACCESS_LEVEL, access_log_level) + + log.info('Restart the server to flush the logs') + topo.restart() + + # These comments contain lines we are trying to find without regex + log.info("Check if access log does not contain internal log of MOD operation") + # (Internal) op=2(2)(1) SRCH base="cn=config + assert not topo.ds_access_log.match(r'.*\(Internal\) op=2\(2\)\(1\) SRCH base="cn=config.*') + # (Internal) op=2(2)(1) RESULT err=0 tag=48 nentries=1 + assert not topo.ds_access_log.match(r'.*\(Internal\) op=2\(2\)\(1\) RESULT err=0 tag=48 nentries=1.*') + + log.info("Check if the other internal operations are not present") + # conn=Internal(0) op=0 + assert not topo.ds_access_log.match(r'.*conn=Internal\(0\) op=0.*') + + [email protected] [email protected] +def test_internal_log_server_level_4(topology_st): + """Tests server-initiated internal operations + :id: a3500e47-d941-4575-b399-e3f4b49bc4b6 + :setup: Standalone instance + :steps: + 1. Set nsslapd-plugin-logging to on + 2. Configure access log level to only 4 + 3. Check the access logs, it should contain info about MOD operation of cn=config and other + internal operations should have the conn field set to Internal + and all values inside parenthesis set to 0. + :expectedresults: + 1. Operation should be successful + 2. Operation should be successful + 3. Access log should contain correct internal log formats with cn=config modification: + "(Internal) op=2(1)(1)" + "conn=Internal(0)" + """ + + topo = topology_st.standalone + + log.info('Delete the previous access logs for the next test') + topo.deleteAccessLogs() + + log.info('Set nsslapd-plugin-logging to on') + topo.config.set(PLUGIN_LOGGING, 'ON') + + log.info('Configure access log level to 4') + access_log_level = '4' + topo.config.set(LOG_ACCESS_LEVEL, access_log_level) + + log.info('Restart the server to flush the logs') + topo.restart() + + # These comments contain lines we are trying to find without regex + log.info("Check if access log contains internal MOD operation in correct format") + # (Internal) op=2(2)(1) SRCH base="cn=config + assert topo.ds_access_log.match(r'.*\(Internal\) op=2\(2\)\(1\) SRCH base="cn=config.*') + # (Internal) op=2(2)(1) RESULT err=0 tag=48 nentries=1 + assert topo.ds_access_log.match(r'.*\(Internal\) op=2\(2\)\(1\) RESULT err=0 tag=48 nentries=1.*') + + log.info("Check if the other internal operations have the correct format") + # conn=Internal(0) op=0 + assert topo.ds_access_log.match(r'.*conn=Internal\(0\) op=0.*') + + log.info('Delete the previous access logs for the next test') + topo.deleteAccessLogs() + + [email protected] [email protected] +def test_internal_log_level_260(topology_st, add_user_log_level_260): + """Tests client initiated operations when automember plugin is enabled + :id: e68a303e-c037-42b2-a5a0-fbea27c338a9 + :setup: Standalone instance with internal operation + logging on and nsslapd-plugin-logging to on + :steps: + 1. Configure access log level to 260 (4 + 256) + 2. Set nsslapd-plugin-logging to on + 3. Enable Referential Integrity and automember plugins + 4. Restart the server + 5. Add a test group + 6. Add a test user and add it as member of the test group + 7. Rename the test user + 8. Delete the test user + 9. Check the access logs for nested internal operation logs + :expectedresults: + 1. Operation should be successful + 2. Operation should be successful + 3. Operation should be successful + 4. Operation should be successful + 5. Operation should be successful + 6. Operation should be successful + 7. Operation should be successful + 8. Operation should be successful + 9. Access log should contain internal info about operations of the user + """ + + topo = topology_st.standalone + + log.info('Restart the server to flush the logs') + topo.restart() + + # These comments contain lines we are trying to find without regex + log.info("Check the access logs for ADD operation of the user") + # op=10 ADD dn="uid=test_user_777,ou=branch1,dc=example,dc=com" + assert topo.ds_access_log.match(r'.*op=10 ADD dn="uid=test_user_777,ou=branch1,dc=example,dc=com".*') + # (Internal) op=10(1)(1) MOD dn="cn=group,ou=Groups,dc=example,dc=com" + assert topo.ds_access_log.match(r'.*\(Internal\) op=10\(1\)\(1\) MOD dn="cn=group,ou=Groups,dc=example,dc=com".*') + # (Internal) op=10(1)(2) SRCH base="cn=group,ou=Groups,dc=example,dc=com" + assert topo.ds_access_log.match(r'.*\(Internal\) op=10\(1\)\(2\) SRCH base="cn=group,' + r'ou=Groups,dc=example,dc=com".*') + # (Internal) op=10(1)(2) RESULT err=0 tag=48 nentries=1 + assert topo.ds_access_log.match(r'.*\(Internal\) op=10\(1\)\(2\) RESULT err=0 tag=48 nentries=1*') + # (Internal) op=10(1)(1) RESULT err=0 tag=48 + assert topo.ds_access_log.match(r'.*\(Internal\) op=10\(1\)\(1\) RESULT err=0 tag=48.*') + # op=10 RESULT err=0 tag=105 + assert topo.ds_access_log.match(r'.*op=10 RESULT err=0 tag=105.*') + + log.info("Check the access logs for MOD operation of the user") + # op=12 MODRDN dn="uid=test_user_777,ou=branch1,dc=example,dc=com" ' + # 'newrdn="uid=new_test_user_777" newsuperior="dc=example,dc=com" + assert topo.ds_access_log.match(r'.*op=12 MODRDN dn="uid=test_user_777,ou=branch1,dc=example,dc=com" ' + 'newrdn="uid=new_test_user_777" newsuperior="dc=example,dc=com".*') + # (Internal) op=12(1)(1) SRCH base="uid=test_user_777, ou=branch1,dc=example,dc=com" + assert topo.ds_access_log.match(r'.*\(Internal\) op=12\(1\)\(1\) SRCH base="uid=test_user_777,' + 'ou=branch1,dc=example,dc=com".*') + # (Internal) op=12(1)(1) RESULT err=0 tag=48 nentries=1 + assert topo.ds_access_log.match(r'.*\(Internal\) op=12\(1\)\(1\) RESULT err=0 tag=48 nentries=1.*') + # op=12 RESULT err=0 tag=109 + assert topo.ds_access_log.match(r'.*op=12 RESULT err=0 tag=109.*') + + log.info("Check the access logs for DEL operation of the user") + # op=15 DEL dn="uid=new_test_user_777,dc=example,dc=com" + assert topo.ds_access_log.match(r'.*op=15 DEL dn="uid=new_test_user_777,dc=example,dc=com".*') + # (Internal) op=15(1)(1) SRCH base="uid=new_test_user_777, dc=example,dc=com" + assert topo.ds_access_log.match(r'.*\(Internal\) op=15\(1\)\(1\) SRCH base="uid=new_test_user_777,' + 'dc=example,dc=com".*') + # (Internal) op=15(1)(1) RESULT err=0 tag=48 nentries=1 + assert topo.ds_access_log.match(r'.*\(Internal\) op=15\(1\)\(1\) RESULT err=0 tag=48 nentries=1.*') + # op=15 RESULT err=0 tag=107 + assert topo.ds_access_log.match(r'.*op=15 RESULT err=0 tag=107.*') + + log.info("Check if the other internal operations have the correct format") + # conn=Internal(0) op=0 + assert topo.ds_access_log.match(r'.*conn=Internal\(0\) op=0.*') + + log.info('Delete the previous access logs for the next test') + topo.deleteAccessLogs() + + [email protected] [email protected] +def test_internal_log_level_131076(topology_st, add_user_log_level_131076): + """Tests client-initiated operations while referential integrity plugin is enabled + :id: 44836ac9-dabd-4a8c-abd5-ecd7c2509739 + :setup: Standalone instance + Configure access log level to - 131072 + 4 + Set nsslapd-plugin-logging to on + :steps: + 1. Configure access log level to 131076 + 2. Set nsslapd-plugin-logging to on + 3. Enable Referential Integrity and automember plugins + 4. Restart the server + 5. Add a test group + 6. Add a test user and add it as member of the test group + 7. Rename the test user + 8. Delete the test user + 9. Check the access logs for nested internal operation logs + :expectedresults: + 1. Operation should be successful + 2. Operation should be successful + 3. Operation should be successful + 4. Operation should be successful + 5. Operation should be successful + 6. Operation should be successful + 7. Operation should be successful + 8. Operation should be successful + 9. Access log should contain internal info about operations of the user + """ + + topo = topology_st.standalone + + log.info('Restart the server to flush the logs') + topo.restart() + + path = topo.ds_access_log._get_log_path() + with open(path) as f: + print(f.read()) + + # These comments contain lines we are trying to find without regex + log.info("Check the access logs for ADD operation of the user") + # op=10 ADD dn="uid=test_user_777,ou=branch1,dc=example,dc=com" + assert not topo.ds_access_log.match(r'.*op=10 ADD dn="uid=test_user_777,ou=branch1,dc=example,dc=com".*') + # (Internal) op=10(1)(1) MOD dn="cn=group,ou=Groups,dc=example,dc=com" + assert topo.ds_access_log.match(r'.*\(Internal\) op=10\(1\)\(1\) MOD dn="cn=group,ou=Groups,dc=example,dc=com".*') + # (Internal) op=10(1)(2) SRCH base="cn=group,ou=Groups,dc=example,dc=com" + assert topo.ds_access_log.match(r'.*\(Internal\) op=10\(1\)\(2\) SRCH base="cn=group,ou=Groups,dc=example,dc=com".*') + # (Internal) op=10(1)(2) RESULT err=0 tag=48 nentries=1*') + assert topo.ds_access_log.match(r'.*\(Internal\) op=10\(1\)\(2\) RESULT err=0 tag=48 nentries=1*') + # (Internal) op=10(1)(1) RESULT err=0 tag=48 + assert topo.ds_access_log.match(r'.*\(Internal\) op=10\(1\)\(1\) RESULT err=0 tag=48.*') + # op=10 RESULT err=0 tag=105 + assert not topo.ds_access_log.match(r'.*op=10 RESULT err=0 tag=105.*') + + log.info("Check the access logs for MOD operation of the user") + # op=12 MODRDN dn="uid=test_user_777,ou=branch1,dc=example,dc=com" ' + # 'newrdn="uid=new_test_user_777" newsuperior="dc=example,dc=com" + assert not topo.ds_access_log.match(r'.*op=12 MODRDN dn="uid=test_user_777,ou=branch1,dc=example,dc=com" ' + 'newrdn="uid=new_test_user_777" newsuperior="dc=example,dc=com".*') + # (Internal) op=12(1)(1) SRCH base="uid=test_user_777, ou=branch1,dc=example,dc=com" + assert topo.ds_access_log.match(r'.*\(Internal\) op=12\(1\)\(1\) SRCH base="uid=test_user_777,' + 'ou=branch1,dc=example,dc=com".*') + # (Internal) op=12(1)(1) RESULT err=0 tag=48 nentries=1 + assert topo.ds_access_log.match(r'.*\(Internal\) op=12\(1\)\(1\) RESULT err=0 tag=48 nentries=1.*') + # op=12 RESULT err=0 tag=109 + assert not topo.ds_access_log.match(r'.*op=12 RESULT err=0 tag=109.*') + + log.info("Check the access logs for DEL operation of the user") + # op=15 DEL dn="uid=new_test_user_777,dc=example,dc=com" + assert not topo.ds_access_log.match(r'.*op=15 DEL dn="uid=new_test_user_777,dc=example,dc=com".*') + # (Internal) op=15(1)(1) SRCH base="uid=new_test_user_777, dc=example,dc=com" + assert topo.ds_access_log.match(r'.*\(Internal\) op=15\(1\)\(1\) SRCH base="uid=new_test_user_777,' + 'dc=example,dc=com".*') + # (Internal) op=15(1)(1) RESULT err=0 tag=48 nentries=1 + assert topo.ds_access_log.match(r'.*\(Internal\) op=15\(1\)\(1\) RESULT err=0 tag=48 nentries=1.*') + # op=15 RESULT err=0 tag=107 + assert not topo.ds_access_log.match(r'.*op=15 RESULT err=0 tag=107.*') + + log.info("Check if the other internal operations have the correct format") + # conn=Internal(0) op=0 + assert topo.ds_access_log.match(r'.*conn=Internal\(0\) op=0.*') + + log.info('Delete the previous access logs for the next test') + topo.deleteAccessLogs() + + [email protected] [email protected] +def test_internal_log_level_516(topology_st, add_user_log_level_516): + """Tests client initiated operations when referential integrity plugin is enabled + :id: bee1d681-763d-4fa5-aca2-569cf93f8b71 + :setup: Standalone instance + Configure access log level to - 512+4 + Set nsslapd-plugin-logging to on + :steps: + 1. Configure access log level to 516 + 2. Set nsslapd-plugin-logging to on + 3. Enable Referential Integrity and automember plugins + 4. Restart the server + 5. Add a test group + 6. Add a test user and add it as member of the test group + 7. Rename the test user + 8. Delete the test user + 9. Check the access logs for nested internal operation logs + :expectedresults: + 1. Operation should be successful + 2. Operation should be successful + 3. Operation should be successful + 4. Operation should be successful + 5. Operation should be successful + 6. Operation should be successful + 7. Operation should be successful + 8. Operation should be successful + 9. Access log should contain internal info about operations of the user + """ + + topo = topology_st.standalone + + log.info('Restart the server to flush the logs') + topo.restart() + + # These comments contain lines we are trying to find without regex + log.info("Check the access logs for ADD operation of the user") + # op=10 ADD dn="uid=test_user_777,ou=branch1,dc=example,dc=com" + assert not topo.ds_access_log.match(r'.*op=10 ADD dn="uid=test_user_777,ou=branch1,dc=example,dc=com".*') + # (Internal) op=10(1)(1) MOD dn="cn=group,ou=Groups,dc=example,dc=com" + assert topo.ds_access_log.match(r'.*\(Internal\) op=10\(1\)\(1\) MOD dn="cn=group,ou=Groups,dc=example,dc=com".*') + # (Internal) op=10(1)(2) SRCH base="cn=group,ou=Groups,dc=example,dc=com" + assert topo.ds_access_log.match(r'.*\(Internal\) op=10\(1\)\(2\) SRCH base="cn=group,ou=Groups,dc=example,dc=com".*') + # (Internal) op=10(1)(2) ENTRY dn="cn=group,ou=Groups,dc=example,dc=com" + assert topo.ds_access_log.match(r'.*\(Internal\) op=10\(1\)\(2\) ENTRY dn="cn=group,ou=Groups,dc=example,dc=com".*') + # (Internal) op=10(1)(2) RESULT err=0 tag=48 nentries=1*') + assert topo.ds_access_log.match(r'.*\(Internal\) op=10\(1\)\(2\) RESULT err=0 tag=48 nentries=1*') + # (Internal) op=10(1)(1) RESULT err=0 tag=48 + assert topo.ds_access_log.match(r'.*\(Internal\) op=10\(1\)\(1\) RESULT err=0 tag=48.*') + # op=10 RESULT err=0 tag=105 + assert not topo.ds_access_log.match(r'.*op=10 RESULT err=0 tag=105.*') + + log.info("Check the access logs for MOD operation of the user") + # op=12 MODRDN dn="uid=test_user_777,ou=branch1,dc=example,dc=com" ' + # 'newrdn="uid=new_test_user_777" newsuperior="dc=example,dc=com" + assert not topo.ds_access_log.match(r'.*op=12 MODRDN dn="uid=test_user_777,ou=branch1,dc=example,dc=com" ' + 'newrdn="uid=new_test_user_777" newsuperior="dc=example,dc=com".*') + # Internal) op=12(1)(1) SRCH base="uid=test_user_777, ou=branch1,dc=example,dc=com" + assert topo.ds_access_log.match(r'.*\(Internal\) op=12\(1\)\(1\) SRCH base="uid=test_user_777,' + 'ou=branch1,dc=example,dc=com".*') + # (Internal) op=12(1)(1) ENTRY dn="uid=test_user_777, ou=branch1,dc=example,dc=com" + assert topo.ds_access_log.match(r'.*\(Internal\) op=12\(1\)\(1\) ENTRY dn="uid=test_user_777,' + 'ou=branch1,dc=example,dc=com".*') + # (Internal) op=12(1)(1) RESULT err=0 tag=48 nentries=1 + assert topo.ds_access_log.match(r'.*\(Internal\) op=12\(1\)\(1\) RESULT err=0 tag=48 nentries=1.*') + # op=12 RESULT err=0 tag=109 + assert not topo.ds_access_log.match(r'.*op=12 RESULT err=0 tag=109.*') + + log.info("Check the access logs for DEL operation of the user") + # op=15 DEL dn="uid=new_test_user_777,dc=example,dc=com" + assert not topo.ds_access_log.match(r'.*op=15 DEL dn="uid=new_test_user_777,dc=example,dc=com".*') + # (Internal) op=15(1)(1) SRCH base="uid=new_test_user_777, dc=example,dc=com" + assert topo.ds_access_log.match(r'.*\(Internal\) op=15\(1\)\(1\) SRCH base="uid=new_test_user_777,' + 'dc=example,dc=com".*') + # (Internal) op=15(1)(1) ENTRY dn="uid=new_test_user_777, dc=example,dc=com" + assert topo.ds_access_log.match(r'.*\(Internal\) op=15\(1\)\(1\) ENTRY dn="uid=new_test_user_777,' + 'dc=example,dc=com".*') + # (Internal) op=15(1)(1) RESULT err=0 tag=48 nentries=1 + assert topo.ds_access_log.match(r'.*\(Internal\) op=15\(1\)\(1\) RESULT err=0 tag=48 nentries=1.*') + # op=15 RESULT err=0 tag=107 + assert not topo.ds_access_log.match(r'.*op=15 RESULT err=0 tag=107.*') + + log.info("Check if the other internal operations have the correct format") + # conn=Internal(0) op=0 + assert topo.ds_access_log.match(r'.*conn=Internal\(0\) op=0.*') + + log.info('Delete the previous access logs for the next test') + topo.deleteAccessLogs() + + if __name__ == '__main__': # Run isolated # -s for DEBUG mode
0
3d4c48eb4fc78628ef15e981d5175c68ab9ee4d8
389ds/389-ds-base
Ticket 50355 - NSS can change the requested SSL min and max versions Description: If we try and set a min and max SSL version in the server, it is actually only a request. After setting the min and max, you need to retrieve the min and max to see what NSS did. Then you have to reset the min and max versions one more time to actually set the valid range. So yes, you do have to do a set() -> get() -> set(). There also another outstanding issue with NSS where it says the default max SSL version in FIPS mode is 1.3, but in fact it is 1.2. So this patch has a hack fix to workaround that bug. It should be able to be removed soon... https://pagure.io/389-ds-base/issue/50355 Reviewed by: mhonek(Thanks!)
commit 3d4c48eb4fc78628ef15e981d5175c68ab9ee4d8 Author: Mark Reynolds <[email protected]> Date: Tue May 14 16:58:55 2019 -0400 Ticket 50355 - NSS can change the requested SSL min and max versions Description: If we try and set a min and max SSL version in the server, it is actually only a request. After setting the min and max, you need to retrieve the min and max to see what NSS did. Then you have to reset the min and max versions one more time to actually set the valid range. So yes, you do have to do a set() -> get() -> set(). There also another outstanding issue with NSS where it says the default max SSL version in FIPS mode is 1.3, but in fact it is 1.2. So this patch has a hack fix to workaround that bug. It should be able to be removed soon... https://pagure.io/389-ds-base/issue/50355 Reviewed by: mhonek(Thanks!) diff --git a/ldap/servers/slapd/ssl.c b/ldap/servers/slapd/ssl.c index a7c3ab7b1..2d7bc2bd6 100644 --- a/ldap/servers/slapd/ssl.c +++ b/ldap/servers/slapd/ssl.c @@ -41,15 +41,15 @@ * Default SSL Version Rule * Old SSL version attributes: * nsSSL3: off -- nsSSL3 == SSL_LIBRARY_VERSION_3_0 - * nsTLS1: on -- nsTLS1 == SSL_LIBRARY_VERSION_TLS_1_0 and greater + * nsTLS1: on -- nsTLS1 == SSL_LIBRARY_VERSION_TLS_1_2 and greater * Note: TLS1.0 is defined in RFC2246, which is close to SSL 3.0. * New SSL version attributes: - * sslVersionMin: TLS1.0 + * sslVersionMin: TLS1.2 * sslVersionMax: max ssl version supported by NSS ******************************************************************************/ -#define DEFVERSION "TLS1.0" -#define CURRENT_DEFAULT_SSL_VERSION SSL_LIBRARY_VERSION_TLS_1_0 +#define DEFVERSION "TLS1.2" +#define CURRENT_DEFAULT_SSL_VERSION SSL_LIBRARY_VERSION_TLS_1_2 extern char *slapd_SSL3ciphers; extern symbol_t supported_ciphers[]; @@ -435,8 +435,13 @@ getSSLVersionRange(char **min, char **max) return -1; } if (!slapd_ssl_listener_is_initialized()) { + /* + * We have not initialized NSS yet, so we will set the default for + * now. Then it will get adjusted to NSS's default min and max once + * we complete the security initialization in slapd_ssl_init2() + */ if (min) { - *min = slapi_getSSLVersion_str(LDAP_OPT_X_TLS_PROTOCOL_TLS1_0, NULL, 0); + *min = slapi_getSSLVersion_str(LDAP_OPT_X_TLS_PROTOCOL_TLS1_2, NULL, 0); } if (max) { *max = slapi_getSSLVersion_str(LDAP_OPT_X_TLS_PROTOCOL_TLS1_2, NULL, 0); @@ -457,7 +462,7 @@ getSSLVersionRangeOL(int *min, int *max) { /* default range values */ if (min) { - *min = LDAP_OPT_X_TLS_PROTOCOL_TLS1_0; + *min = LDAP_OPT_X_TLS_PROTOCOL_TLS1_2; } if (max) { *max = LDAP_OPT_X_TLS_PROTOCOL_TLS1_2; @@ -2099,43 +2104,57 @@ slapd_ssl_init2(PRFileDesc **fd, int startTLS) } } - if (NSSVersionMin > 0) { - /* Use new NSS API SSL_VersionRangeSet (NSS3.14 or newer) */ - slapdNSSVersions.min = NSSVersionMin; - slapdNSSVersions.max = NSSVersionMax; - restrict_SSLVersionRange(); - (void)slapi_getSSLVersion_str(slapdNSSVersions.min, mymin, sizeof(mymin)); - (void)slapi_getSSLVersion_str(slapdNSSVersions.max, mymax, sizeof(mymax)); - slapi_log_err(SLAPI_LOG_INFO, "Security Initialization", - "slapd_ssl_init2 - Configured SSL version range: min: %s, max: %s\n", - mymin, mymax); + /* Handle the SSL version range */ + slapdNSSVersions.min = NSSVersionMin; + slapdNSSVersions.max = NSSVersionMax; + restrict_SSLVersionRange(); + (void)slapi_getSSLVersion_str(slapdNSSVersions.min, mymin, sizeof(mymin)); + (void)slapi_getSSLVersion_str(slapdNSSVersions.max, mymax, sizeof(mymax)); + slapi_log_err(SLAPI_LOG_INFO, "Security Initialization", + "slapd_ssl_init2 - Configured SSL version range: min: %s, max: %s\n", + mymin, mymax); + sslStatus = SSL_VersionRangeSet(pr_sock, &slapdNSSVersions); + if (sslStatus != SECSuccess) { + errorCode = PR_GetError(); + slapd_SSL_error("Security Initialization - " + "slapd_ssl_init2 - Failed to set SSL range: min: %s, max: %s - error %d (%s)\n", + mymin, mymax, errorCode, slapd_pr_strerror(errorCode)); + } + /* + * Get the version range as NSS might have adjusted our requested range. FIPS mode is + * pretty picky about this stuff. + */ + sslStatus = SSL_VersionRangeGet(pr_sock, &slapdNSSVersions); + if (sslStatus == SECSuccess) { + if (slapdNSSVersions.max > LDAP_OPT_X_TLS_PROTOCOL_TLS1_2 && slapd_pk11_isFIPS()) { + /* + * FIPS & NSS currently only support a max version of TLS1.2 + * (although NSS advertises 1.3 as a max range in FIPS mode), + * hopefully this code block can be removed soon... + */ + slapdNSSVersions.max = LDAP_OPT_X_TLS_PROTOCOL_TLS1_2; + } + /* Reset request range */ sslStatus = SSL_VersionRangeSet(pr_sock, &slapdNSSVersions); if (sslStatus == SECSuccess) { - /* Set the restricted value to the cn=encryption entry */ + (void)slapi_getSSLVersion_str(slapdNSSVersions.min, mymin, sizeof(mymin)); + (void)slapi_getSSLVersion_str(slapdNSSVersions.max, mymax, sizeof(mymax)); + slapi_log_err(SLAPI_LOG_INFO, "Security Initialization", + "slapd_ssl_init2 - NSS adjusted SSL version range: min: %s, max: %s\n", + mymin, mymax); } else { + errorCode = PR_GetError(); + (void)slapi_getSSLVersion_str(slapdNSSVersions.min, mymin, sizeof(mymin)); + (void)slapi_getSSLVersion_str(slapdNSSVersions.max, mymax, sizeof(mymax)); slapd_SSL_error("Security Initialization - " - "slapd_ssl_init2 - Failed to set SSL range: min: %s, max: %s\n", - mymin, mymax); + "slapd_ssl_init2 - Failed to set SSL range: min: %s, max: %s - error %d (%s)\n", + mymin, mymax, errorCode, slapd_pr_strerror(errorCode)); } } else { - /* deprecated code */ - sslStatus = SSL_OptionSet(pr_sock, SSL_ENABLE_SSL3, enableSSL3); - if (sslStatus != SECSuccess) { - errorCode = PR_GetError(); - slapd_SSL_warn("Failed to %s SSLv3 " - "on the imported socket (" SLAPI_COMPONENT_NAME_NSPR " error %d - %s)", - enableSSL3 ? "enable" : "disable", - errorCode, slapd_pr_strerror(errorCode)); - } - - sslStatus = SSL_OptionSet(pr_sock, SSL_ENABLE_TLS, enableTLS1); - if (sslStatus != SECSuccess) { - errorCode = PR_GetError(); - slapd_SSL_warn("Failed to %s TLSv1 " - "on the imported socket (" SLAPI_COMPONENT_NAME_NSPR " error %d - %s)", - enableTLS1 ? "enable" : "disable", - errorCode, slapd_pr_strerror(errorCode)); - } + errorCode = PR_GetError(); + slapd_SSL_error("Security Initialization - ", + "slapd_ssl_init2 - Failed to get SSL range from socket - error %d (%s)\n", + errorCode, slapd_pr_strerror(errorCode)); } val = NULL; @@ -2221,7 +2240,7 @@ slapd_ssl_init2(PRFileDesc **fd, int startTLS) * that matters. */ if (!startTLS) - _ssl_listener_initialized = 1; /* --ugaston */ + _ssl_listener_initialized = 1; return 0; }
0
07d7c8977e783d1e9c34c25ce09f7a162a391c4a
389ds/389-ds-base
Bug 630090 - (cov#15445) Fix illegal free in archive code The directory variable points to a dynamically allocated string returned by rel2abspath(). We are changing directory to point to a string constant if we are unable to parse the directory. This not only leaks memory, but it can cause us to attempt to free the string constant. We should free the string before we overwrite it, and we should dynamically allocate a new string instead of using a string constant.
commit 07d7c8977e783d1e9c34c25ce09f7a162a391c4a Author: Nathan Kinder <[email protected]> Date: Thu Sep 9 10:35:11 2010 -0700 Bug 630090 - (cov#15445) Fix illegal free in archive code The directory variable points to a dynamically allocated string returned by rel2abspath(). We are changing directory to point to a string constant if we are unable to parse the directory. This not only leaks memory, but it can cause us to attempt to free the string constant. We should free the string before we overwrite it, and we should dynamically allocate a new string instead of using a string constant. diff --git a/ldap/servers/slapd/back-ldbm/archive.c b/ldap/servers/slapd/back-ldbm/archive.c index f048a6fc4..edaa5edf8 100644 --- a/ldap/servers/slapd/back-ldbm/archive.c +++ b/ldap/servers/slapd/back-ldbm/archive.c @@ -208,7 +208,8 @@ int ldbm_back_archive2ldbm( Slapi_PBlock *pb ) if (NULL == p) /* never happen, I guess */ { - directory = "."; + slapi_ch_free_string(&directory); + directory = slapi_ch_smprintf("."); c = '/'; } else
0
d2a3f2eb6261374bc24a618bb3483da622d9aa99
389ds/389-ds-base
Ticket 4313 - improve tests and improve readme re refdel Bug Description: This is a supplement to 51260. Fix Description: This expands the test cases to be able to detect the subsequent data corruption of 51260. This also improves documentation around the rfc, and some todo comments for future work with entryuuid + openldap. Fixes: https://github.com/389ds/389-ds-base/issues/4313 Author: William Brown <[email protected]> Review by: @tbordaz
commit d2a3f2eb6261374bc24a618bb3483da622d9aa99 Author: William Brown <[email protected]> Date: Mon Sep 7 13:23:03 2020 +1000 Ticket 4313 - improve tests and improve readme re refdel Bug Description: This is a supplement to 51260. Fix Description: This expands the test cases to be able to detect the subsequent data corruption of 51260. This also improves documentation around the rfc, and some todo comments for future work with entryuuid + openldap. Fixes: https://github.com/389ds/389-ds-base/issues/4313 Author: William Brown <[email protected]> Review by: @tbordaz diff --git a/dirsrvtests/tests/suites/syncrepl_plugin/__init__.py b/dirsrvtests/tests/suites/syncrepl_plugin/__init__.py index d51f52fba..8baa7355d 100644 --- a/dirsrvtests/tests/suites/syncrepl_plugin/__init__.py +++ b/dirsrvtests/tests/suites/syncrepl_plugin/__init__.py @@ -21,6 +21,8 @@ from lib389._constants import * log = logging.getLogger(__name__) +OU_PEOPLE = "ou=people,%s" % DEFAULT_SUFFIX + class ISyncRepl(DirSrv, SyncreplConsumer): """ This implements a test harness for checking syncrepl, and allowing us to check various actions or @@ -28,6 +30,11 @@ class ISyncRepl(DirSrv, SyncreplConsumer): later to ensure that syncrepl worked as expected. """ def __init__(self, inst, openldap=False): + ### 🚧 WARNING 🚧 + # There are bugs with python ldap sync repl in ALL VERSIONS below 3.3.1. + # These tests WILL FAIL unless you have version 3.3.1 or higher! + assert ldap.__version__ >= '3.3.1' + self.inst = inst self.msgid = None @@ -55,6 +62,7 @@ class ISyncRepl(DirSrv, SyncreplConsumer): self.delete = [] self.present = [] self.entries = {} + self.refdel = False self.next_cookie = None # Start the sync # If cookie is none, will call "get_cookie" we have. @@ -89,6 +97,9 @@ class ISyncRepl(DirSrv, SyncreplConsumer): def syncrepl_present(self, uuids, refreshDeletes=False): log.debug(f'=====> refdel -> {refreshDeletes} uuids -> {uuids}') + if refreshDeletes: + # Indicate we recieved a refdel in the process. + self.refdel = True if uuids is not None: self.present = self.present + uuids @@ -105,8 +116,9 @@ class ISyncRepl(DirSrv, SyncreplConsumer): def syncstate_assert(st, sync): # How many entries do we have? + # We setup sync under ou=people so we can modrdn out of the scope. r = st.search_ext_s( - base=DEFAULT_SUFFIX, + base=OU_PEOPLE, scope=ldap.SCOPE_SUBTREE, filterstr='(objectClass=*)', attrsonly=1, @@ -115,49 +127,154 @@ def syncstate_assert(st, sync): # Initial sync log.debug("*test* initial") - sync.syncrepl_search() + sync.syncrepl_search(base=OU_PEOPLE) sync.syncrepl_complete() # check we caught them all assert len(r) == len(sync.entries.keys()) assert len(r) == len(sync.present) assert 0 == len(sync.delete) + if sync.openldap: + assert True == sync.refdel + else: + assert False == sync.refdel # Add a new entry - account = nsUserAccounts(st, DEFAULT_SUFFIX).create_test_user() + + # Find the primary uuid we expect to see in syncrepl. + # This will be None if not present. + acc_uuid = account.get_attr_val_utf8('entryuuid') + if acc_uuid is None: + nsid = account.get_attr_val_utf8('nsuniqueid') + # nsunique has a diff format, so we change it up. + # 431cf081-b44311ea-83fdb082-f24d490e + # Add a hyphen V + # 431cf081-b443-11ea-83fdb082-f24d490e + nsid_a = nsid[:13] + '-' + nsid[13:] + # Add a hyphen V + # 431cf081-b443-11ea-83fd-b082-f24d490e + nsid_b = nsid_a[:23] + '-' + nsid_a[23:] + # Remove a hyphen V + # 431cf081-b443-11ea-83fd-b082-f24d490e + acc_uuid = nsid_b[:28] + nsid_b[29:] + # Tada! + # 431cf081-b443-11ea-83fd-b082f24d490e + log.debug(f"--> expected sync uuid (from nsuniqueid): {acc_uuid}") + else: + log.debug(f"--> expected sync uuid (from entryuuid): {acc_uuid}") + # Check log.debug("*test* add") - sync.syncrepl_search() + sync.syncrepl_search(base=OU_PEOPLE) sync.syncrepl_complete() sync.check_cookie() + log.debug(f"sd: {sync.delete}, sp: {sync.present} sek: {sync.entries.keys()}") + assert 1 == len(sync.entries.keys()) assert 1 == len(sync.present) + #################################### + ## assert sync.present == [acc_uuid] assert 0 == len(sync.delete) + if sync.openldap: + assert True == sync.refdel + else: + assert False == sync.refdel # Mod account.replace('description', 'change') # Check log.debug("*test* mod") - sync.syncrepl_search() + sync.syncrepl_search(base=OU_PEOPLE) + sync.syncrepl_complete() + sync.check_cookie() + log.debug(f"sd: {sync.delete}, sp: {sync.present} sek: {sync.entries.keys()}") + assert 1 == len(sync.entries.keys()) + assert 1 == len(sync.present) + #################################### + ## assert sync.present == [acc_uuid] + assert 0 == len(sync.delete) + if sync.openldap: + assert True == sync.refdel + else: + assert False == sync.refdel + + ## ModRdn (remain in scope) + account.rename('uid=test1_modrdn') + # newsuperior=None + # Check + log.debug("*test* modrdn (in scope)") + sync.syncrepl_search(base=OU_PEOPLE) + sync.syncrepl_complete() + sync.check_cookie() + log.debug(f"sd: {sync.delete}, sp: {sync.present} sek: {sync.entries.keys()}") + assert 1 == len(sync.entries.keys()) + assert 1 == len(sync.present) + #################################### + ## assert sync.present == [acc_uuid] + assert 0 == len(sync.delete) + if sync.openldap: + assert True == sync.refdel + else: + assert False == sync.refdel + + ## Modrdn (out of scope, then back into scope) + account.rename('uid=test1_modrdn', newsuperior=DEFAULT_SUFFIX) + + # Check it's gone. + log.debug("*test* modrdn (move out of scope)") + sync.syncrepl_search(base=OU_PEOPLE) + sync.syncrepl_complete() + sync.check_cookie() + log.debug(f"sd: {sync.delete}, sp: {sync.present} sek: {sync.entries.keys()}") + assert 0 == len(sync.entries.keys()) + assert 0 == len(sync.present) + assert 0 == len(sync.delete) + if sync.openldap: + assert True == sync.refdel + else: + assert True == sync.refdel + + # Put it back + account.rename('uid=test1_modrdn', newsuperior=OU_PEOPLE) + log.debug("*test* modrdn (move in to scope)") + sync.syncrepl_search(base=OU_PEOPLE) sync.syncrepl_complete() sync.check_cookie() + log.debug(f"sd: {sync.delete}, sp: {sync.present} sek: {sync.entries.keys()}") assert 1 == len(sync.entries.keys()) assert 1 == len(sync.present) + #################################### + ## assert sync.present == [acc_uuid] assert 0 == len(sync.delete) + if sync.openldap: + assert True == sync.refdel + else: + assert False == sync.refdel ## Delete account.delete() + # import time + # print("attach now ....") + # time.sleep(45) + # Check log.debug("*test* del") - sync.syncrepl_search() + sync.syncrepl_search(base=OU_PEOPLE) sync.syncrepl_complete() # In a delete, the cookie isn't updated (?) sync.check_cookie() log.debug(f'{sync.entries.keys()}') log.debug(f'{sync.present}') log.debug(f'{sync.delete}') + log.debug(f"sd: {sync.delete}, sp: {sync.present} sek: {sync.entries.keys()}") assert 0 == len(sync.entries.keys()) assert 0 == len(sync.present) - assert 1 == len(sync.delete) + assert 0 == len(sync.delete) + #################################### + ## assert sync.delete == [acc_uuid] + if sync.openldap: + assert True == sync.refdel + else: + assert True == sync.refdel diff --git a/dirsrvtests/tests/suites/syncrepl_plugin/basic_test.py b/dirsrvtests/tests/suites/syncrepl_plugin/basic_test.py index 94fd02139..04c0a0985 100644 --- a/dirsrvtests/tests/suites/syncrepl_plugin/basic_test.py +++ b/dirsrvtests/tests/suites/syncrepl_plugin/basic_test.py @@ -109,6 +109,8 @@ def init_sync_repl_plugins(topology, request): pass request.addfinalizer(fin) [email protected](ldap.__version__ < '3.3.1', + reason="python ldap versions less that 3.3.1 have bugs in sync repl that will cause this to fail!") def test_syncrepl_basic(topology): """ Test basic functionality of the SyncRepl interface diff --git a/ldap/servers/plugins/sync/README.md b/ldap/servers/plugins/sync/README.md new file mode 100644 index 000000000..af6d302f6 --- /dev/null +++ b/ldap/servers/plugins/sync/README.md @@ -0,0 +1,42 @@ +With support from a techwriter at SUSE, we managed to translate RCF4533 +into something we can understand. + +* Server issues Sync Operation to search. +* Search returns entries +* Each entry has a state add which includes the UUID of the entry +* Distinguished names can change, but UUIDs are stable. +* At the end of the search results, a sync done control cookie is sent to indicate that the session is done. + +* Clients issue a Sync Operation to search, and include previously returned cookie. +* Server determines what would be returned in a normal search operation. +* Server uses cookie to work out what was previously returned. +* Server issues results of only the things that have changed since last search. +* Each result sent also includes info about the status (changed or unchanged) + +* Server has two phases to sync deleted entries: present or delete. +* Each phase ends with a sync done control cookie. +* The present phase ends with sync done control value of searchresultdone=false +* the delete phase ends with sync done control value of searchresultdone=true +* The present phase can be followed by the delete phase. +* Each phase is complete only after a sync info message of refreshdone=false + +* During the present phase, the server sends an empty entry with state=present for each unchanged entry. +* During the present phase, the client is changed to match the server state, in preparation for the delete phase. +* During the delete phase, the server determines which entries in the client copy are no longer present. It also checks that the the number of changed entries is less than the number of unchanged entries. + For each entry that is no longer present, the server sends a state=delete. It does not* return a state=present for each present entry. + +* The server can send sync info messages that contain the list of UUIDs of either unchanged present entries, or deleted entries. This is instead of sending individual messages for each entry. +* If refreshDeletes=false the UUIDs of unchanged present entries are included in the syncUUIDs set. +* If refreshDeletes=true the UUIDs of unchanged deleted entries are included in the syncUUIDs set. +* Optionally, you can include a syncIdSet cookie to indicate the state of the content in the syncUUIDs set. + +* If the syncDoneValue is refreshDeletes=false the new copy includes: +- All changed entries returned by the current sync +- All unchanged entries from a previous sync that have been confirmed to still be present +- Unchanged entries confirmed as deleted are deleted from the client. In this case, they are assumed to have been deleted or moved. + +* If the syncDoneValue is refreshDeletes=true the new copy includes: +- All changed entries returned by the current sync +- All entries from a previous sync that have not been marked as deleted. + +* Clients can request that the synchronized copy is refreshed at any time. diff --git a/ldap/servers/plugins/sync/sync_refresh.c b/ldap/servers/plugins/sync/sync_refresh.c index 25dd8d6c9..28963cc02 100644 --- a/ldap/servers/plugins/sync/sync_refresh.c +++ b/ldap/servers/plugins/sync/sync_refresh.c @@ -234,6 +234,8 @@ sync_srch_refresh_post_search(Slapi_PBlock *pb) * Point is, if we set refresh to true for openldap mode, it works, and if * it's false, the moment we send a single intermediate delete message, we * delete literally everything 🔥. + * + * See README.md for more about how this works. */ if (info->cookie->openldap_compat) { sync_create_sync_done_control(&ctrl[0], 1, cookiestr);
0
4f11606b02419c8ccdb319b8040e683af9109d1b
389ds/389-ds-base
Ticket #47748 - Simultaneous adding a user and binding as the user could fail in the password policy check Description: commit 4fc53e1a63222d0ff67c30a59f2cff4b535f90a8 fix for Ticket #47748 introduced a bug: "Simple bind hangs after enabling password policy". In do_bind, slapi_check_account_lock and need_new_pw overwrote the return code from backend bind which is used later. This patch fixes it not to override the return code. https://fedorahosted.org/389/ticket/47748 Reviewed by [email protected] (Thank you, Mark!!)
commit 4f11606b02419c8ccdb319b8040e683af9109d1b Author: Noriko Hosoi <[email protected]> Date: Tue Sep 9 12:45:58 2014 -0700 Ticket #47748 - Simultaneous adding a user and binding as the user could fail in the password policy check Description: commit 4fc53e1a63222d0ff67c30a59f2cff4b535f90a8 fix for Ticket #47748 introduced a bug: "Simple bind hangs after enabling password policy". In do_bind, slapi_check_account_lock and need_new_pw overwrote the return code from backend bind which is used later. This patch fixes it not to override the return code. https://fedorahosted.org/389/ticket/47748 Reviewed by [email protected] (Thank you, Mark!!) diff --git a/ldap/servers/slapd/bind.c b/ldap/servers/slapd/bind.c index 58a4e1324..bc4aa2488 100644 --- a/ldap/servers/slapd/bind.c +++ b/ldap/servers/slapd/bind.c @@ -769,6 +769,7 @@ do_bind( Slapi_PBlock *pb ) } if ( rc == SLAPI_BIND_SUCCESS ) { + int myrc = 0; if (!auto_bind) { /* * There could be a race that bind_target_entry was not added @@ -779,9 +780,9 @@ do_bind( Slapi_PBlock *pb ) if (!bind_target_entry) { bind_target_entry = get_entry(pb, slapi_sdn_get_ndn(sdn)); if (bind_target_entry) { - rc = slapi_check_account_lock(pb, bind_target_entry, + myrc = slapi_check_account_lock(pb, bind_target_entry, pw_response_requested, 1, 1); - if (1 == rc) { /* account is locked */ + if (1 == myrc) { /* account is locked */ goto account_locked; } } else { @@ -795,8 +796,8 @@ do_bind( Slapi_PBlock *pb ) if (!slapi_be_is_flag_set(be, SLAPI_BE_FLAG_REMOTE_DATA)) { /* check if need new password before sending the bind success result */ - rc = need_new_pw(pb, &t, bind_target_entry, pw_response_requested); - switch (rc) { + myrc = need_new_pw(pb, &t, bind_target_entry, pw_response_requested); + switch (myrc) { case 1: (void)slapi_add_pwd_control(pb, LDAP_CONTROL_PWEXPIRED, 0); break; @@ -811,8 +812,8 @@ do_bind( Slapi_PBlock *pb ) if (auth_response_requested) { slapi_add_auth_response_control(pb, slapi_sdn_get_ndn(sdn)); } - if (-1 == rc) { - /* neeed_new_pw failed; need_new_pw already send_ldap_result in it. */ + if (-1 == myrc) { + /* need_new_pw failed; need_new_pw already send_ldap_result in it. */ goto free_and_return; } } else { /* anonymous */
0
3813f7990711780068bf2629345ac2152eb8e119
389ds/389-ds-base
Remove stale libevent(-devel) dependency It appears that the last user of libevent disappeared with 44e92dc8b900 ("Ticket 50669 - remove nunc-stans").
commit 3813f7990711780068bf2629345ac2152eb8e119 Author: Florian Schmaus <[email protected]> Date: Wed Feb 23 11:02:59 2022 +0100 Remove stale libevent(-devel) dependency It appears that the last user of libevent disappeared with 44e92dc8b900 ("Ticket 50669 - remove nunc-stans"). diff --git a/configure.ac b/configure.ac index dca928497..e27edbd4f 100644 --- a/configure.ac +++ b/configure.ac @@ -801,8 +801,6 @@ AM_CONDITIONAL([FREEBSD],[test "$platform" = "freebsd"]) AM_CONDITIONAL([SPARC],[test "x$TARGET" = xSPARC]) # Check for library dependencies -PKG_CHECK_MODULES([EVENT], [libevent]) - if $PKG_CONFIG --exists nspr; then PKG_CHECK_MODULES([NSPR], [nspr]) else diff --git a/docker/389-ds-suse/Dockerfile b/docker/389-ds-suse/Dockerfile index 6022d04c6..4a0bbe00c 100644 --- a/docker/389-ds-suse/Dockerfile +++ b/docker/389-ds-suse/Dockerfile @@ -16,7 +16,7 @@ RUN zypper --non-interactive si --build-deps-only 389-ds && \ # Install build dependencies # RUN zypper in -C -y autoconf automake cracklib-devel cyrus-sasl-devel db-devel doxygen gcc-c++ \ -# gdb krb5-devel libcmocka-devel libevent-devel libtalloc-devel libtevent-devel libtool \ +# gdb krb5-devel libcmocka-devel libtalloc-devel libtevent-devel libtool \ # net-snmp-devel openldap2-devel pam-devel pkgconfig python-rpm-macros "pkgconfig(icu-i18n)" \ # "pkgconfig(icu-uc)" "pkgconfig(libcap)" "pkgconfig(libpcre)" "pkgconfig(libsystemd)" \ # "pkgconfig(nspr)" "pkgconfig(nss)" rsync cargo rust rust-std acl cyrus-sasl-plain db-utils \ diff --git a/rpm/389-ds-base.spec.in b/rpm/389-ds-base.spec.in index 857a20f08..e16323d32 100644 --- a/rpm/389-ds-base.spec.in +++ b/rpm/389-ds-base.spec.in @@ -220,7 +220,6 @@ BuildRequires: libtool BuildRequires: doxygen # For tests! BuildRequires: libcmocka-devel -BuildRequires: libevent-devel # For lib389 and related components. BuildRequires: python%{python3_pkgversion} BuildRequires: python%{python3_pkgversion}-devel @@ -316,7 +315,6 @@ Conflicts: svrcore Requires: nss >= 3.34 Requires: nspr Requires: openldap -Requires: libevent Requires: systemd-libs # Pull in sasl Requires: cyrus-sasl-lib
0
091a5f5daf3fa378f029e293c5358ae9be9f548e
389ds/389-ds-base
Ticket #48536 - Crash in slapi_get_object_extension Description: The crashed was caused by the combination of psearch and updating one of these group values: groupOfNames, groupOfUniqueNames, groupOfCertificates, groupOfURL. In the psearch, it creates aclpb in the acl plug-in and sets the original pblock address in the aclpb. Then, psearch creates a copy of the pblock and sets it in the psearch structure. Now, the pblock address in aclpb and the pblock address in the psearch structure do not match. The original pblock itself is freed and the pblock area which address is stored in aclpb is not guaranteed what is in it. If nothing occurs, the freed pblock in aclpb is not accessed. But once one of the group values is updated, the acl plug-in signature is updated and it triggers to get aclpb from the pblock. The acl_get_aclpb call accesses the freed pblock (e.g., NULL op) and it crashes the server. This patch checks the current pblock address and the pblock address in aclpb. If they don't match, the address in aclpb is reassigned to the current pblock address. https://fedorahosted.org/389/ticket/48536 Reviewed by [email protected] (Thank you, Mark!!)
commit 091a5f5daf3fa378f029e293c5358ae9be9f548e Author: Noriko Hosoi <[email protected]> Date: Tue Feb 9 16:12:07 2016 -0800 Ticket #48536 - Crash in slapi_get_object_extension Description: The crashed was caused by the combination of psearch and updating one of these group values: groupOfNames, groupOfUniqueNames, groupOfCertificates, groupOfURL. In the psearch, it creates aclpb in the acl plug-in and sets the original pblock address in the aclpb. Then, psearch creates a copy of the pblock and sets it in the psearch structure. Now, the pblock address in aclpb and the pblock address in the psearch structure do not match. The original pblock itself is freed and the pblock area which address is stored in aclpb is not guaranteed what is in it. If nothing occurs, the freed pblock in aclpb is not accessed. But once one of the group values is updated, the acl plug-in signature is updated and it triggers to get aclpb from the pblock. The acl_get_aclpb call accesses the freed pblock (e.g., NULL op) and it crashes the server. This patch checks the current pblock address and the pblock address in aclpb. If they don't match, the address in aclpb is reassigned to the current pblock address. https://fedorahosted.org/389/ticket/48536 Reviewed by [email protected] (Thank you, Mark!!) diff --git a/ldap/servers/plugins/acl/acl.c b/ldap/servers/plugins/acl/acl.c index 678a999e6..d56bed6ce 100644 --- a/ldap/servers/plugins/acl/acl.c +++ b/ldap/servers/plugins/acl/acl.c @@ -317,6 +317,13 @@ acl_access_allowed( goto cleanup_and_ret; } + if (pb != aclpb->aclpb_pblock) { + slapi_log_error(SLAPI_LOG_FATAL, plugin_name, + "acl_access_allowed: Resetting aclpb_pblock 0x%x to pblock addr 0x%x\n", + aclpb->aclpb_pblock, pb); + aclpb->aclpb_pblock = pb; + } + if ( !aclpb->aclpb_curr_entry_sdn ) { slapi_log_error ( SLAPI_LOG_FATAL, plugin_name, "NULL aclpb_curr_entry_sdn \n" ); ret_val = LDAP_OPERATIONS_ERROR; @@ -932,6 +939,13 @@ acl_read_access_allowed_on_entry ( tnf_string,end,"aclpb error"); return LDAP_OPERATIONS_ERROR; } + + if (pb != aclpb->aclpb_pblock) { + slapi_log_error(SLAPI_LOG_ACL, plugin_name, + "acl_read_access_allowed_on_entry: Resetting aclpb_pblock 0x%x to pblock addr 0x%x\n", + aclpb->aclpb_pblock, pb); + aclpb->aclpb_pblock = pb; + } /* * Am I a anonymous dude ? then we can use our anonympous profile
0
c482e15aa9d014284cecddedc6e2fd52a65a24ec
389ds/389-ds-base
correction to fix for #50417 Bug: The patch for 50417 did break start-dirsrv and stop-dirsrv. Some paths were not correctly set Fix: use path variable like in other legacy scripts, eg @sbindir@ Reviewed by: Mark, thanks
commit c482e15aa9d014284cecddedc6e2fd52a65a24ec Author: Ludwig Krispenz <[email protected]> Date: Thu Jul 18 09:16:13 2019 +0200 correction to fix for #50417 Bug: The patch for 50417 did break start-dirsrv and stop-dirsrv. Some paths were not correctly set Fix: use path variable like in other legacy scripts, eg @sbindir@ Reviewed by: Mark, thanks diff --git a/ldap/admin/src/scripts/start-dirsrv.in b/ldap/admin/src/scripts/start-dirsrv.in index a6d63d375..c1ed5f7b2 100755 --- a/ldap/admin/src/scripts/start-dirsrv.in +++ b/ldap/admin/src/scripts/start-dirsrv.in @@ -44,7 +44,7 @@ start_instance() { instance=`get_slapd_instance @instconfigdir@ $SERV_ID` || { echo Instance $SERV_ID not found. ; return 1 ; } CONFIG_DIR="@instconfigdir@/slapd-$instance"; - PIDFILE=$RUN_DIR/slapd-$SERV_ID.pid + PIDFILE=@localstatedir@$RUN_DIR/slapd-$SERV_ID.pid if test -f $PIDFILE ; then PID=`cat $PIDFILE` @@ -58,12 +58,12 @@ start_instance() { if test 1 -eq @enable_asan@; then echo "NOTICE: Starting instance ${SERV_ID} with ASAN options." echo "This is probably not what you want. Please contact support." - : ${ASAN_LOG_PATH:=$RUN_DIR/ns-slapd-${SERV_ID}.asan} + : ${ASAN_LOG_PATH:=@localstatedir@$RUN_DIR/ns-slapd-${SERV_ID}.asan} echo "Asan errors will go to ${ASAN_LOG_PATH}*" export ASAN_OPTIONS="detect_leaks=1 symbolize=1 detect_deadlocks=1 log_path=${ASAN_LOG_PATH}" export ASAN_SYMBOLIZER_PATH=/usr/bin/llvm-symbolizer fi - $SERVERBIN_DIR/ns-slapd -D $CONFIG_DIR -i $PIDFILE "$@" + @sbindir@/ns-slapd -D $CONFIG_DIR -i $PIDFILE "$@" if [ $? -ne 0 ]; then return 1 fi diff --git a/ldap/admin/src/scripts/stop-dirsrv.in b/ldap/admin/src/scripts/stop-dirsrv.in index 755cd8b8b..7c2503438 100755 --- a/ldap/admin/src/scripts/stop-dirsrv.in +++ b/ldap/admin/src/scripts/stop-dirsrv.in @@ -13,7 +13,7 @@ RUN_DIR="@localrundir@/@PACKAGE_NAME@"; stop_instance() { SERV_ID=$1 - PIDFILE=$RUN_DIR/slapd-$SERV_ID.pid + PIDFILE=@localstatedir@$RUN_DIR/slapd-$SERV_ID.pid if test ! -f $PIDFILE ; then echo No ns-slapd PID file found. Server is probably not running return 2
0
b2e2a3f5294707e1ccf2b25fd281ce3653dac819
389ds/389-ds-base
Allow dirsrv_t to log to a fifo in SELinux policy. This patch changes the SELinux dirsrv policy to allow ns-slapd to log to a fifo file. Author: nkinder (Thanks!) Tested on RHEL5 i386
commit b2e2a3f5294707e1ccf2b25fd281ce3653dac819 Author: Nathan Kinder <[email protected]> Date: Mon Nov 23 09:48:50 2009 -0800 Allow dirsrv_t to log to a fifo in SELinux policy. This patch changes the SELinux dirsrv policy to allow ns-slapd to log to a fifo file. Author: nkinder (Thanks!) Tested on RHEL5 i386 diff --git a/selinux/dirsrv.if b/selinux/dirsrv.if index 80b478f18..b8e1a7f99 100644 --- a/selinux/dirsrv.if +++ b/selinux/dirsrv.if @@ -77,6 +77,7 @@ interface(`dirsrv_manage_log',` allow $1 dirsrv_var_log_t:dir manage_dir_perms; allow $1 dirsrv_var_log_t:file manage_file_perms; + allow $1 dirsrv_var_log_t:fifo_file: manage_fifo_file_perms; ') ####################################### diff --git a/selinux/dirsrv.te b/selinux/dirsrv.te index 60901f284..ef09fb296 100644 --- a/selinux/dirsrv.te +++ b/selinux/dirsrv.te @@ -105,6 +105,7 @@ files_var_lib_filetrans(dirsrv_t,dirsrv_var_lib_t, { file dir sock_file }) # log files manage_files_pattern(dirsrv_t, dirsrv_var_log_t, dirsrv_var_log_t) +manage_fifo_files_pattern(dirsrv_t, dirsrv_var_log_t, dirsrv_var_log_t) allow dirsrv_t dirsrv_var_log_t:dir { setattr }; logging_log_filetrans(dirsrv_t,dirsrv_var_log_t,{ sock_file file dir })
0