-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathNDSAdminNL.pm
2307 lines (2090 loc) · 71 KB
/
NDSAdminNL.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package NDSAdminNL;
use Socket;
use Sys::Hostname;
use IPC::Open2;
use Symbol;
use URI::Escape;
use MIME::Base64;
use Cwd;
use File::Basename;
use Net::LDAP;
use Net::LDAP::Util qw(canonical_dn ldap_explode_dn ldap_error_name);
use Net::LDAP::Constant qw(:all);
require Exporter;
@ISA = qw(Exporter Net::LDAP);
@EXPORT = qw(getFQDN getdomainname createAndSetupReplica replicaSetupAll
createInstance defaultadmindomain defaultsuffix printRUV
parseCSNs compareCSNs compareRUVs $MASTER_TYPE $HUB_TYPE $LEAF_TYPE
parseCSN getTSDiff printTSDiff removeOtherInstance
check_mesg my_ldap_explode_dn normalizeDN my_ldap_url_parse);
my $isNT = -d '\\';
my $REPLBINDDN;
my $REPLBINDCN;
my $REPLBINDPW;
sub hex_unescape {
my $s = shift;
$s =~ s/%([A-Fa-f0-9]{2})/chr(hex($1))/eg; # unescape
return $s;
}
sub my_ldap_url_parse {
my $url = shift;
my $href = {};
if ($url =~ m|^(ldap.?)://([^/]+)/([^\?]+)?\?([^\?]+)?\?([^\?]+)?\?([^\?]+)?|) {
$href->{meth} = $1;
# $2 includes port, if present
$href->{host} = hex_unescape($2);
# $href->{port} = $3;
$href->{dn} = hex_unescape($3);
$href->{attr} = hex_unescape($4);
$href->{scope} = hex_unescape($5);
$href->{filter} = hex_unescape($6);
} else {
print "invalid url : $url\n";
return $href;
}
if ($href->{host} =~ /:(\d+)$/) {
$href->{host} = $`;
$href->{port} = $1;
}
if ($href->{attr}) { # convert to array
my @ary = split(/,/, $href->{attr});
$href->{attr} = \@ary;
}
return $href;
}
sub normalizeDN {
my $dn = shift;
return lc(canonical_dn($dn, casefold => 'lower'));
}
# if args is 1, return an array of values, no attribute name or '='
sub my_ldap_explode_dn {
my ($dn, $valuesOnly) = @_;
my $ary = ldap_explode_dn($dn, casefold => 'none');
my @rdns;
while (@$ary) {
my $href = shift @$ary;
while (my ($key, $val) = each %$href) {
if ($valuesOnly) {
push @rdns, $val;
} else {
push @rdns, $key . '=' . $val;
}
}
}
return @rdns;
}
sub getFQDN {
# return fully qualified host and domain name
# ex : hippo.example.com
# if the hostname from hostname() is not FQDN, find the first alias
# which matches the hostname which is also FQDN e.g.
# if given hippo, the $name might be realhost.example.com, but one of the aliases
# may be hippo.example.com - prefer the latter over the former since it matches
# the hostname
my $hostname = shift;
my $hrefalias = shift;
return 'localhost' if (!$hostname && $ENV{LOCALHOSTFORHOSTNAME});
return 'localhost' if ($hostname eq 'localhost' && $ENV{LOCALHOSTFORHOSTNAME});
my $fqdn;
if ($isNT) { # gethostbyname on NT messes up ldap_simple_bind_s
$hostname = $hostname || `hostname`; # hostname on NT does not give FQDN
} else {
$hostname = $hostname || hostname();
# find the alias that most closely matches the hostname
my ($name, $aliases, @rest) = gethostbyname($hostname);
if ($aliases) {
my @alias = split(/\s+/, $aliases);
my $max = 1; # must have at least 1 domain component
for (@alias) {
$hrefalias->{$_} = $_ if ($hrefalias);
my $n = tr/\./\./; # count dots in name
if (($n >= $max) && /^$hostname/) {
$max = $n;
$fqdn = $_;
}
}
}
}
if (!$fqdn) {
if (open(NSLOOKUP, "nslookup $hostname|")) {
my $name;
sleep 1; # allow pipe to fill with data
while (<NSLOOKUP>) {
chop;
# use aliases if available, and the alias is an FQDN, and the
# the alias is a close match to our hostname
if (/^Aliases:\s*/) {
my $alias = $';
$hrefalias->{$alias} = $alias if ($hrefalias);
if ($alias =~ /\./ && $alias =~ /^$hostname/) {
$fqdn = $alias;
last;
}
}
# if no alias, just use the name
if (/^Name:\s*/) {
$name = $';
$hrefalias->{$name} = $name if ($hrefalias);
}
}
close NSLOOKUP;
if (!$fqdn && $name) {
$fqdn = $name;
}
}
}
# if we could not find a match, return the hostname if it contains
# domain components or return the $name
if (!$fqdn) {
if ($hostname =~ /\./) { # perhaps the hostname is already fqdn
$fqdn = $hostname;
} elsif ($name =~ /\./) { # try the canonical name
$fqdn = $name;
} elsif (my $dmn = `domainname`) { # append the domain name
$fqdn = $hostname.$dmn;
} else { # punt
$fqdn = $hostname;
}
}
return $fqdn;
}
sub getdomainname {
my $h = getFQDN(shift);
# if $h begins with word. ...
if ($h =~ /^.+?\./) {
# ... return everything after word.
return $'; # ' fix comment
}
return "";
}
sub defaultadmindomain {
return (getdomainname(shift) || "example.com");
}
sub defaultsuffix {
my $dm = getdomainname(shift);
return "dc=example, dc=com" if (! $dm);
my @dc = split(/\./, $dm);
map { $_ = "dc=$_" } @dc;
return join(',', @dc);
}
#########################################
# OVERRIDE methods go here ##############
#########################################
sub rebindProc {
print "In rebind proc, args = @_\n" if ($verbose);
return ($main::binddn, $main::bindpw, LDAP_AUTH_SIMPLE);
}
# returns the rebind proc subroutine
sub genRebindProc {
my ($dn, $pwd, $auth, $verbose) = @_;
$auth = LDAP_AUTH_SIMPLE if (!$auth);
return sub {
print "In rebind proc, args = @_\n" if ($verbose);
return ($dn, $pwd, $auth);
};
}
sub toString {
my $self = shift;
return $self->{host} . ":" . $self->{port};
}
sub toLDAPURL {
my $self = shift;
return "ldap://" . $self->{host} . ":" . $self->{port} . "/";
}
# mesg is the Net::LDAP::Message returned from the api call
# text is a string to print with the error message
# ignore is a hash - the keys are ldap error codes to ignore
sub check_mesg {
my ($mesg, $txt, $ignore) = @_;
my $code = $mesg->code;
# if ($ignore) {
# foreach my $val (keys %$ignore) {
# print "ignoring code $val\n";
# }
# print "returned code = $code\n";
# }
if (($code != LDAP_SUCCESS) && (!$ignore || !$ignore->{ldap_error_name($code)})) {
my ($pkg, $file, $line) = caller;
die $txt . ": code " . $code . " error [" . $mesg->error() . "] at $pkg:$file:$line";
}
return $code;
}
sub init {
my $self = shift;
my $code;
if ($self->{binddn} && $self->{bindpasswd}) {
$mesg = $self->bind($self->{binddn},
password => $self->{bindpasswd},
version => 3);
$code = check_mesg($mesg, "Could not bind to " . $self->toString() . " as " . $self->{binddn},
$self->{ignore});
} else {
$mesg = $self->bind; # anon
$code = check_mesg($mesg, "Could not bind as anonymous", $self->{ignore});
}
return $code;
}
sub new {
my $type = shift;
my $self = Net::LDAP->new(@_);
if (!$self) {
return $self;
}
my $host = shift if @_ % 2;
my %ret = @_;
my $mesg;
$self->{host} = $host;
$self->{port} = $ret{port} || 389;
$self->{binddn} = $ret{binddn};
$self->{bindpasswd} = $ret{bindpasswd};
$self->{ignore} = $ret{ignore};
# see if binddn is a dn or a uid that we need to lookup
if ($self->{binddn} && ($self->{binddn} !~ /\=/)) {
$mesg = $self->bind; # anon
check_mesg($mesg, "Could not anon bind to lookup " . $self->{binddn});
$mesg = $self->search(base => "o=NetscapeRoot",
filter => "(uid=" . $self->{binddn} . ")",
attrs => ['uid']);
check_mesg($mesg, "Could not lookup " . $self->{binddn});
my $cfgent = $mesg->shift_entry;
if ($cfgent) {
$self->{binddn} = $cfgent->dn;
} else {
print "Error: could not find ", $self->{"binddn"}, " under o=NetscapeRoot\n";
}
}
$self = bless $self, $type;
my $code = $self->init;
if ($code == LDAP_SUCCESS) {
$self->initPart2();
}
return $self;
}
# we should do this any time we rebind - the user may have created the initial
# connection as anonymous, then did a rebind as an administrative user, so we
# need to read the information we could not read before
sub initPart2 {
my $self = shift;
# set the other things like the instance name and server root, but not if
# the connection is anonymous
if ($self->{binddn} && length($self->{binddn}) && !$self->{sroot}) {
$mesg = $self->search(base => "cn=config",
scope => 'base',
filter => "(objectclass=*)",
attrs => [ 'nsslapd-instancedir', 'nsslapd-errorlog' ]);
check_mesg($mesg, "Could not read cn=config",
# ignore these errors
{ LDAP_INSUFFICIENT_ACCESS => LDAP_INSUFFICIENT_ACCESS,
LDAP_CONNECT_ERROR => LDAP_CONNECT_ERROR });
my $cfgent = $mesg->shift_entry();
if ($cfgent) {
my $instdir = $cfgent->get_value('nsslapd-instancedir');
if ($instdir =~ m|(.*)[\\/]slapd-(\w+)$|) {
$self->{sroot} = $1;
$self->{inst} = $2;
} else {
print "Error: could not parse instance dir $instdir\n";
}
$self->{errlog} = $cfgent->get_value('nsslapd-errorlog');
if (!$self->{isLocal}) {
# possibly dangerous - many machines could have /usr/netscape/slapd-foo
if (-d $instdir) { # does instance dir exist on this machine?
$self->{isLocal} = 1;
} else {
$self->{isLocal} = 0;
}
}
}
}
}
# this does not check to see if the suffix already has backends, because
# this function can also be used to create multiple backends for entry
# distribution
# call getBackendsForSuffix before calling this function if you need
# to make sure the suffix does not already have backends
# returns the name (the cn) of the backend just created or 0
sub setupBackend {
my ($self, $suffix, $binddn, $bindpw, $urls, $attrvals) = @_;
my $ldbmdn = "cn=ldbm database, cn=plugins, cn=config";
my $chaindn = "cn=chaining database, cn=plugins, cn=config";
my $dnbase;
my $benamebase;
# figure out what type of be based on args
if ($binddn && $bindpw && $urls) { # its a chaining be
$benamebase = "chaindb";
$dnbase = $chaindn;
} else { # its a ldbm be
$benamebase = "localdb";
$dnbase = $ldbmdn;
}
my $nsuffix = normalizeDN($suffix);
my $rc = LDAP_ALREADY_EXISTS;
my $benum = 1;
my $mesg;
while ($rc == LDAP_ALREADY_EXISTS) {
$entry = new Net::LDAP::Entry;
my $cn = $benamebase . $benum; # e.g. localdb1
my $dn = "cn=$cn, $dnbase";
$entry->dn($dn);
$entry->add('objectclass' => ['top', 'extensibleObject', 'nsBackendInstance']);
$entry->add('cn' => $cn);
$entry->add('nsslapd-suffix' => $nsuffix);
if ($binddn && $bindpw && $urls) { # its a chaining be
$entry->add('nsfarmserverurl' => $urls);
$entry->add('nsmultiplexorbinddn' => $binddn);
$entry->add('nsmultiplexorcredentials' => $bindpw);
} else { # set ldbm parameters, if any
# $entry->add('nsslapd-cachesize' => '-1');
# $entry->add('nsslapd-cachememsize' => '2097152');
}
while ($attrvals && (my ($attr, $val) = each %{$attrvals})) { # add more attrs and values
print "adding $attr = $val to entry $dn\n";
$entry->add($attr => $val);
}
$entry->dump;
$mesg = $self->add($entry);
check_mesg($mesg, "Error adding be entry " . $dn,
{LDAP_ALREADY_EXISTS => LDAP_ALREADY_EXISTS});
$rc = $mesg->code();
if ($rc == LDAP_SUCCESS) {
$mesg = $self->search(base => $dn, scope => "base", filter => "(objectclass=*)");
check_mesg($mesg, "Error getting new be entry " . $dn);
$entry = $mesg->shift_entry();
if (! $entry) {
print "Entry $dn was added successfully, but I cannot search it\n";
$rc = -1;
} else {
$entry->dump;
return $cn;
}
} elsif ($rc == LDAP_ALREADY_EXISTS) { # that name exists
$benum++; # increment and try again
}
}
return 0;
}
sub setupSuffix {
my ($self, $suffix, $bename, $parent, $rc) = @_;
my $nsuffix = normalizeDN($suffix);
my $nparent = normalizeDN($parent) if ($parent);
my $dn = "cn=\"$nsuffix\", cn=mapping tree, cn=config";
my $mesg = $self->search(base => "cn=mapping tree, cn=config",
scope => "sub",
filter => "(|(cn=\"$suffix\")(cn=\"$nsuffix\"))");
check_mesg($mesg, "Error searching for parent suffix");
my $entry = $mesg->shift_entry();
if (! $entry) {
$entry = new Net::LDAP::Entry();
$dn = "cn=\"$nsuffix\", cn=mapping tree, cn=config";
$entry->dn($dn);
$entry->add('objectclass' => ['top', 'extensibleObject', 'nsMappingTree']);
$entry->add('cn' => "\"$nsuffix\"");
$entry->add('nsslapd-state' => 'backend');
$entry->add('nsslapd-backend' => $bename);
$entry->add('nsslapd-parent-suffix'=> "\"$nparent\"") if ($parent);
$mesg = $self->add($entry);
check_mesg($mesg, "Error adding new suffix entry $dn");
$mesg = $self->search(base => $dn, scope => "base", filter => "(objectclass=*)");
check_mesg($mesg, "Error getting new suffix entry $dn");
$entry = $mesg->shift_entry;
if (! $entry) {
print "Entry $dn was added successfully, but I cannot search it\n";
$rc = -1;
} else {
$entry->dump;
}
}
return $rc;
}
# given a suffix, return the mapping tree entry for it
sub getMTEntry {
my ($self, $suffix, @attrs) = @_;
my $nsuffix = normalizeDN($suffix);
my $mesg = $self->search(base => "cn=mapping tree,cn=config",
scope => "one",
filter => "(|(cn=\"$suffix\")(cn=\"$nsuffix\"))",
attrs => [@attrs]);
check_mesg($mesg, "Error searching for mapping tree entry for $suffix");
return $mesg->shift_entry;
}
# given a suffix, return a list of backend entries for that suffix
sub getBackendsForSuffix {
my ($self, $suffix, @attrs) = @_;
my $nsuffix = normalizeDN($suffix);
my $mesg;
$mesg = $self->search(base => "cn=plugins,cn=config",
scope => "sub",
filter => "(&(objectclass=nsBackendInstance)(|(nsslapd-suffix=$suffix)(nsslapd-suffix=$nsuffix)))",
attrs => [@attrs]);
check_mesg($mesg, "Error searching for backends for suffix " . $nsuffix);
return $mesg->entries();
}
# given a backend name, return the mapping tree entry for it
sub getSuffixForBackend {
my ($self, $bename, @attrs) = @_;
my $mesg = $self->search(base => "cn=plugins,cn=config",
scope => "sub",
filter => "(&(objectclass=nsBackendInstance)(cn=$_))",
attrs => ['nsslapd-suffix']);
check_mesg($mesg, "Error searching for be entry for $_");
my $beent = $mesg->shift_entry;
if ($beent) {
my $suffix = $beent->get_value('nsslapd-suffix');
return $self->getMTEntry($suffix, @attrs);
}
return 0;
}
sub addSuffix {
my ($self, $suffix, $binddn, $bindpw, @urls) = @_;
my @beents = $self->getBackendsForSuffix($suffix, qw(cn));
my $bename;
my @benames;
# no backends for this suffix yet - create one
if (!@beents) {
if (!($bename = $self->setupBackend($suffix, $binddn, $bindpw, \@urls))) {
print "Couldn't create backend for $suffix\n";
return -1; # ldap error code handled already
}
} else { # use existing backend(s)
for (@beents) {
push @benames, $_->get_value('cn');
}
$bename = shift @benames;
}
my $parent = $self->findParentSuffix($suffix);
if (my $rc = $self->setupSuffix($suffix, $bename, $parent)) {
print "Couldn't create suffix for $bename $suffix " . $self->getErrorString(), "\n";
}
return $rc;
}
# specify the suffix (should contain 1 local database backend),
# the name of the attribute to index, and the types of indexes
# to create e.g. "pres", "eq", "sub"
sub addIndex {
my ($self, $suffix, $attr, @indexTypes) = @_;
my @beents = $self->getBackendsForSuffix($suffix, qw(cn));
# assume 1 local backend
my $dn = "cn=$attr,cn=index," . $beents[0]->dn;
my $entry = new Net::LDAP::Entry();
$entry->dn($dn);
$entry->add('objectclass' => ['top', 'nsIndex']);
$entry->add('cn' => $attr);
$entry->add('nsSystemIndex' => "false");
$entry->add('nsIndexType', \@indexTypes);
my $mesg = $self->add($entry);
check_mesg($mesg, "Error adding index entry $dn",
{LDAP_ALREADY_EXISTS => LDAP_ALREADY_EXISTS});
}
sub requireIndex {
my ($self, $suffix) = @_;
my @beents = $self->getBackendsForSuffix($suffix, qw(cn));
# assume 1 local backend
my $dn = $beents[0]->dn;
my $mesg = $self->modify($dn, replace => {'nsslapd-require-index' => 'on'});
check_mesg($mesg, "Error making index required for $dn");
}
sub startTaskAndWait {
my ($self, $entry, $verbose) = @_;
my $dn = $entry->dn;
# start the task
my $mesg = $self->add($entry);
check_mesg($mesg, "Error adding task entry $dn");
$mesg = $self->search(base => $dn, scope => "base", filter => "(objectclass=*)");
check_mesg($mesg, "Error searching for task entry $dn");
$entry = $mesg->shift_entry;
if (! $entry) {
print "Entry $dn was added successfully, but I cannot search it\n" if ($verbose);
return -1;
} elsif ($verbose) {
$entry->dump;
}
# wait for task completion - task is complete when the nsTaskExitCode attr is set
my $attrlist = [qw(nsTaskLog nsTaskStatus nsTaskExitCode nsTaskCurrentItem nsTaskTotalItems)];
my $done = 0;
my $exitCode = 0;
while (! $done) {
sleep 1;
$mesg = $self->search(base => $dn, scope => "base",
filter => "(objectclass=*)", attrs => $attrlist);
check_mesg($mesg, "Error checking status of task $dn");
$entry = $mesg->shift_entry;
$entry->dump if ($verbose);
if ($entry->exists('nsTaskExitCode')) {
$exitCode = $entry->get_value('nsTaskExitCode');
$done = 1;
}
}
return $exitCode;
}
sub importLDIF {
my ($self, $file, $suffix, $be, $verbose, $rc) = @_;
my $cn = "import" . time;
my $dn = "cn=$cn, cn=import, cn=tasks, cn=config";
my $entry = new Net::LDAP::Entry();
$entry->dn($dn);
$entry->add('objectclass' => ['top', 'extensibleObject']);
$entry->add('cn' => $cn);
$entry->add('nsFilename' => $file);
if ($be) {
$entry->add('nsInstance' => $be);
} else {
$entry->add('nsIncludeSuffix' => $suffix);
}
$rc = $self->startTaskAndWait($entry, $verbose);
if ($rc) {
print "Error: import task $cn exited with $rc\n" if ($verbose);
} else {
print "Import task $cn completed successfully\n" if ($verbose);
}
return $rc;
}
sub exportLDIF {
my ($self, $file, $suffix, $forrepl, $verbose, $rc) = @_;
my $cn = "export" . time;
my $dn = "cn=$cn, cn=export, cn=tasks, cn=config";
my $entry = new Net::LDAP::Entry();
$entry->dn($dn);
$entry->add('objectclass' => ['top', 'extensibleObject']);
$entry->add('cn' => $cn);
$entry->add('nsFilename' => $file);
$entry->add('nsIncludeSuffix' => $suffix);
$entry->add('nsExportReplica' => "true") if ($forrepl); # create replica init file
$rc = $self->startTaskAndWait($entry, $verbose);
if ($rc) {
print "Error: export task $cn exited with $rc\n" if ($verbose);
} else {
print "Export task $cn completed successfully\n" if ($verbose);
}
return $rc;
}
# use two ways: give conn and full path to archiveDir
# OR
# give conn, server root, and instance dir - a timestamp based archive name will be
# generated and returned
sub backupDB {
my ($self, $archiveDir, $verbose, $rc) = @_;
my $curtime = time;
my $cn = "backup" . $curtime;
my $dn = "cn=$cn, cn=backup, cn=tasks, cn=config";
if (! $archiveDir) { # $archiveDir should not exist yet, so this must be the server root
$archiveDir = "$self->{sroot}/slapd-$self->{inst}/bak/$curtime";
} # also, this only works on the localhost
my $entry = new Net::LDAP::Entry();
$entry->dn($dn);
$entry->add('objectclass' => ['top', 'extensibleObject']);
$entry->add('cn' => $cn);
$entry->add('nsArchiveDir' => $archiveDir);
$rc = $self->startTaskAndWait($entry, $verbose);
if ($rc) {
print "Error: backup task $cn exited with $rc\n" if ($verbose);
return 0;
} else {
print "Backup task $cn completed successfully\n" if ($verbose);
}
return $archiveDir;
}
sub restoreDB {
my ($self, $archiveDir, $verbose, $rc) = @_;
my $curtime = time;
my $cn = "restore" . $curtime;
my $dn = "cn=$cn, cn=restore, cn=tasks, cn=config";
my $entry = new Net::LDAP::Entry();
$entry->dn($dn);
$entry->add('objectclass' => ['top', 'extensibleObject']);
$entry->add('cn' => $cn);
$entry->add('nsArchiveDir' => $archiveDir);
$rc = $self->startTaskAndWait($entry, $verbose);
if ($rc) {
print "Error: restore task $cn exited with $rc\n" if ($verbose);
} else {
print "Restore task $cn completed successfully\n" if ($verbose);
}
return $rc;
}
sub serverCmd {
my ($self, $cmd, $verbose, $timeout) = @_;
my ($sroot, $inst) = ($self->{sroot}, $self->{inst});
my $instanceDir = $sroot . "/slapd-" . $inst;
my $errLog = $instanceDir . "/" . 'logs' . "/" . 'errors';
if ($self->{errlog}) {
$errLog = $self->{errlog};
}
# emulate tail -f
# if the last line we see does not contain "slapd started", try again
my $done = 0;
my $started = 1;
my $code = 0;
my $lastLine = "";
$cmd = lc($cmd);
my $fullCmd = $instanceDir . "/$cmd-slapd";
my $cmdPat = (($cmd eq 'start') ? 'slapd started\.' : 'slapd stopped\.');
$timeout = $timeout?$timeout:120; # default is 120 seconds
$timeout = time + $timeout; # 20 minutes
if ($cmd eq 'stop') {
$self->disconnect();
}
open(IN, $errLog) or print "Could not open error log $errLog: $!\n", return -1;
seek IN, 0, 2; # go to eof
my $pos = tell(IN);
# . . . reset the EOF status of the file desc
seek(IN, $pos, 0);
$code = system($fullCmd);
while (($done == 0) && (time < $timeout)) {
for (; ($done == 0) && ($_ = <IN>); $pos = tell(IN)) {
$lastLine = $_;
print if ($verbose);
# the server has already been started and shutdown once . . .
if (/$cmdPat/) {
$started++;
if ($started == 2) {
$done = 1;
}
# sometimes the server will fail to come up; in that case, restart it
} elsif (/Initialization Failed/) {
# print "Server failed to start: $_";
$code = system($fullCmd);
# sometimes the server will fail to come up; in that case, restart it
} elsif (/exiting\./) {
# print "Server failed to start: $_";
#$code = &mySystem($fullCmd);
$code = system($fullCmd);
}
}
if ($lastLine =~ /PR_Bind/) {
# server port conflicts with another one, just report and punt
print $lastLine;
print "This server cannot be started until the other server on this\n";
print "port is shutdown.\n";
$done = 1;
}
if ($done == 0) {
# rest a bit, then . . .
sleep(2);
# . . . reset the EOF status of the file desc
seek(IN, $pos, 0);
}
}
close(IN);
if ($started < 2) {
$! = $code;
$now = time;
if ($now > $timeout) {
print "Possible timeout: timeout=$timeout now=$now\n";
}
print "Error: could not $cmd server $sroot $inst: $!" if ($verbose);
return 1;
} else {
print "$cmd was successful for $sroot $inst\n" if ($verbose);
if ($cmd eq 'start') {
$self->init();
}
}
return 0;
}
sub start {
my ($self, $verbose, $timeout) = @_;
if (!$self->{isLocal} && $self->{asport}) {
my %cgiargs = ( 'dummy' => 'dummy' );
print "starting remote server ", $self->toString(), "\n" if ($verbose);
my $rc = &cgiPost($self->{host}, $self->{asport}, $self->{cfgdsuser},
$self->{cfgdspwd},
"/slapd-$self->{inst}/Tasks/Operation/start",
$verbose, \%cgiargs);
print "connecting remote server ", $self->toString(), "\n" if ($verbose);
$self->init() if (!$rc);
print "started remote server ", $self->toString(), " rc = $rc\n" if ($verbose);
return $rc;
} else {
return $self->serverCmd('start', $verbose, $timeout);
}
}
sub stop {
my ($self, $verbose, $timeout) = @_;
if (!$self->{isLocal} && $self->{asport}) {
print "stopping remote server ", $self->toString(), "\n" if ($verbose);
$self->disconnect();
print "closed remote server ", $self->toString(), "\n" if ($verbose);
my %cgiargs = ( 'dummy' => 'dummy' );
my $rc = &cgiPost($self->{host}, $self->{asport}, $self->{cfgdsuser},
$self->{cfgdspwd},
"/slapd-$self->{inst}/Tasks/Operation/stop",
$verbose, \%cgiargs);
print "stopped remote server ", $self->toString(), " rc = $rc\n" if ($verbose);
return $rc;
} else {
return $self->serverCmd('stop', $verbose, $timeout);
}
}
sub addSchema {
my ($self, $attr, $val) = @_;
my $dn = "cn=schema";
my $mesg = $self->modify($dn, add => {$attr => $val});
check_mesg($mesg, "Could not add $attr $val to schema");
return 0;
}
sub addAttr {
my $self = shift;
return $self->addSchema('attributeTypes', @_);
}
sub addObjClass {
my $self = shift;
return $self->addSchema('objectClasses', @_);
}
sub waitForEntry {
my ($self, $dn, $timeout, $attr, $quiet, $rc) = @_;
my $scope = "base";
my $filter = "(objectclass=*)";
if ($attr) {
$filter = "($attr=*)";
}
my @attrlist = ();
if ($attr) {
@attrlist = ($attr);
}
$timeout = ($timeout ? $timeout : 7200);
$timeout = time + $timeout;
if (ref($dn) eq 'Net::LDAP::Entry') {
$dn = $dn->dn;
}
# wait for entry and/or attr to show up
my $mesg = $self->search(base => $dn, scope => $scope, filter => $filter, attrs => [@attrlist]);
check_mesg($mesg, "Error waiting for entry $dn",
{LDAP_NO_SUCH_OBJECT => LDAP_NO_SUCH_OBJECT});
$rc = $mesg->code();
$attr = "" if (!$attr); # to avoid uninit. variable
$| = 1; #keep that output coming...
print "Waiting for $dn:$attr ", $self->toString() if (!$quiet);
my $entry = $mesg->shift_entry();
while (!$entry && (time < $timeout)) {
print "$rc:" if (!$quiet);
sleep 1;
my $mesg = $self->search(base => $dn, scope => $scope, filter => $filter, attrs => [@attrlist]);
check_mesg($mesg, "Error waiting for entry $dn",
{LDAP_NO_SUCH_OBJECT => LDAP_NO_SUCH_OBJECT});
$entry = $mesg->shift_entry;
$rc = $mesg->code;
}
if (!$entry && (time > $timeout)) {
print "\nwaitForEntry timeout for $dn for ", $self->toString(), "\n";
} elsif ($entry && !$quiet) {
print "\nThe waited for entry is:\n";
$entry->dump;
print "\n";
} elsif (!$entry) {
print "\nwaitForEntry error $rc reading $dn for ", $self->toString(), "\n";
}
return $entry;
}
# if $parentOrEntry is a string DN, add a random entry using that DN as the parent
# if $parentOrEntry is an Entry, add the entry
# returns the entry added or undef
sub addEntry {
my ($self, $parentOrEntry, $check) = @_;
my $rc;
my $dn;
my $entry;
if (ref($parentOrEntry) ne 'Net::LDAP::Entry') {
my $cn = "repl" . rand(100);
$dn = "cn=$cn, " . $parentOrEntry;
$mesg = $self->search(base => $dn, scope => "base", filter => "(objectclass=*)");
check_mesg($mesg, "Error searching for $dn",
{LDAP_NO_SUCH_OBJECT => LDAP_NO_SUCH_OBJECT});
$entry = $mesg->shift_entry;
if (!$entry) {
$entry = new Net::LDAP::Entry;
$entry->dn($dn);
$entry->add('objectclass' => ["top", "extensibleobject"]);
$entry->add('cn', $cn);
$mesg = $self->add($entry);
}
} else {
$entry = $parentOrEntry;
$dn = $entry->dn;
$mesg = $self->add($entry);
}
check_mesg($mesg, "Could not add entry $dn");
if ($check) {
$mesg = $self->search(base => $dn, scope => "base", filter => "(objectclass=*)");
check_mesg($mesg, "Could not search for new entry $dn");
$entry = $mesg->shift_entry;
$entry->dump;
}
return $entry;
}
sub enableReplLogging {
my $self = shift;
return $self->setLogLevel(8192);
}
sub disableReplLogging {
my $self = shift;
return $self->setLogLevel(0);
}
sub setLogLevel {
my ($self, @vals) = @_;
my ($rc, %mod, $val);
for (@vals) {
$val += $_;
}
my $mesg = $self->modify('cn=config', replace => {'nsslapd-errorlog-level' => $val});
check_mesg($mesg, "Could not set log level to $val");
return $rc;
}
sub setAccessLogLevel {
my ($self, @vals) = @_;
my ($rc, %mod, $val);
for (@vals) {
$val += $_;
}
my $mesg = $self->modify('cn=config', replace => {'nsslapd-accesslog-level' => $val});
check_mesg($mesg, "Could not set access log level to $val");
return $rc;
}
sub setDBReadOnly {
my ($self, $val, $bename) = @_;
$bename = ($bename ? $bename : "userRoot");
my $dn = "cn=$bename, cn=ldbm database, cn=plugins, cn=config";
my $mesg = $self->modify($dn, replace => {'nsslapd-readonly' => $val});
check_mesg($mesg, "Could not set nsslapd-readonly to $val");
return $rc;
}
# argument is a hashref - key is password policy attr, value is off or on
# attrs are:
# passwordchecksyntax - check password syntax when adding/changing password
# passwordexp - check for password expiration
# passwordhistory - keep and check password history
# passwordlockout - lockout accounts after unsuccessful bind attempts
# passwordisglobalpolicy - allow replication of operational password policy attrs in user entries
sub setupPasswordPolicy {
my ($self, $href) = @_;
my @changes;
while (my ($key, $val) = each %{$href}) {
push @changes, ( replace => [ $key => $val ] );
print "setupPasswordPolicy: $key is $val\n";
}
my $mesg = $self->modify("cn=config", changes => \@changes);
check_mesg($mesg, "Could not setup password policy");
return 0;
}
sub setupChainingIntermediate {
my ($self, $bename) = @_;
my $confdn = "cn=config,cn=chaining database,cn=plugins,cn=config";
my $mesg = $self->modify($confdn, add =>
{nsTransmittedControl =>
[ '2.16.840.1.113730.3.4.12', '1.3.6.1.4.1.1466.29539.12' ]
}
);
check_mesg($mesg, "Could not setup chaining intermediate",
{LDAP_TYPE_OR_VALUE_EXISTS => LDAP_TYPE_OR_VALUE_EXISTS});
return 0;
}
sub setupChainingMux {
my ($self, $suffix, $isIntermediate, $binddn, $bindpw, @urls) = @_;
my $rc = $self->addSuffix($suffix, $binddn, $bindpw, @urls);
if (!$rc && $isIntermediate) {
$rc = $self->setupChainingIntermediate($suffix);
}
return $rc;
}
sub setupChainingFarm {
my ($self, $suffix, $binddn, $bindcn, $bindpw) = @_;
my $rc;
# step 1 - create the bind dn to use as the proxy
if ($rc = $self->setupBindDN($binddn, $bindcn, $bindpw)) {
print "Couldn't setup chaining bind dn $binddn $rc: " . $self->getErrorString(), "\n";
} elsif ($rc = $self->addSuffix($suffix)) { # step 2 - create the suffix
print "Couldn't add chaining suffix $bename $suffix $rc: " . $self->getErrorString(), "\n";
} else {
# step 3 - add the proxy ACI to the suffix
my $mesg = $self->modify($suffix, add =>
{aci =>
[ "(targetattr = \"*\")(version 3.0; acl \"Proxied authorization for database links\"; allow (proxy) userdn = \"ldap:///$binddn\";)" ]
}
);
check_mesg($mesg, "Could not add aci for chaining farm",
{LDAP_TYPE_OR_VALUE_EXISTS => LDAP_TYPE_OR_VALUE_EXISTS});