summaryrefslogtreecommitdiffstats
path: root/ldap/admin/src/scripts/FileConn.pm
blob: f1ac4d2d686214ea484ca2afcf44132aa16b7fd4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
# 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) 2007 Red Hat, Inc.
# All rights reserved.
# END COPYRIGHT BLOCK
#
# FileConn is a subclass of Mozilla::LDAP::Conn.  This class does
# not use LDAP.  Instead, it operates on a given LDAP file, allowing
# you to search, add, modify, and delete entries in the file.
#
package FileConn;

use Mozilla::LDAP::Conn;
use Mozilla::LDAP::API qw(:constant ldap_explode_dn ldap_err2string); # Direct access to C API
use Mozilla::LDAP::Utils qw(normalizeDN);
use Mozilla::LDAP::LDIF;

use Carp;

require    Exporter;
@ISA       = qw(Exporter Mozilla::LDAP::Conn);
@EXPORT    = qw();
@EXPORT_OK = qw();

sub new {
    my $class = shift;
    my $filename = shift;
    my $readonly = shift;
    my @namingContexts = @_;
    my $self = {};

    $self = bless $self, $class;

    $self->{readonly} = $readonly;
    for (@namingContexts) {
        $self->setNamingContext($_);
    }
    $self->setNamingContext(""); # root DSE
    if (!$self->read($filename)) {
        return;
    }

    return $self;
}

sub getParentDN {
    my $dn = shift;
    my @rdns = ldap_explode_dn($dn, 0);
    shift @rdns;
    return join(',', @rdns);
}

sub read {
    my $self = shift;
    my $filename = shift;

    if ($filename) {
        $self->{filename} = $filename;
    } else {
        $filename = $self->{filename};
    }

    if (!$self->{filename}) {
        return 1; # no filename given - ok
    }

    if (!open( MYLDIF, "$filename" )) {
        confess "Can't open $filename: $!";
        return 0;
    }

    my $in = new Mozilla::LDAP::LDIF(*MYLDIF);
    $self->{reading} = 1;
    while ($ent = readOneEntry $in) {
        if (!$self->add($ent)) {
            confess "Error: could not add entry ", $ent->getDN(), ":", $self->getErrorString();
        }
    }
    delete $self->{reading};
    close( MYLDIF );

    return 1;
}

sub setNamingContext {
    my $self = shift;
    my $nc = shift;
    my $ndn = normalizeDN($nc);
    $self->{namingContexts}->{$ndn} = $ndn;
}

sub isNamingContext {
    my $self = shift;
    my $ndn = shift;
    return exists($self->{namingContexts}->{$ndn});
}

# return all nodes below the given node
sub iterate {
    my $self = shift;
    my $dn = shift;
    my $scope = shift;
    my $callback = shift;
    my $context = shift;
    my $suppress = shift;
    my $ndn = normalizeDN($dn);
    my $children;
    if (exists($self->{$ndn}) and exists($self->{$ndn}->{children})) {
        $children = $self->{$ndn}->{children};
    }
    if (($scope != LDAP_SCOPE_ONELEVEL) && exists($self->{$ndn}) &&
        exists($self->{$ndn}->{data}) && $self->{$ndn}->{data} && !$suppress) {
        &{$callback}($self->{$ndn}->{data}, $context);
    }

    if ($scope == LDAP_SCOPE_BASE) {
        return;
    }

    for my $node (@{$children}) {
        &{$callback}($node->{data}, $context);
    }
    if ($scope == LDAP_SCOPE_SUBTREE) {
        for my $node (@{$children}) {
            $self->iterate($node->{data}->getDN(), $scope, $callback, $context, 1);
        }
    }
}

sub writecb {
    my $entry = shift;
    my $fh = shift;
    if (! $entry->getDN()) { # rootDSE requires special hack around perldap bug
        my $ary = $entry->getLDIFrecords();
        shift @$ary; # remove "dn"
        shift @$ary; # remove the empty dn value
        print $fh "dn:\n";
        print $fh (Mozilla::LDAP::LDIF::pack_LDIF (78, $ary), "\n");
    } else {
        Mozilla::LDAP::LDIF::put_LDIF($fh, 78, $entry);
    }
}

sub write {
    my $self = shift;
    my $filename = shift;

    if ($filename) {
        $self->{filename} = $filename;
    } else {
        $filename = $self->{filename};
    }

    if (!$self->{filename} or $self->{readonly} or $self->{reading}) {
        return 1; # ok - no filename given - just ignore
    }

    if (!open( MYLDIF, ">$filename" )) {
        confess "Can't write $filename: $!";
        return 0;
    }

    $self->iterate("", LDAP_SCOPE_SUBTREE, \&writecb, \*MYLDIF);
    for (keys %{$self->{namingContexts}}) {
        next if (!$_); # skip "" - we already did that
        $self->iterate($_, LDAP_SCOPE_SUBTREE, \&writecb, \*MYLDIF);
    }
    close( MYLDIF );

    return 1;
}

sub setErrorCode {
    my $self = shift;
    $self->{lastErrorCode} = shift;
}

sub getErrorCode {
    my $self = shift;
    return $self->{lastErrorCode};
}

sub getErrorString {
    my $self = shift;
    return ($self->{lastErrorCode} ? ldap_err2string($self->{lastErrorCode}) : LDAP_SUCCESS);
}

#############################################################################
# Print the last error code...
#
sub printError
{
  my ($self, $str) = @_;

  $str = "LDAP error:" unless defined($str);
  print "$str ", $self->getErrorString(), "\n";
}

sub DESTROY {
    my $self = shift;
    $self->close();
}

sub close {
    my $self = shift;
    return if ($self->{readonly});
    $self->write();
}

sub printcb {
    my $entry = shift;

    print $entry->getDN(), "\n";
}

sub print {
    my $self = shift;
    my $dn = shift;
    my $scope = shift;
    $self->iterate($dn, $scope, \&printcb);
}

# for each entry, call the user provided filter callback
# with the entry and the user provided filter context
# if the filtercb returns true, add the entry to the
# list of entries to return
sub searchcb {
    my $entry = shift;
    my $context = shift;
    my $self = $context->[0];
    my $filtercb = $context->[1];
    my $filtercontext = $context->[2];
    if (&{$filtercb}($entry, $filtercontext)) {
        push @{$self->{entries}}, $entry;
    }
}

sub matchall {
    return 1;
}

sub matchAttrVal {
    my $entry = shift;
    my $context = shift;
    my $attr = $context->[0];
    my $val = $context->[1];

    if ($val eq "*") {
        return $entry->exists($attr);
    }
    return $entry->hasValue($attr, $val, 1);
}   

my $attrpat  = '[-;.:\w]*[-;\w]';

# given a string filter, figure out which subroutine to 
# use to match
sub filterToMatchSub {
    my $self = shift;
    my ($basedn, $scope, $filter, $attrsonly, @rest) = @_;
    my ($matchsub, $context);
# do some filter processing
    if (!$filter or ($filter eq "(objectclass=*)") or
        ($filter eq "objectclass=*")) {
        $matchsub = \&matchall;
    } elsif ($filter =~ /^\(($attrpat)=(.+)\)$/o) {
        push @{$context}, $1, $2;
        $matchsub = \&matchAttrVal;
#     } elsif ($filter =~ /^\(\|\(($attrpat)=(.+)\)\(($attrpat)=(.+)\)\)$/o) {
#         $attr = $1;
#         $val = $2;
#         $attr1 = $1;
#         $val1 = $2;
#         $isand = 0;
#     } elsif ($filter =~ /^\(\&\(($attrpat)=(.+)\)\(($attrpat)=(.+)\)\)$/o) {
#         $attr = $1;
#         $val = $2;
#         $attr1 = $1;
#         $val1 = $2;
#         $isand = 1;
#     } elsif ($filter =~ /^\(\|\(($attrpat)=(.+)\)\(($attrpat)=(.+)\)\)$/o) {) {
# # 						   "(&(objectclass=nsBackendInstance)(|(nsslapd-suffix=$suffix)(nsslapd-suffix=$nsuffix)))");
    }

    $self->iterate($basedn, $scope, \&searchcb, [$self, $matchsub, $context]);
}

# simple searches only
sub search {
    my $self = shift;
    my ($basedn, $scope, $filter, $attrsonly, @rest) = @_;
    my $attrs;
    if (ref($rest[0]) eq "ARRAY") {
        $attrs = $rest[0];
    } elsif (scalar(@rest) > 0) {
        $attrs = \@rest;
    }

    $scope = Mozilla::LDAP::Utils::str2Scope($scope);

    $self->{entries} = [];

    my $ndn = normalizeDN($basedn);
    if (!exists($self->{$ndn}) or !exists($self->{$ndn}->{data})) {
        $self->setErrorCode(LDAP_NO_SUCH_OBJECT);
        return undef;
    }

    $self->setErrorCode(0);
    if (ref($filter) eq 'CODE') {
        $self->iterate($basedn, $scope, \&searchcb, [$self, $filter, $attrsonly]);
    } else {
        $self->filterToMatchSub($basedn, $scope, $filter, $attrsonly);
    }

    return $self->nextEntry();
}

sub cloneEntry {
    my $src = shift;
    if (!$src) {
        return undef;
    }
    my $dest = new Mozilla::LDAP::Entry();
    $dest->setDN($src->getDN());
    for (keys %{$src}) {
        if (ref($src->{$_})) {
            my @copyary = @{$src->{$_}};
            $dest->{$_} = [ @copyary ]; # make a deep copy
        } else {
            $dest->{$_} = $src->{$_};
        }
    }

    return $dest;
}

# have to return a copy of the entry - disallow inplace updates
sub nextEntry {
    my $self = shift;
    my $ent = shift @{$self->{entries}};
    return cloneEntry($ent);
}

sub add {
    my $self = shift;
    my $entry = shift;
    my $dn = $entry->getDN();
    my $ndn = normalizeDN($dn);
    my $parentdn = getParentDN($dn);
    my $nparentdn = normalizeDN($parentdn);

    $self->setErrorCode(0);
    # special case of naming context - has no parent
    if ($self->isNamingContext($ndn) and
        !exists($self->{$ndn}->{data})) {
        $self->{$ndn}->{data} = $entry;
        return $self->write();
    }

    if (exists($self->{$ndn})) {
        $self->setErrorCode(LDAP_ALREADY_EXISTS);
        return 0;
    }

    if ($ndn && $nparentdn && !exists($self->{$nparentdn})) {
        $self->setErrorCode(LDAP_NO_SUCH_OBJECT);
        return 0;
    }
    # each hash entry has two keys
    # data is the actual Entry
    # children is the array ref of the one level children of this dn
    $self->{$ndn}->{data} = $entry;
    # don't add parent to list of children
    if ($nparentdn ne $ndn) {
        push @{$self->{$nparentdn}->{children}}, $self->{$ndn};
    }

    return 1;
}

sub update {
    my $self = shift;
    my $entry = shift;
    my $dn = $entry->getDN();
    my $ndn = normalizeDN($dn);

    confess "Attempt to modify read only $self->{filename} entry $dn" if ($self->{readonly});

    $self->setErrorCode(0);
    if (!exists($self->{$ndn})) {
        $self->setErrorCode(LDAP_NO_SUCH_OBJECT);
        return 0;
    }

    # The cloned entry will not contain the deleted attrs - the cloning
    # process omits the deleted attrs via the Entry FETCH, FIRSTKEY, and NEXTKEY
    # methods
    $self->{$ndn}->{data} = cloneEntry($entry);
    return $self->write();
}

sub delete {
    my $self = shift;
    my $dn = shift;

    confess "Attempt to modify read only $self->{filename} entry $dn" if ($self->{readonly});

    if (ref($dn)) {
        $dn = $dn->getDN(); # an Entry
    }
    my $ndn = normalizeDN($dn);

    $self->setErrorCode(0);
    if (!exists($self->{$ndn})) {
        $self->setErrorCode(LDAP_NO_SUCH_OBJECT);
        return 0;
    }

    if (@{$self->{$ndn}->{children}}) {
        $self->setErrorCode(LDAP_NOT_ALLOWED_ON_NONLEAF);
        return 0;
    }

    # delete the data associated with this node
    delete $self->{$ndn}->{data};
    delete $self->{$ndn}->{children};

    my $parentdn = getParentDN($dn);
    my $nparentdn = normalizeDN($parentdn);
    # delete this node from its parent
    if ($ndn ne $nparentdn) {
        for (my $ii = 0; $ii < @{$self->{$nparentdn}->{children}}; ++$ii) {
            # find matching hash ref in parent's child list
            if ($self->{$nparentdn}->{children}->[$ii] eq $self->{$ndn}) {
                # remove that element from the array
                splice @{$self->{$nparentdn}->{children}}, $ii, 1;
                # done - should only ever be one matching child
                last;
            }
        }
    }

    # delete this node
    delete $self->{$ndn};

    return $self->write();
}

1;