goto-common/0000755000175000017500000000000011401404140012623 5ustar benoitbenoitgoto-common/GOto/0000755000175000017500000000000011415400611013477 5ustar benoitbenoitgoto-common/GOto/LDAP.pm0000755000175000017500000006405511346132401014574 0ustar benoitbenoit#!/usr/bin/perl -l -s # Copyright (c) 2008 Landeshauptstadt München # # Author: Matthias S. Benkmann # # 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, either version 2 of the License, or # (at your option) any later version. # # 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, see . # Documentation available via # perldoc GOto::LDAP # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # If you change anything that affects the API, don't forget to update # the pod at the end of this file! # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! package GOto::LDAP; use strict; use warnings; use Carp; use Net::LDAP; use Net::LDAP::Util qw(escape_filter_value ldap_explode_dn); use MIME::Base64; our (@ISA, @EXPORT, @EXPORT_OK); require Exporter; @ISA=('Exporter'); @EXPORT = qw(); @EXPORT_OK = qw(ldap_get_object printEntry printAttribute); sub ldap_get_object { my %a = @_; my ($ldap, $basedn, $user, $timeout, $filter, $debug, $objectClass, $cnou, $subquery, $sublevel, $subconflict, $attributeSelectionRegexes, $enctrigger, $format, $dups, $mergeResults) = #NOTE: mergeResults only has an effect in list context ($a{ldap}, $a{basedn}, $a{user}, $a{timeout}, $a{filter}, $a{debug}, $a{objectClass}, $a{cnou}, $a{subquery}, $a{sublevel}, $a{subconflict}, $a{attributeSelectionRegexes}, $a{enctrigger}, $a{format}, $a{dups},$a{mergeResults}); my $results; defined($mergeResults) or $mergeResults = 1; wantarray or $mergeResults = 1; if (defined($debug)) { defined($enctrigger) or $enctrigger="[\x00-\x1f]"; $enctrigger eq "none" and $enctrigger="^\x00\$"; if (!defined($format) or ($format ne "a:v" and $format ne "v")) { $format="a:v"; } } if (not defined($filter) or $filter eq "") { $filter = ""; } else { $filter = "(" . $filter . ")" unless $filter =~ m/^\(.*\)$/; } $user = escape_filter_value($user); defined($timeout) or $timeout=10; if (defined($subquery)) { defined($sublevel) or $sublevel=9999; defined($subconflict) or $subconflict=1; $subquery="(" . $subquery . ")" unless $subquery =~ m/^\(.*\)$/; } else { $sublevel=undef; $subconflict=undef; } if (defined($objectClass) and defined($cnou)) { $objectClass = escape_filter_value($objectClass); $cnou = escape_filter_value($cnou); } else { $objectClass = undef; $cnou = undef; } if (defined($objectClass)) # looking for object { $results = $ldap->search( base => $basedn, filter => "(&" . $filter . "(&(objectClass=$objectClass)(cn=$cnou))" . ")", timelimit => $timeout, ); ($results->code == 0) or return error($results->error); if ($results->count == 0) { $results = $ldap->search( base => $basedn, filter => "(&" . $filter . "(&(objectClass=$objectClass)(ou=$cnou))" . ")", timelimit => $timeout, ); } ($results->count == 0) and return error("Could not find data for object \"$objectClass/$cnou\""); ($results->count > 1) and return error("More than one object matches \"$objectClass/$cnou\""); } else # looking for user { $results = $ldap->search( base => $basedn, filter => "(&" . $filter . "(|(&(objectClass=posixAccount)(uid=$user))(&(objectClass=posixGroup)(memberUid=$user)))" . ")", timelimit => $timeout, ); ($results->code == 0) or return error($results->error); ($results->count == 0) and return error("Could not find data for user \"$user\""); } my @entries = $results->entries; if (defined($debug)) { print "x:================= primary object and posixGroups =================="; foreach my $entry (@entries) { printEntry($entry, [".*"], $enctrigger, $format); print "x:_______________________________________________________________"; } } my ($userDN, $dnFilter) = collectDNs($results); defined($userDN) or return error(); $results = $ldap->search( base => $basedn, filter => "(&" . $filter . $dnFilter . ")", timelimit => $timeout, ); ($results->code == 0) or return error($results->error); my @objectGroups = $results->entries; if (defined($debug)) { print "x:================= gosaGroupOfNames =================="; foreach my $entry (@objectGroups) { printEntry($entry, [".*"], $enctrigger, $format); print "x:_______________________________________________________________"; } } my $userEntry = Net::LDAP::Entry->new; my $posixGroupEntry = Net::LDAP::Entry->new; my $objectGroupEntry = Net::LDAP::Entry->new; my $objectPosixGroupEntry = Net::LDAP::Entry->new; my %userEntryPseudoPrefixes = (); my %posixGroupEntryPseudoPrefixes = (); my %objectGroupEntryPseudoPrefixes = (); my %objectPosixGroupEntryPseudoPrefixes = (); foreach my $entry (@entries) # User node and posixGroups { if (defined($subquery)) { if (!integrateSubtrees($ldap, $timeout, $entry, $subquery)) {return error();}; } my ($dest, $destPseudoPrefixes); if ($entry->dn eq $userDN) { $dest = $userEntry; $destPseudoPrefixes = \%userEntryPseudoPrefixes; } else { $dest = $posixGroupEntry; $destPseudoPrefixes = \%posixGroupEntryPseudoPrefixes; } copySelectedAttributes($entry, $dest, $attributeSelectionRegexes, 1, $sublevel, $subconflict, $destPseudoPrefixes); } foreach my $entry (@objectGroups) # object groups with direct and indirect membership { if (defined($subquery)) { if (!integrateSubtrees($ldap, $timeout, $entry, $subquery)) {return error();}; } my ($dest, $destPseudoPrefixes); if (hasAttribute($entry, "member", $userDN)) #direct membership { $dest = $objectGroupEntry; $destPseudoPrefixes = \%objectGroupEntryPseudoPrefixes; } else #indirect membership { $dest = $objectPosixGroupEntry; $destPseudoPrefixes = \%objectPosixGroupEntryPseudoPrefixes; } copySelectedAttributes($entry, $dest, $attributeSelectionRegexes, 1, $sublevel, $subconflict, $destPseudoPrefixes); } if (defined($debug)) { print "x:================= attributes from primary object =================="; printEntry($userEntry, [".*"], $enctrigger, $format); print "x:================= attributes from posixGroups =================="; printEntry($posixGroupEntry, [".*"], $enctrigger, $format); print "x:=========== attributes from gosaGroupOfNames (direct membership) ============"; printEntry($objectGroupEntry, [".*"], $enctrigger, $format); print "x:=========== attributes from gosaGroupOfNames (via posixGroup) ============"; printEntry($objectPosixGroupEntry, [".*"], $enctrigger, $format); } # If $mergeResults is requested, we move all attributes to $userEntry. # If $mergeResults is not wanted, we still move those attributes which are # not merged (because only one value is allowed for them). my $attributesToMove; if ($mergeResults) { $attributesToMove = $attributeSelectionRegexes; } else { $attributesToMove = [grep(!/^@/, @$attributeSelectionRegexes)]; } # Warnings are turned off here, because they've already been printed by the calls to # copySelectedAttributes above and there's no need to get every warning twice. # Besides, since we always copy to the same object we'd get lots of bogus warnings. moveSelectedAttributes($posixGroupEntry, $userEntry, $attributesToMove, 0, $sublevel, $subconflict, \%userEntryPseudoPrefixes); moveSelectedAttributes($objectGroupEntry, $userEntry, $attributesToMove, 0, $sublevel, $subconflict, \%userEntryPseudoPrefixes); moveSelectedAttributes($objectPosixGroupEntry, $userEntry, $attributesToMove, 0, $sublevel, $subconflict, \%userEntryPseudoPrefixes); $userEntry->dn($userDN); my @results = ($userEntry); if (not $mergeResults) { foreach my $additionalEntry ($posixGroupEntry, $objectGroupEntry, $objectPosixGroupEntry) { if ($additionalEntry->attributes) { push @results, $additionalEntry; } } } # Unfortunately Net::LDAP::Entry does not remove duplicate attribute values, so we # have to do it ourselves. if (defined($dups) and not $dups) { foreach my $entry (@results) { foreach my $attr ($entry->attributes) { my %unique = (); my @values = (); my $r_values = $entry->get_value($attr, asref => 1); foreach my $value (@$r_values) { if (!exists($unique{$value})) { $unique{$value} = 1; push @values, $value; } } $entry->replace($attr, \@values); } } } if (wantarray) { return @results; } else { return $results[0]; } } # ldap_get_object() # printEntry($entry, \@attributeSelectionRegexes, $enctrigger, $format, [$suppressDn]) # Prints out all attributes of $entry. The dn is only printed if it matches one of the # regexes from @attributeSelectionRegexes and only if $suppressDn is false. sub printEntry { my ($entry, $r_regex, $enctrigger, $format, $suppressDn) = @_; defined($entry) or return error("printEntry called for undef"); foreach my $rx (@$r_regex) { my $regex = $rx; # copy so that we don't change the original value if (substr($regex, 0, 1) eq "\@") { $regex = substr($regex,1); } $regex = "^" . $regex . "\$"; # always match complete string if (not($suppressDn) and "dn" =~ m/$regex/) { my $dn = $entry->dn; defined($dn) or $dn = ""; printAttribute("dn", [$dn], $enctrigger, $format); last; } } foreach my $attr (sort $entry->attributes) { my $r_values = $entry->get_value($attr, asref => 1); printAttribute($attr, $r_values, $enctrigger, $format); } } # printAttribute($attr, \@values, $enctrigger, $format) sub printAttribute { my ($attr, $r_values, $enctrigger, $format) = @_; my %haveSeen; my $regex = qr($enctrigger); foreach my $value (sort @$r_values) { exists($haveSeen{$value}) and next; $haveSeen{$value} = 1; my $out = ""; if ($value =~ m/$enctrigger/) { if ($format eq "a:v") { $out = $attr . ":: "; } $out = $out . encode_base64($value, ""); } else { if ($format eq "a:v") { $out = $attr . ": "; } $out = $out . $value; } print $out; } } # integrateSubtrees($ldap, $timeout, $entry, $subquery) # On error returns false, otherwise true. sub integrateSubtrees { my ($ldap, $timeout, $entry, $subquery) = @_; my $results = $ldap->search( base => $entry->dn, filter => $subquery, timelimit => $timeout, ); ($results->code == 0) or return error($results->error); foreach my $subentry ($results->entries) { ($subentry->dn eq $entry->dn) and next; my $dn = $subentry->dn; $dn = substr($dn, 0, length($dn) - length($entry->dn) - 1); # -1 for "," my $x = ldap_explode_dn($dn, reverse => 1); my $attrPrefix = ""; foreach my $part (@$x) { foreach my $str (sort values %$part) { $attrPrefix .= $str . "/"; } } foreach my $attr ($subentry->attributes) { my $r_values = $subentry->get_value($attr, asref => 1); $entry->add($attrPrefix . $attr, $r_values); } } return 1; } # see copyMoveSelectedAttributes sub copySelectedAttributes { copyMoveSelectedAttributes(0, @_); } # see copyMoveSelectedAttributes sub moveSelectedAttributes { copyMoveSelectedAttributes(1, @_); } # copyMoveSelectedAttributes($move, $entry, $dest, \@attributeSelectionRegexes, # $warn, $sublevel, $subconflict, \%destPseudoPrefixes) # Copies those entries from $entry to $dest (both of type Net::LDAP::Entry) # whose names match one of the regular expressions in the array @attributeSelectionRegexes. # If an attribute is already present in $dest, conflict resolution is # performed as detailed in the USAGE. In the case of a non-merge conflict, the attribute will # not be copied, i.e. for conflicting non-merged attributes, $dest's existing # values take precedence. # If $warn is false, then no warning is printed in case of a non-merge conflicting attribute. # $sublevel works as described in the USAGE. # If $subconflict > 0 then an attribute whose name contains a slash will be considered to # already exist in $dest iff %destPseudoPrefixes contains the string you get by removing # the shortest suffix with $subconflict slashes from the attribute name. # Before copySelectedAttributes returns, it adds all of the pseudo-prefixes of the # copied attributes to %destPseudoPrefixes so that the next time they will give a conflict. # If $move is true, the original attribute will be removed from its dataset, even if it # was not copied due to a conflict. sub copyMoveSelectedAttributes { my ($move, $entry, $dest, $r_regex, $wrn, $sublevel, $subconflict, $destPseudoPrefixes) = @_; my @attrNames = $entry->attributes; my %newPseudoPrefixes = (); foreach my $rx (@$r_regex) { my $regex = $rx; # copy so that we don't change the original value ($regex eq "") and next; (scalar(@attrNames) == 0) and last; my $merge = 0; if (substr($regex, 0, 1) eq "\@") { $regex = substr($regex,1); $merge = 1; } $regex = "^" . $regex . "\$"; # always match complete string $regex = qr/$regex/i; # case-insensitive match my @matching = grep(/$regex/, @attrNames); @attrNames = grep(!/$regex/, @attrNames); foreach my $longattr (@matching) { my $attr = $longattr; if (defined($sublevel) and $sublevel < 9999) { $attr = suffixWithMaxSlashes($attr, $sublevel); } my $conflict = 0; if (not $merge) { if (defined($subconflict) and $subconflict != 0 and index($attr, "/") >= 0) { my $conflicter = removeSuffixWithSlashes($attr, $subconflict); if (exists($$destPseudoPrefixes{$conflicter})) { $conflict = 1; } else { $newPseudoPrefixes{$conflicter} = 1; # next time the same string will give a conflict } } elsif ($dest->exists($attr)) { $conflict = 1; } $conflict and $wrn and print STDERR "WARNING: 2 sources with same precedence for attribute \"", $attr, "\""; } if (not $conflict) { my $r_values = $entry->get_value($longattr, asref => 1); $dest->add($attr => $r_values); } if ($move) { $entry->delete($longattr); } } } my ($k, $v); while (($k,$v) = each %newPseudoPrefixes) { $$destPseudoPrefixes{$k} = $v; } } # $string = removeSuffixWithSlashes($string, $slashnum) # Returns $string with the shortest suffix that contains $slashnum slashes removed. # If $string contains fewer than $slashnum slashes, returns the empty string. sub removeSuffixWithSlashes { my ($string, $slashnum) = @_; my $pos = length($string); while (--$slashnum >= 0) { $pos = rindex($string, "/", $pos-1); ($pos < 0) and return ""; # fewer slashes than required => return "" } return substr($string, 0, $pos); } # $string = suffixWithMaxSlashes($string, $slashnum) # Returns the longest suffix of $string that contains at most $slashnum slashes. sub suffixWithMaxSlashes { my ($string, $slashnum) = @_; my $pos = length($string); while ($slashnum-- >= 0) { $pos = rindex($string, "/", $pos-1); ($pos < 0) and return $string; # fewer slashes than required max. => return original string } return substr($string, $pos + 1); } # ($userDN, $dnFilter) = collectDNs($results) # $results: return value from ldap->search. Only $results->entries is used. # ($userDN, $dnFilter): # $userDN: the DN of the entry of objectClass posixAccount. # If there are multiple, the sub will return undef # If there is none, the first entry's DN will be used. # $dnFilter: (|(member=DN1)(member=DN2)...) where DN1,... are the DNs of the entries. sub collectDNs { my $results = shift; my $userDN; my $dnFilter = ""; my $firstDN; foreach my $entry ($results->entries) { defined($firstDN) or $firstDN = $entry->dn; if (hasAttribute($entry, "objectClass", "posixAccount")) { defined($userDN) and return error("2 posixAccounts for the same user"); $userDN = $entry->dn; } $dnFilter = $dnFilter . "(member=" . escape_filter_value($entry->dn) . ")"; } defined($userDN) or $userDN = $firstDN; $dnFilter = "(|" . $dnFilter . ")"; return ($userDN, $dnFilter); } # $bool = hasAttribute($entry, $attrName, $attrValue) # Returns true iff the Net::LDAP::Entry $entry has # an attribute named $attrName with value $attrValue. sub hasAttribute { my ($entry, $attrName, $attrValue) = @_; foreach my $attr ($entry->get_value($attrName)) { if ($attr eq $attrValue) { return 1; } } return 0; } sub error { if (@_) { carp "ERROR: ", @_; } if (wantarray) { return (); } else { return undef; } } 1; __END__ =head1 NAME GOto::LDAP - Support library for goto-* scripts to access LDAP =head1 SYNOPSIS use GOto::Common qw(:ldap); use GOto::LDAP qw(ldap_get_object); my $ldapinfo = goto_ldap_parse_config_ex(); #ref to hash my ($ldapbase,$ldapuris) = ($ldapinfo->{"LDAP_BASE"}, $ldapinfo->{"LDAP_URIS"}); my $ldap = Net::LDAP->new( $ldapuris, timeout => $timeout ) or die; $ldap->bind() ; # anonymous bind # list context my @results = ldap_get_object(ldap => $ldap, basedn => $ldapbase, user => $user, timeout => $timeout, filter => $filter, debug => $debug, objectClass => $objectClass, cnou => $cn, subquery => $subquery, sublevel => $sublevel, subconflict => $subconflict, attributeSelectionRegexes => \@attributeSelectionRegexes, enctrigger => $enctrigger, format => $format, dups => $dups, mergeResults => $mergeResults ); @results or die; # scalar context my $result = ldap_get_object(...); $result or die; =head1 DESCRIPTION of C C reads information about an object (usually a user, but can also be a workstation, a POSIX group,...) from LDAP. C understands gosaGroupOfNames and posixGroups and will not only return properties of the queried object itself but also properties inherited from groups of both types. =head1 PARAMETERS =over =item B An object of type L that is already bound. Required. =item B The base DN to use for all searches. Required. =item B/B and B You must pass either C or C. If you pass C, C is ignored and C will search for an object with C and C equal to the value passed as C. If you pass C, then you must also pass C and C will search for an object with the given C and a C equal to the value passed as C. If no such object is found, it will attempt to find an object with the given C and C equal to the value of C. =item B and B A reference to a an array of regular expressions (as strings) that select the attributes to be returned and determines how to proceed in case there are multiple sources for an attribute (e.g. the user's posixAccount node and a posixGroup the user is a member of). Each regex selects all attributes with matching names. If the regex starts with the character C<@> (which is ignored for the matching), then attribute values from different sources will be merged (i.e. the result will include all values). If attributeRegex does NOT start with C<@>, then an attribute from the queried object's own node beats a posix group, which beats an object group (=gosaGroupOfNames) that includes the object directly which beats an object group that contains a posix group containing the object. Object groups containing other object groups are not supported by GOsa, so this case cannot occur. If 2 sources with the same precedence (e.g. 2 posix groups) provide an attribute of the same name, selected by a regex that doesn not start with C<@>, then a WARNING is signalled and the program picks one of the conflicting attributes. If multiple attribute regexes match the same attribute, the 1st matching attribute regex's presence or absence of C<@> determines conflict resolution. Matching is always performed against the I attribute name as if the regex had been enclosed in C<^...$>, i.e. an attribute regex C will NOT match an attribute called C. Neither will the regex C. Matching is always performed case-insensitive. If the parameter C is not passed, it defaults to C<@.*>. =item B If C is C and C is evaluated in list context, then it will return a list of L objects where each object represents the attributes on a given precedence level. The first entry gives the attributes that come from the own node, i.e. those with the highest precedence. Attributes selected with a non-C<@> regex, i.e. those for which only one source is permitted, are always found in the first entry and only there. For these attributes all conflicting values from lower precedence levels are always discarded, so C only makes sense when requesting merged attributes via C<@>. If C is C (the default) or if C is evaluated in scalar context, then only one L will be returned that contains all of the requested attributes. =item B L does not perform duplicate removal on its attribute value lists by default. If C (the default), the results returned from C may contain attributes that contain duplicate entries. If this would confuse your code, pass C and duplicate values will be eliminated (at the cost of a few CPU cycles). =item B If C is passed, LDAP requests will use a timeout of this number of seconds. Note that this does I mean that C will finish within this time limit, since several LDAP requests may be involved. Default timeout is 10s. =item B C is an LDAP-Expression that will be ANDed with all user/object/group searches done by this program. Use this to filter by C. =item B The C parameter is an LDAP filter such as C. For the subtrees rooted at the object's own node and at all of its containing groups' nodes, an LDAP query using this filter will be done. The attributes of all of the objects resulting from these queries will be treated as if they were attributes of the node at which the search was rooted. The names of these pseudo-attributes have the form C. =item B C specifies the maximum number of slashes the pseudo-attribute names will contain. If the complete name of a pseudo-attribute has more slashes than the given number, the name will be shortened to the longest suffix that contains this many slashes. Specifying a C of 0 will effectively merge all subquery nodes with the user/object/group node so that in the end result their attributes are indistinguishable from those of the user/object/group node. Default C is 9999. Note: attribute regex matching is performed on the full name with all slashes. =item B C is a number that determines when 2 pseudo-attributes are treated as being in conflict with each other. 2 pseudo-attributes are treated as conflicting if the results of removing the shortest suffixes containing C slashes from their names (shortened according to C) are identical. E.g. with C the pseudo-attributes C and C are not conflicting, whereas with C they are. Default C is 1. =item B If C is C, then lots of debug output (mostly all of the nodes considered in constructing the result) is printed to stdout. =item B This parameter is only relevant when C is C. It affects the way, attribute values are printed. If C is passed, it is interpreted as a regular expression and all DNs and attribute values will be tested against this regex. Whenever a value matches, it will be output base64 encoded. Matching is performed case-sensitive and unless ^ and $ are used in the regex, matching substrings are enough to trigger encoding. If no C is specified, the default C<[\x00-\x1f]> is used (i.e. base64 encoding will be used whenever a value contains a control character). If you pass C, encoding will be completely disabled. =item B This parameter is only relevant when C is C. It affects the way, attribute values are printed. Format C<"a:v"> means to print C pairs. Format C means to print the values only. =back =cut goto-common/GOto/Utils.pm0000644000175000017500000002356511415400611015150 0ustar benoitbenoit#********************************************************************* # # GOto::Utils package -- Log parsing aid. # # (c) 2008 by Cajus Pollmeier # #********************************************************************* package GOto::Utils; use Exporter; @ISA = qw(Exporter); @EXPORT = qw(process_input); use strict; use warnings; use POSIX; use Locale::gettext; use MIME::Base64; BEGIN {} END {} ### Start ###################################################################### # I18N setup setlocale(LC_MESSAGES, ""); textdomain("fai-progress"); use constant TG_NONE => 0; use constant TG_INSTALL => 1; use constant TG_CONFIG => 1; use constant TG_WAITACTIVE => 2; use constant TG_HWDETECT => 3; # "Global" variables my $percent= 0; my $pkg_step= 0.0; my $scr_step= 0.0; my $task= TG_NONE; my $action= gettext("Initializing FAI"); #=== FUNCTION ================================================================ # NAME: process_input # PARAMETERS: received line of input # RETURNS: true if stream wants us to finish # DESCRIPTION: parses information from the lines and sets the progress # respectively #=============================================================================== sub process_input($) { my %result; my $line= shift; chomp($line); # Assume no errors $result{'status'}= 0; # Do regex if ( $line =~ m/^fai-progress: hangup$/ ) { $result{'status'}= -1; } elsif ( $line =~ /^Calling task_confdir$/ ) { %result = ( 'status' => 0, 'percent' => 0, 'task' => "task_confdir", 'action' => gettext("Retrieving initial client configuration")); } elsif ( $line =~ /^Calling task_setup$/ ) { %result = ( 'status' => 0, 'percent' => 1, 'task' => "task_setup", 'action' => gettext("Gathering client information")); } elsif ( $line =~ /^Calling task_defclass$/ ) { %result = ( 'status' => 0, 'percent' => 1, 'task' => "task_defclass", 'action' => gettext("Defining installation classes")); } elsif ( $line =~ /^Calling task_defvar$/ ) { %result = ( 'status' => 0, 'percent' => 1, 'task' => "task_defvar", 'action' => gettext("Defining installation variables")); } elsif ( $line =~ /^FAI_ACTION: install$/ ) { %result = ( 'status' => 0, 'percent' => 2, 'task' => "task_defvar", 'action' => gettext("Starting installation")); } elsif ( $line =~ /^Calling task_install$/ ) { %result = ( 'status' => 0, 'percent' => 2, 'task' => "task_defvar", 'action' => gettext("Starting installation")); } elsif ( $line =~ /^Calling task_partition$/ ) { %result = ( 'status' => 0, 'percent' => 2, 'task' => "task_partition", 'action' => gettext("Inspecting harddisks")); } elsif ( $line =~ /^Creating partition table/ ) { %result = ( 'status' => 0, 'percent' => 2, 'task' => "task_partition", 'action' => gettext("Partitioning harddisk")); } elsif ( $line =~ /^Creating file systems/ ) { %result = ( 'status' => 0, 'percent' => 3, 'task' => "task_partition", 'action' => gettext("Creating filesystems")); } elsif ( $line =~ /^Calling task_mountdisks$/ ) { %result = ( 'status' => 0, 'percent' => 3, 'task' => "task_mountdisks", 'action' => gettext("Mounting filesystems")); # Original FAI counting, no possibility to do anything here... } elsif ( $line =~ /^Calling task_extrbase$/ ) { %result = ( 'status' => 0, 'percent' => 3, 'task' => "task_extrbase", 'action' => gettext("Bootstrapping base system")); $percent= 3; # Using debootstrap for boostrapping is a bit more wise in at this point. Start at 3% and grow to approx 15%. } elsif ( $line =~ /^HOOK extrbase/ ) { %result = ( 'status' => 0, 'percent' => 3, 'task' => "task_extrbase", 'action' => gettext("Bootstrapping base system")); } elsif ( $line =~ /^I: Retrieving (.+)$/ ) { $percent= ($percent > 12) ? 12 : $percent + 0.025; %result = ( 'status' => 0, 'percent' => floor(3 + $percent), 'task' => "task_extrbase", 'action' => gettext("Bootstrapping base system").": ".sprintf(gettext("Retrieving %s..."), $1)); } elsif ( $line =~ /^I: Extracting (.+)$/ ) { $percent= ($percent > 12) ? 12 : $percent + 0.025; %result = ( 'status' => 0, 'percent' => floor(3 + $percent), 'task' => "task_extrbase", 'action' => gettext("Bootstrapping base system").": ".sprintf(gettext("Extracting %s..."), $1)); } elsif ( $line =~ /^I: Validating (.+)$/ ) { $percent= ($percent > 12) ? 12 : $percent + 0.025; %result = ( 'status' => 0, 'percent' => floor(3 + $percent), 'task' => "task_extrbase", 'action' => gettext("Bootstrapping base system").": ".sprintf(gettext("Validating %s..."), $1)); } elsif ( $line =~ /^I: Unpacking (.+)$/ ) { $percent= ($percent > 12) ? 12 : $percent + 0.025; %result = ( 'status' => 0, 'percent' => floor(3 + $percent), 'task' => "task_extrbase", 'action' => gettext("Bootstrapping base system").": ".sprintf(gettext("Unpacking %s..."), $1)); } elsif ( $line =~ /^I: Configuring (.+)$/ ) { $percent= ($percent > 12) ? 12 : $percent + 0.025; %result = ( 'status' => 0, 'percent' => floor(3 + $percent), 'task' => "task_extrbase", 'action' => gettext("Bootstrapping base system").": ".sprintf(gettext("Configuring %s..."), $1)); } elsif ( $line =~ /^Calling task_debconf$/ ) { %result = ( 'status' => 0, 'percent' => 15, 'task' => "task_debconf", 'action' => gettext("Configuring base system")); } elsif ( $line =~ /^Calling task_prepareapt$/ ) { %result = ( 'status' => 0, 'percent' => 15, 'task' => "task_prepareapt", 'action' => gettext("Preparing network install")); } elsif ( $line =~ /^Calling task_updatebase$/ ) { %result = ( 'status' => 0, 'percent' => 15, 'task' => "task_updatebase", 'action' => gettext("Updating base system")); } elsif ( $line =~ /^Calling task_instsoft$/ ) { $task= TG_INSTALL; %result = ( 'status' => 0, 'percent' => 16, 'task' => "task_instsoft", 'action' => gettext("Gathering information for package lists")); } elsif ( $task == TG_INSTALL && $line =~ /([0-9]+) packages upgraded, ([0-9]+) newly installed/ ) { $pkg_step= 69.0 / ($1 + $2) / 3.0; $percent= 16.0; } elsif ( $task == TG_INSTALL && $line =~ /Get:[0-9]+ [^ ]+ [^ ]+ ([^ ]+)/ ) { $percent+= $pkg_step; %result = ( 'status' => 0, 'percent' => floor($percent), 'task' => "task_instsoft", 'action' => gettext("Software installation").": ".sprintf(gettext("Retrieving %s..."), $1)); } elsif ( $task == TG_INSTALL && $line =~ /Unpacking ([^ ]+) .*from/ ) { $percent+= $pkg_step; %result = ( 'status' => 0, 'percent' => floor($percent), 'task' => "task_instsoft", 'action' => gettext("Software installation").": ".sprintf(gettext("Extracting %s..."), $1)); } elsif ( $task == TG_INSTALL && $line =~ /Setting up ([^ ]+)/ ) { $percent+= $pkg_step; %result = ( 'status' => 0, 'percent' => floor($percent), 'task' => "task_instsoft", 'action' => gettext("Software installation").": ".sprintf(gettext("Configuring %s..."), $1)); } elsif ( $line =~ /^Calling task_configure$/ ) { $task= TG_CONFIG; %result = ( 'status' => 0, 'percent' => 80, 'task' => "task_configure", 'action' => gettext("Software installation").": ".gettext("Adapting system and package configuration")); } elsif ( $line =~ /^Script count: ([0-9]+)$/ ) { $percent= 85.0; $scr_step= 15.0 / $1; } elsif ( $line =~ /^Executing +([^ ]+): ([^\n ]+)$/ ) { $percent+= $scr_step; %result = ( 'status' => 0, 'percent' => floor($percent), 'task' => "task_configure", 'action' => sprintf(gettext("Running script %s (%s)..."), $1, $2)); } elsif ( $line =~ /^Calling task_savelog$/ ) { $percent= 100; %result = ( 'status' => 0, 'percent' => floor($percent), 'task' => "task_savelog", 'action' => gettext("Installation finished")); # Status evaluation } elsif ( $line =~ /^TASKEND ([^ ]+) ([0-9]+)$/ ) { if ($2 != 0){ %result = ( 'status' => $2, 'task' => "$1"); } # Common errors } elsif ( $line =~ /^goto-error-([^:]+)$/ ) { %result = ( 'status' => 5, 'task' => "error-$1"); } elsif ( $line =~ /^goto-error-([^:]+):(.*)$/ ) { %result = ( 'status' => 6, 'task' => "error-$1", 'action' => "$2"); } elsif ( $line =~ /^ldap2fai-error:(.*)$/ ) { my $message= decode_base64("$1"); $message =~ tr/\n/\n .\n /; %result = ( 'status' => 7, 'task' => "ldap2fai-error", 'action' => $message); } elsif ( $line =~ /^gosa-si-no-server-available$/ ) { %result = ( 'status' => 8, 'task' => "error-gosa-si-no-server", 'action' => gettext("No activation server available")); # GOto built ins } elsif ( $line =~ /goto-hardware-detection-start/ ) { if ($task != TG_WAITACTIVE){ $task= TG_HWDETECT; } %result = ( 'status' => 0, 'task' => "goto-hardware-detection-start", 'action' => gettext("Detecting hardware")); } elsif ( $line =~ /goto-hardware-detection-stop/ ) { if ($task == TG_WAITACTIVE){ %result = ( 'status' => 0, 'task' => "goto-activation-start", 'action' => gettext("Waiting for the system to be activated")); } else { %result = ( 'status' => 0, 'task' => "goto-hardware-detection-stop", 'action' => gettext("Inventarizing hardware information")); } } elsif ( $line =~ m/goto-activation-start/ ) { if ($task != TG_HWDETECT){ %result = ( 'status' => 0, 'task' => "goto-activation-start", 'action' => gettext("Waiting for the system to be activated")); } $task= TG_WAITACTIVE; } elsif ( $line =~ m/goto-activation-stop/ ) { %result = ( 'status' => 0, 'task' => "goto-activation-stop", 'action' => gettext("System activated - retrieving configuration")); } return \%result; } 1; goto-common/GOto/Common.pm0000644000175000017500000002572211357722345015315 0ustar benoitbenoitpackage GOto::Common; # $Id$ use strict; use Net::LDAP; use Net::LDAP::Constant qw(LDAP_NO_SUCH_OBJECT LDAP_REFERRAL); use URI; BEGIN { use Exporter (); use vars qw(%EXPORT_TAGS @ISA $VERSION); $VERSION = '20080116'; @ISA = qw(Exporter); %EXPORT_TAGS = ( 'ldap' => [qw( &goto_ldap_parse_config &goto_ldap_parse_config_ex &goto_ldap_fsearch &goto_ldap_rsearch &goto_ldap_is_single_result &goto_ldap_split_dn )], 'file' => [qw( &goto_file_write &goto_file_chown )], 'array' => [qw( &goto_array_find_and_remove )], 'string' => [qw( &goto_gen_random_str )] ); Exporter::export_ok_tags(keys %EXPORT_TAGS); } #------------------------------------------------------------------------------ sub goto_ldap_parse_config { my ($ldap_config) = @_; $ldap_config = $ENV{ 'LDAPCONF' } if( !defined $ldap_config && exists $ENV{ 'LDAPCONF' } ); $ldap_config = "/etc/ldap/ldap.conf" if( !defined $ldap_config ); # Read LDAP return if( ! open (LDAPCONF,"${ldap_config}") ); my @content=; close(LDAPCONF); my ($ldap_base, @ldap_uris); # Scan LDAP config foreach my $line (@content) { $line =~ /^\s*(#|$)/ && next; chomp($line); if ($line =~ /^BASE\s+(.*)$/i) { $ldap_base= $1; next; } if ($line =~ /^URI\s+(.*)\s*$/i) { my (@ldap_servers) = split( ' ', $1 ); foreach my $server (@ldap_servers) { if ( $server =~ /^((ldap[si]?:\/\/)([^\/:\s]+)?(:([0-9]+))?\/?)$/ ) { my $ldap_server = $3 ? $1 : $2.'localhost'; $ldap_server =~ s/\/\/127\.0\.0\.1/\/\/localhost/; push @ldap_uris, $ldap_server if ( $1 && ! grep { $_ =~ /^$ldap_server$/ } @ldap_uris ); } } next; } } return( $ldap_base, \@ldap_uris ); } sub goto_ldap_parse_config_ex { my %result = (); my $ldap_info = '/etc/ldap/ldap-shell.conf'; if ( -r '/etc/ldap/ldap-offline.conf' ) { $ldap_info = '/etc/ldap/ldap-offline.conf'; } if (!open( LDAPINFO, "<${ldap_info}" )) { warn "Couldn't open ldap info ($ldap_info): $!\n"; return undef; } while( ) { if( $_ =~ m/^([a-zA-Z_0-9]+)="(.*)"$/ ) { if ($1 eq "LDAP_URIS") { my @uris = split(/ /,$2); $result{$1} = \@uris; } else { $result{$1} = $2; } } } close( LDAPINFO ); if (not exists($result{"LDAP_URIS"})) { warn "LDAP_URIS missing in file $ldap_info\n"; } return \%result; } # Split the dn (works with escaped commas) sub goto_ldap_split_dn { my ($dn) = @_; # Split at comma my @comma_rdns = split( ',', $dn ); my @result_rdns = (); my $line = ''; foreach my $rdn (@comma_rdns) { # Append comma and rdn to line if( '' eq $line ) { $line = $rdn; } else { $line .= ',' . $rdn; } # Count the backslashes at the end. If we have even length # of $bs add to result array and set empty line my($bs) = $rdn =~ m/([\\]+)$/; $bs = "" if( ! defined $bs ); if( 0 == (length($bs) % 2) ) { push( @result_rdns, $line ); $line = ""; } } return @result_rdns; } #------------------------------------------------------------------------------ sub goto_file_write { my @opts = @_; my $len = scalar @_; ($len < 2) && return; my $filename = shift; my $data = shift; open (SCRIPT,">${filename}") || warn "Can't create ${filename}. $!\n"; print SCRIPT $data; close(SCRIPT); ($opts[2] ne "") && chmod oct($opts[2]),${filename}; ($opts[3] ne "") && goto_file_chown(${filename}, $opts[3]); } #------------------------------------------------------------------------------ sub goto_file_chown { my @owner = split('.',$_[1]); my $filename = $_[0]; my ($uid,$gid); $uid = getpwnam($owner[0]); $gid = getgrnam($owner[1]); chown $uid, $gid, $filename; } # # Common checks for forward and reverse searches # sub goto_ldap_search_checks { my( $base, $sbase ) = (@_)[1,2]; if( scalar @_ < 3 ) { warn( "goto_ldap_search needs at least 3 parameters" ); return; }; if( defined $sbase && (length($sbase) > 0) ) { # Check, if $sbase is a base of $base if( $sbase ne substr($base,-1 * length($sbase)) ) { warn( "goto_ldap_search: (1) '$sbase' isn't the base of '$base'" ); return; } $base = substr( $base, 0, length( $base ) - length( $sbase ) ); # Check, if $base ends with ',' after $sbase strip if( ',' ne substr( $base, -1 ) ) { warn( "goto_ldap_search: (2) '$sbase' isn't the base of '$base'" ); return; } $base = substr( $base, 0, length($base) - 1 ); $sbase = ',' . $sbase; } else { $sbase = ''; } return( $base, $sbase ); } # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # # $ldap = Net::LDAP handle # $base = Search base ( i.e.: ou=test,ou=me,ou=very,ou=well ) # $sbase = Stop base ( i.e.: ou=very,ou=well ) # $filter = LDAP filter # $scope = LDAP scope # $subbase = On every $base look into $subbase,$base ( i.e.: ou=do ) # $attrs = Result attributes # # Example searches in: # ou=do,ou=test,ou=me,ou=very,ou=well # ou=do,ou=me,ou=very,ou=well # ou=do,ou=very,ou=well # # Returns (Net::LDAP::Search, $search_base) on LDAP failure # Returns (Net::LDAP::Search, $search_base) on success # Returns undef on non-LDAP failures # sub goto_ldap_rsearch { use Switch; my ($ldap,$base,$sbase,$filter,$scope,$subbase,$attrs) = @_; ( $base, $sbase ) = goto_ldap_search_checks( @_ ); return if( ! defined $base ); my (@rdns,$search_base,$mesg); @rdns = goto_ldap_split_dn( $base ); return if( 0 == scalar @rdns ); while( 1 ) { # Walk the DN tree switch( scalar @rdns ) { case 0 { # We also want to search the stop base, if it was defined return if( ! defined $sbase ); if( length( $sbase ) > 0 ) { $search_base = substr( $sbase, 1 ); } else { $search_base = ''; } undef( $sbase ); } else { $search_base = join( ',', @rdns ); shift(@rdns); $search_base .= $sbase; } } # Initialize hash with filter my %opts = ( 'filter' => $filter ); # Set searchbase if( defined $subbase && $subbase ) { $opts{ 'base' } = "${subbase},${search_base}" } else { $opts{ 'base' } = "${search_base}" } # Set scope $opts{ 'scope' } = "$scope" if( defined $scope && $scope ); $opts{ 'attrs' } = @$attrs if( defined $attrs ); # LDAP search # The referral chasing is much simpler then the OpenLDAP one. # It's just single level support, therefore it can't really # chase a trail of referrals, but will check a list of them. my @referrals; my $chase_referrals = 0; RETRY_SEARCH: $mesg = $ldap->search( %opts ); if( LDAP_REFERRAL == $mesg->code ) { # Follow the referral if( ! $chase_referrals ) { my @result_referrals = $mesg->referrals(); foreach my $referral (@result_referrals) { my $uri = new URI( $referral ); next if( $uri->dn ne $opts{ 'base' } ); # But just if we have the same base push( @referrals, $uri ); } $chase_referrals = 1; } NEXT_REFERRAL: next if( ! length @referrals ); my $uri = new URI( $referrals[ 0 ] ); $ldap = new Net::LDAP( $uri->host ); @referrals = splice( @referrals, 1 ); goto NEXT_REFERRAL if( ! defined $ldap ); $mesg = $ldap->bind(); goto NEXT_REFERRAL if( 0 != $mesg->code ); goto RETRY_SEARCH; } if( LDAP_NO_SUCH_OBJECT == $mesg->code ) { # Ignore missing objects (32) goto NEXT_REFERRAL if( scalar @referrals ); next; } return $mesg if( $mesg->code ); # Return undef on other failures last if( $mesg->count() > 0 ); } return( $mesg, ${search_base} ); } #------------------------------------------------------------------------------ # See goto_ldap_rsearch # # sbase = start base # # Example searches in: # ou=do,ou=very,ou=well # ou=do,ou=me,ou=very,ou=well # ou=do,ou=test,ou=me,ou=very,ou=well # sub goto_ldap_fsearch { use Switch; my ($ldap,$base,$sbase,$filter,$scope,$subbase,$attrs) = @_; ( $base, $sbase ) = goto_ldap_search_checks( @_ ); return if( ! defined $base ); my (@rdns,$search_base,$mesg,$rdn_count); @rdns = reverse goto_ldap_split_dn( $base ); $rdn_count = scalar @rdns; return if( 0 == $rdn_count ); while( 1 ) { # Walk the DN tree if( ! defined $search_base ) { # We need to strip the leading ",", which is needed for research if( length( $sbase ) > 0 ) { $search_base = substr( $sbase, 1 ); } else { $search_base = ''; } } elsif( 0 == scalar @rdns ) { return undef; } else { $search_base = $rdns[ 0 ] . ',' . $search_base; shift(@rdns); } # Initialize hash with filter my %opts = ( 'filter' => $filter ); # Set searchbase if( defined $subbase && $subbase ) { $opts{ 'base' } = "${subbase},${search_base}"; } else { $opts{ 'base' } = "${search_base}"; } # Set scope $opts{ 'scope' } = "$scope" if( defined $scope && $scope ); $opts{ 'attrs' } = @$attrs if( defined $attrs ); # LDAP search $mesg = $ldap->search( %opts ); next if( $mesg->code == 32 ); # Ignore missing objects (32) return $mesg if( $mesg->code ); # Return undef on other failures last if( $mesg->count() > 0 ); } return( $mesg, ${search_base} ); } #------------------------------------------------------------------------------ # # $search_result = Net::LDAP::Serach # $get_entry = boolean # # if $get_entry == true, return $entry # == false, return 1 # # returns 0 on failure # sub goto_ldap_is_single_result { my ($search_result,$get_entry) = @_; my $result = 0; if( (defined $search_result) && (0 == $search_result->code) && (1 == $search_result->count()) ) { if( defined $get_entry && $get_entry ) { $result = ($search_result->entries())[ 0 ]; } else { $result = 1; } } return $result; } #------------------------------------------------------------------------------ sub goto_array_find_and_remove { my ($haystack,$needle) = @_; my $index = 0; foreach my $item (@$haystack) { if ($item eq $needle) { splice( @$haystack, $index, 1 ); return 1; } $index++; } return 0; } # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # # Generate a random string based on a symbolset # # @param int $strlen: length of result string # @param array ref: symbol set (optional) # @return string or undef # sub goto_gen_random_str { my ($strlen, $symbolset) = @_; return if( (! defined $strlen) || (0 > $strlen) ); return '' if( 0 == $strlen ); if( (! defined $symbolset) || ('ARRAY' ne ref( $symbolset )) || (0 >= scalar( @$symbolset )) ) { my @stdset = (0..9, 'a'..'z', 'A'..'Z'); $symbolset = \@stdset; } my $randstr = join '', map @$symbolset[rand @$symbolset], 0..($strlen-1); return $randstr; } END {} 1; __END__ # vim:ts=2:sw=2:expandtab:shiftwidth=2:syntax:paste goto-common/goto-support.lib0000644000175000017500000002464211401404140016005 0ustar benoitbenoit#!/bin/sh ############################################################################### # GOsa agent library # ############################################################################### SSH='ssh -o "StrictHostKeyChecking=no" -o "UserKnownHostsFile /dev/null" -o "BatchMode yes" ' GOTO_SYSCFG="/etc/sysconfig" GOTO_ERROR_STR="" GOTO_LDIF="/tmp/upload.ldif" # Source ldap-info, if available if [ -r /etc/ldap/ldap-shell.conf ]; then . /etc/ldap/ldap-shell.conf [ -f /etc/ldap/ldap-offline.conf ] && . /etc/ldap/ldap-offline.conf else # Fallback for non ldap2base config for config in $LDAPCONF /etc/*ldap/ldap.conf /etc/ldap.conf; do # Not readable? Continue [ ! -r $config ] && continue # Extract LDAP_BASE LDAP_BASE=$(sed -ne 's/^BASE[\t ]\+\(.\+\)[[\t ]*$/\1/p' $config) # Break, if found [ "x" != "x$LDAP_BASE" ] && break done fi if [ "x" = "x$LDAP_BASE" ]; then eval_gettext "No readable LDAP information - LDAP functions may fail!" fi set_dir_sysconfig() { GOTO_SYSCFG=$1 } get_fqdn_from_ip() { v=$(host -i $1); w=${v##*[ ]} echo ${w%%.*} | grep -q 'NX' if [ $? -eq 0 ]; then echo "unknown" else echo "$v" | grep -q ';;' if [ $? -eq 0 ]; then if [ -n "$HOSTNAME" ]; then echo "$HOSTNAME" else echo "unknown" fi else echo ${w%.*} fi fi } get_hostname_from_ip() { FQDN=$(get_fqdn_from_ip $1) if [ "unknown" != "${FQDN}" ]; then echo "${FQDN%%.*}" else echo "${FQDN}" fi } get_hostname_from_display() { if [ -n "$DISPLAY" ]; then HOST=${DISPLAY%%:*} NUMBER=${DISPLAY##*:} # IP addresses are not supported here echo $HOST | grep -q '^[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*$' if [ $? -ne 0 ]; then echo ${DISPLAY%%.*} else get_hostname_from_ip $HOST fi else echo "unknown" fi } kill_user_processes() { # don't let root do this if [ "$USER" = "root" -o "$(id -ru)" -eq 0 ]; then return fi # Preset, or load from file candidates="kdeinit\: soffice.bin mozilla-bin" [ -r /etc/goto/kill-process.conf ] && candidates=$(cat /etc/goto/kill-process.conf) # kill old existing user processes for process in $candidates; do ps -fu $USER | grep "$process" | grep -v 'kprogress' | awk ' FS=" " { system("kill "$2) } ' done # kill old existing user processes that didn't left us with SIGTERM for process in $candidates; do ps -fu $USER | grep "$process" | grep -v 'kprogress' | awk ' FS=" " { system("kill "$2) } ' done } fix_ldif_all() { (cat -; echo "bank") | awk ' /^[a-zA-Z]/ { if(line!=""){ print line } line = $0 } /^ / { line = line substr($0,2) } ' | while read line; do if echo $line | grep -q -e '^[[:alnum:]]*:: ' ; then attr=${line%%:*} arg=${line##*:} echo $attr: $(echo $arg|base64 -d) else echo $line fi done } ldap_count() { ldapsearch -x -LLL "$1" dn | grep '^dn:' | wc -l } decode_blob() { base64 -d > /tmp/agent-lib-decode.$$ file /tmp/agent-lib-decode.$$ 2>/dev/null| grep -qi 'text' [ $? -eq 0 ] && cat /tmp/agent-lib-decode.$$ | recode 'utf8..latin1' [ -f /tmp/agent-lib-decode.$$ ] && rm /tmp/agent-lib-decode.$$ } ldap_import() { for v in $(set grep ldap_import_ | cut -d= -f1); do unset $v; done vname_lastrun="" counter=0 > /tmp/agent-lib.$$ (ldapsearch -x -LLL $2 "$1" $3 2> /dev/null) | fix_ldif | sed 's/^\([^:]*\):\(.*\)$/\1="\2"/' | while read line; do vname=$(echo $line|cut -d= -f1) vvalue=$(echo $line|cut -d= -f2-) echo $line | grep -q '=": ' if [ $? -eq 0 ]; then vvalue=`echo $line|sed 's/^[^="]*=": //'|decode_blob` vvalue="$vvalue\"" else vvalue=`echo $line|sed 's/^[^="]*=" //'` fi if [ "$vname_lastrun" = "$vname" ]; then counter=$(( $counter + 1 )); else counter=0 vname_lastrun=$vname fi echo "ldap_import_$vname[$counter]=\"$vvalue" >> /tmp/agent-lib.$$ done eval $(cat /tmp/agent-lib.$$) rm /tmp/agent-lib.$$ } ldap_cat() { vname_lastrun="" counter=0 > /tmp/agent-lib.$$ (ldapsearch -x -LLL -b "$1" -s base 2> /dev/null) | fix_ldif | sed 's/^\([^:]*\):\(.*\)$/\1="\2"/' | while read line; do vname=$(echo $line|cut -d= -f1) vvalue=$(echo $line|cut -d= -f2-) echo $line | grep -q '=": ' if [ $? -eq 0 ]; then vvalue=`echo $line|sed 's/^[^="]*=": //'|decode_blob` vvalue="$vvalue\"" else vvalue=`echo $line|sed 's/^[^="]*=" //'` fi if [ "$vname_lastrun" = "$vname" ]; then counter=$(( $counter + 1 )); else counter=0 vname_lastrun=$vname fi echo "ldap_import_$vname[$counter]=\"$vvalue" >> /tmp/agent-lib.$$ done eval $(cat /tmp/agent-lib.$$) rm /tmp/agent-lib.$$ } ldap_get_group_membership_of() { ldapsearch -x -LLL "(&$UNIT_TAG_FILTER(memberUid=$1))" \ cn 2> /dev/null | fix_ldif | awk '/^cn: / {print $2}' } ldap_get_home_of() { ldapsearch -x -LLL "(&$UNIT_TAG_FILTER(uid=$1))" homeDirectory | fix_ldif | \ awk '/^homeDirectory:/ {print $2}' | sed -e "s/\(.*\)\/$/\1/g" } ldap_get_kiosk_profile_of() { ldap_get_object -user="$1" -enctrigger=none -format=v -filter="$UNIT_TAG_FILTER" gotoKioskProfile } ldap_get_profilequota_of() { ldap_get_object -user="$1" -enctrigger=none -format=v -filter="$UNIT_TAG_FILTER" gotoProfileQuota } ldap_get_profileserver_of() { ldap_get_object -user="$1" -enctrigger=none -format=v -filter="$UNIT_TAG_FILTER" gotoProfileServer } ldap_get_login_scripts_of() { ldap_get_object -user="$1" -filter="$UNIT_TAG_FILTER" -enctrigger=none \ -format=v -sort=precedence @gotoLogonScript } ldap_user_has_profile() { ldap_get_profileserver_of "$1" | grep -q .. } ########################################################################## # # ldap_get_user_shares_of: Liefert Shares des Benutzers # (ueber Benutzerobjekt) # # Argument $1: UID des Benutzers # ########################################################################## ldap_get_user_shares_of() { ldapsearch -x -LLL "(&$UNIT_TAG_FILTER(uid=$1))" gotoShare | fix_ldif | \ grep "^gotoShare:" | sed 's/^gotoShare: //g' | LC_ALL=C sort | uniq } ########################################################################## # # ldap_get_shares_of: Liefert Shares des Benutzers # (ueber Benutzer und Gruppenobjekte) # # Argument $1: UID des Benutzers # ########################################################################## ldap_get_shares_of() { ldap_get_object -user="$1" -filter="$UNIT_TAG_FILTER" -enctrigger=none \ -format=v @gotoShare } ldap_get_appservers() { ldapsearch -x -LLL "(objectclass=goTerminalServer)" cn | fix_ldif | grep -w cn: |cut -d' ' -f 2 } translate() { # Look for translation while read line; do string="${line%%=*}" if [ "$string" = "$*" ]; then echo "${line##*=}" return fi done < /etc/goto/goto-locales.dat echo $* } show_progress() { # No translation available echo $PROGRESS $(translate "$*") } create_desktop_link() { echo "$gosaApplicationFlags" | grep -q "D" if [ $? -eq 0 ]; then [ "$DEBUG" = "YES" ] && echo "goto_setup: creating desktop link for application $application" 1>&2 ln -f -s ~/.local/share/applications/$cn.desktop ~/Desktop/. fi } create_menu_entry() { echo "$gosaApplicationFlags" | grep -q "M" if [ $? -eq 0 ]; then [ "$DEBUG" = "YES" ] && echo "goto_setup: creating menu link for application $application" 1>&2 cat << EOF > ~/.local/share/applications/$cn.desktop [Desktop Entry] Type=Application Encoding=UTF-8 Exec=$gosaApplicationExecute Name=$gosaApplicationName GenericName=$description Comment=$description Icon=$HOME/.kde/share/icons/${cn}.png Terminal=false Categories=$appcat EOF fi } delete_all_applinks() { list=`ldapsearch -x -LLL "objectClass=gosaApplication" cn | fix_ldif | awk '/^cn: / {print $2}'` for link in $list; do [ -f $HOME/Desktop/$link ] && rm -f $HOME/Desktop/$link [ -f $HOME/.kde/share/applnk/$link.desktop ] && rm -rf $HOME/.kde/share/applnk/$link.desktop done } terminal_load_hardware_profile() { echo -n > "${RAM}${GOTO_SYSCFG}/GOto" ldapsearch -x -LLL "(&(objectClass=goHard)(macAddress=$1))" 2> /dev/null | fix_ldif_all | sed -e 's/^\([^:]*\): \(.*\)$/\U\1\E="\2"/' -e 's/^GOTO//g' >> "${GOTO_SYSCFG}/GOto" # Get DN and load all parent defaults from tree current=$(grep "^DN=" ${GOTO_SYSCFG}/GOto|sed 's/\"//g;s/, /,/g;s/^.*,ou=\(workstations|terminals\),ou=systems,//g') self=$(grep "^DN=" ${GOTO_SYSCFG}/GOto|sed 's/DN="*\([^"]*\)"*$/\1/g;s/, /,/g') # Load potential object group entries ldapsearch -x -LLL "(&(objectClass=gosaGroupOfNames)(|(gosaGroupObjects=[T])(gosaGroupObjects=[S])(gosaGroupObjects=[W]))(member=$self))" 2> /dev/null | fix_ldif_all | sed -e 's/^\([^:]*\): \(.*\)$/\U\1\E="\2"/' -e 's/^GOTO//g' >> "${GOTO_SYSCFG}/GOto" # Reverse sysconfig/GOto tac "${GOTO_SYSCFG}/GOto" > /tmp/GOto.tmp cat /tmp/GOto.tmp > "${GOTO_SYSCFG}/GOto" rm /tmp/GOto.tmp } terminal_has_hardware_profile() { # Do we have a configuration? terminal_load_hardware_profile $1 grep -v "cn=wdefault," "${GOTO_SYSCFG}/GOto" | grep -q "DN=" } terminal_do_softupdate() { terminal_load_hardware_profile $1 grep -q -i '^FAISTATE=.scheduledupdate' "${GOTO_SYSCFG}/GOto" } terminal_activated() { ldapsearch -x -LLL "(&(objectClass=goHard)(macAddress=$1)(gotoMode=active))" gotoMode | grep -q active } terminal_reboot_needed() { if ldapsearch -x -LLL "(&(objectClass=gotoTerminal)(macAddress=$1)(gotoMode=active))" gotoMode | grep -q active; then if [ -f /.THIS_IS_THE_FAI_NFSROOT ]; then return 0 fi fi # Also restart, if we're not in LDAP anymore - i.e. in case of OPSI hosts if ! ldapsearch -x -LLL "macAddress=$1" dn | grep -q ^dn:; then return 0 fi return 1 } ldap_init() { echo "Warning: use of obsolete function ldap_init()!"; } dprint() { if [ "$DEBUG" = "YES" ]; then echo "goto-umount-shares: $*" fi } # $1 = variable name # $2 = LDIF line decode_base64() { if echo "$2" | grep -iq '^[A-Za-z0-9]\+::'; then dec_res=$(echo $2 | cut -d\ -f2- | base64 -d) else dec_res=$(echo $2 | cut -d\ -f2-) fi eval "$1=\"$dec_res\"" } # vim:filetype=sh goto-common/ldap_get_object.examples0000644000175000017500000001151111346132401017475 0ustar benoitbenoitUSAGE des Programms ausgeben ldap_get_object Alle Attribute auflisten, die Benutzer $USER gesetzt bekommt, entweder durch seinen eigenen Knoten oder durch POSIX-Gruppen/Objekgruppen in denen er Mitglied ist oder durch Objekgruppen, die POSIX-Gruppen enthalten, in denen er Mitglied ist. ldap_get_object -user=$USER Um Herauszufinden, woher einzelne Attribute kommen, kann der -debug Switch übergeben werden. Damit gibt das Programm vor dem Endresultat alle Knoten aus, aus denen Attribute gezogen werden. ldap_get_object -user=$USER -debug Alle Attribute auflisten, die das System $HOSTNAME gesetzt bekommt, entweder durch seinen eigenen Knoten oder durch Objektgruppen, in denen es Mitglied ist. (Anmerkung: Der Switch -object erwartet ein Paar objectClass/cn oder objectClass/ou) ./ldap_get_object -object=gotoWorkstation/$HOSTNAME Alle Attribute auflisten, die jemand bekommt, wenn man ihn in die POSIX-Gruppe "camera" steckt, entweder durch den Knoten der Gruppe selbst oder durch Objektgruppen, die die Gruppe "camera" enthalten. Da es mehrere "camera" Gruppen gibt müssen wir anhand des gosaUnitTag filtern. ./ldap_get_object -object=posixGroup/camera -filter="gosaUnitTag=1152296234058713500" Alle Attribute auflisten, die der Benutzer $USER bekommt und die im Namen irgendwo "uid" enthalten. Anmerkung: Da dies auch Attribute listet, die der Benutzer über Gruppen bekommt, listet dieser Befehl auch alle Personen auf (memberUid), die mindestens eine Gruppe gemeinsam haben mit $USER. ldap_get_object -user=$USER "@.*uid.*" Alle mit der Profilsync im Zusammenhang stehenden Attribute ausgeben, die von irgendeinem Knoten auf $USER potentiell Einfluss haben könnten. Anmerkung: Das @ vor dem regulären[B Ausdruck sagt ldap_get_object, dass es alle Attributwerte ausgeben soll, d.h. wenn der Benutzer das Attribut gotoprofileflags sowohl durch seinen eigenen Knoten als auch durch eine Objekgruppe gesetzt bekommt, so werden 2 Werte aufgelistet (jedoch nur wenn sie verschieden sind). ldap_get_object -user=$USER "@gotoprofile.*" Die mit der Profilsync im Zusammenhang stehenden Attribute ausgeben, die effektiv für den Benutzer gültig sind. Der kleine Unterschied zum vorigen Befehl ist das Fehlen des @. Ohne das @ wird die auch in den goto-agents Skripten implementierte Konfliktauflösung verwendet, nämlich dass ein Attribut im Knoten des Benutzers Vorrang hat vor einem Attribut aus einer POSIX-Gruppe, das wiederum Vorrang hat vor einem Attribut aus einer Objektgruppe, die $USER enthält, was wiederum Vorrang hat vor einem Attribut aus einer Objektgruppe, die eine POSIX-Gruppe enthält, die den Benutzer enthält. Hinweis: Sollte der Benutzer das selbe Attribut aus 2 Quellen gleicher Präzedenz bekommen (typischer Konfigurationsfehler), so gibt das Skript eine Warnung aus. Dies ist sehr nützlich zum Debuggen des Problems "Aber ich habe hier bei der Gruppe doch ... eingestellt. Wieso greift das nicht?" ldap_get_object -user=$USER "gotoprofile.*" Das Attribut hobjwt dekodiert ausgeben. Per Default gibt ldap_get_object alle Attributwerte, die Steuerzeichen enthalten (d.h. ASCII-Code <32) Base64-kodiert aus. Über -enctrigger=none lässt sich die Kodierung komplett abschalten. Ein fix_ldif muss mit ldap_get_object nie verwendet werden. Anmerkung: -enctrigger erwartet einen regulären Ausdruck (oder none). Wenn irgenein Teil eines Attributswertes darauf passt, so wird Base64-Kodierung verwendet. ldap_get_object -user=$USER -enctrigger=none "hobjwt" Alle Attribute von $USER Base64-kodiert ausgeben. Anmerkung: -enctrigger erwartet einen regulären Ausdruck (oder none). Wenn irgendein Teil eines Attributswertes darauf passt, so wird Base64-Kodierung verwendet. ldap_get_object -user=$USER -enctrigger="." Den effektiv gültigen Profilserver ausgeben ohne vorangestellten Attributnamen und unabhängig vom Wert ohne Base64-Kodierung. (z.B. nützlich für die Weiterverarbeitung in Shell-Skripten, wo es einem die Verwendung von awk zum Herausgreifen des zweiten Feldes spart). ldap_get_object -format=v -enctrigger=none -user=$USER "gotoprofileserver" Alle POSIX-Gruppen (samt all ihrer Attribute) ausgeben. ldap_get_object -object=organizationalUnit/groups \ -filter="gosaUnitTag=1152296234058713500" \ -subquery="objectClass=posixGroup" Alle Gruppen ausgeben (POSIX und Objektgruppen) samt ihrer Attribute. ldap_get_object -object=organizationalUnit/groups \ -filter="gosaUnitTag=1152296234058713500" \ -subquery="objectClass=*" Alle Systeme ausgeben (samt all ihrer Attribute) ./ldap_get_object -object=organizationalUnit/systems \ -filter="gosaUnitTag=1152296234058713500" \ -subquery="objectClass=*" Auf BC 2.0 die Menüstruktur ausgeben, die der Benuter $USER für das Release halut/2.0.0beta1 bekommt: ldap_get_object -user=$USER -subquery="objectClass=gotoMenuEntry" "@halut/2.0.0beta1/.*" goto-common/GOtoLDAP.10000644000175000017500000003355111401404140014225 0ustar benoitbenoit.\" Automatically generated by Pod::Man 2.1801 (Pod::Simple 3.07) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is turned on, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .ie \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . nr % 0 . rr F .\} .el \{\ . de IX .. .\} .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "LDAP 3" .TH LDAP 3 "2010-03-26" "perl v5.10.0" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" GOto::LDAP \- Support library for goto\-* scripts to access LDAP .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 2 \& use GOto::Common qw(:ldap); \& use GOto::LDAP qw(ldap_get_object); \& \& my $ldapinfo = goto_ldap_parse_config_ex(); #ref to hash \& my ($ldapbase,$ldapuris) = ($ldapinfo\->{"LDAP_BASE"}, $ldapinfo\->{"LDAP_URIS"}); \& \& my $ldap = Net::LDAP\->new( $ldapuris, timeout => $timeout ) or die; \& $ldap\->bind() ; # anonymous bind \& \& # list context \& my @results = ldap_get_object(ldap => $ldap, \& basedn => $ldapbase, \& user => $user, \& timeout => $timeout, \& filter => $filter, \& debug => $debug, \& objectClass => $objectClass, \& cnou => $cn, \& subquery => $subquery, \& sublevel => $sublevel, \& subconflict => $subconflict, \& attributeSelectionRegexes => \e@attributeSelectionRegexes, \& enctrigger => $enctrigger, \& format => $format, \& dups => $dups, \& mergeResults => $mergeResults \& ); \& \& @results or die; \& \& # scalar context \& my $result = ldap_get_object(...); \& $result or die; .Ve .ie n .SH "DESCRIPTION of ""ldap_get_object""" .el .SH "DESCRIPTION of \f(CWldap_get_object\fP" .IX Header "DESCRIPTION of ldap_get_object" \&\f(CW\*(C`ldap_get_object()\*(C'\fR reads information about an object (usually a user, but can also be a workstation, a \s-1POSIX\s0 group,...) from \s-1LDAP\s0. \f(CW\*(C`ldap_get_object()\*(C'\fR understands gosaGroupOfNames and posixGroups and will not only return properties of the queried object itself but also properties inherited from groups of both types. .SH "PARAMETERS" .IX Header "PARAMETERS" .IP "\fBldap\fR" 4 .IX Item "ldap" An object of type Net::LDAP that is already bound. Required. .IP "\fBbasedn\fR" 4 .IX Item "basedn" The base \s-1DN\s0 to use for all searches. Required. .IP "\fBuser\fR/\fBcnou\fR and \fBobjectClass\fR" 4 .IX Item "user/cnou and objectClass" You must pass either \f(CW\*(C`user\*(C'\fR or \f(CW\*(C`cnou\*(C'\fR. If you pass \f(CW\*(C`user\*(C'\fR, \f(CW\*(C`objectClass\*(C'\fR is ignored and \f(CW\*(C`ldap_get_object()\*(C'\fR will search for an object with \f(CW\*(C`objectClass=posixAccount\*(C'\fR and \f(CW\*(C`uid\*(C'\fR equal to the value passed as \f(CW\*(C`user\*(C'\fR. .Sp If you pass \f(CW\*(C`cnou\*(C'\fR, then you must also pass \f(CW\*(C`objectClass\*(C'\fR and \f(CW\*(C`ldap_get_object()\*(C'\fR will search for an object with the given \f(CW\*(C`objectClass\*(C'\fR and a \f(CW\*(C`cn\*(C'\fR equal to the value passed as \f(CW\*(C`cnou\*(C'\fR. If no such object is found, it will attempt to find an object with the given \f(CW\*(C`objectClass\*(C'\fR and \&\f(CW\*(C`ou\*(C'\fR equal to the value of \f(CW\*(C`cnou\*(C'\fR. .IP "\fBattributeSelectionRegexes\fR and \fB\s-1CONFLICT\s0 \s-1RESOLUTION\s0\fR" 4 .IX Item "attributeSelectionRegexes and CONFLICT RESOLUTION" A reference to a an array of regular expressions (as strings) that select the attributes to be returned and determines how to proceed in case there are multiple sources for an attribute (e.g. the user's posixAccount node and a posixGroup the user is a member of). .Sp Each regex selects all attributes with matching names. .Sp If the regex starts with the character \f(CW\*(C`@\*(C'\fR (which is ignored for the matching), then attribute values from different sources will be merged (i.e. the result will include all values). .Sp If attributeRegex does \s-1NOT\s0 start with \f(CW\*(C`@\*(C'\fR, then an attribute from the queried object's own node beats a posix group, which beats an object group (=gosaGroupOfNames) that includes the object directly which beats an object group that contains a posix group containing the object. Object groups containing other object groups are not supported by GOsa, so this case cannot occur. .Sp If 2 sources with the same precedence (e.g. 2 posix groups) provide an attribute of the same name, selected by a regex that doesn not start with \f(CW\*(C`@\*(C'\fR, then a \s-1WARNING\s0 is signalled and the program picks one of the conflicting attributes. .Sp If multiple attribute regexes match the same attribute, the 1st matching attribute regex's presence or absence of \f(CW\*(C`@\*(C'\fR determines conflict resolution. .Sp Matching is always performed against the \fIcomplete\fR attribute name as if the regex had been enclosed in \f(CW\*(C`^...$\*(C'\fR, i.e. an attribute regex \f(CW\*(C`name\*(C'\fR will \s-1NOT\s0 match an attribute called \f(CW\*(C`surname\*(C'\fR. Neither will the regex \&\f(CW\*(C`sur\*(C'\fR. .Sp Matching is always performed case-insensitive. .Sp If the parameter \f(CW\*(C`attributeSelectionRegexes\*(C'\fR is not passed, it defaults to \f(CW\*(C`@.*\*(C'\fR. .IP "\fBmergeResults\fR" 4 .IX Item "mergeResults" If \f(CW\*(C`mergeResults\*(C'\fR is \f(CW\*(C`false\*(C'\fR and \f(CW\*(C`ldap_get_object()\*(C'\fR is evaluated in list context, then it will return a list of Net::LDAP::Entry objects where each object represents the attributes on a given precedence level. The first entry gives the attributes that come from the own node, i.e. those with the highest precedence. .Sp Attributes selected with a non\-\f(CW\*(C`@\*(C'\fR regex, i.e. those for which only one source is permitted, are always found in the first entry and only there. For these attributes all conflicting values from lower precedence levels are always discarded, so \f(CW\*(C`mergeResults=false\*(C'\fR only makes sense when requesting merged attributes via \f(CW\*(C`@\*(C'\fR. .Sp If \f(CW\*(C`mergeResults\*(C'\fR is \f(CW\*(C`true\*(C'\fR (the default) or if \f(CW\*(C`ldap_get_object()\*(C'\fR is evaluated in scalar context, then only one Net::LDAP::Entry will be returned that contains all of the requested attributes. .IP "\fBdups\fR" 4 .IX Item "dups" Net::LDAP::Entry does not perform duplicate removal on its attribute value lists by default. If \f(CW\*(C`dups=true\*(C'\fR (the default), the results returned from \f(CW\*(C`ldap_get_object()\*(C'\fR may contain attributes that contain duplicate entries. If this would confuse your code, pass \f(CW\*(C`dups=false\*(C'\fR and duplicate values will be eliminated (at the cost of a few \s-1CPU\s0 cycles). .IP "\fBtimeout\fR" 4 .IX Item "timeout" If \f(CW\*(C`timeout\*(C'\fR is passed, \s-1LDAP\s0 requests will use a timeout of this number of seconds. Note that this does \fInot\fR mean that \f(CW\*(C`ldap_get_object\*(C'\fR will finish within this time limit, since several \s-1LDAP\s0 requests may be involved. .Sp Default timeout is 10s. .IP "\fBfilter\fR" 4 .IX Item "filter" \&\f(CW\*(C`filter\*(C'\fR is an LDAP-Expression that will be ANDed with all user/object/group searches done by this program. .Sp Use this to filter by \f(CW\*(C`gosaUnitTag\*(C'\fR. .IP "\fBsubquery\fR" 4 .IX Item "subquery" The \f(CW\*(C`subquery\*(C'\fR parameter is an \s-1LDAP\s0 filter such as \f(CW\*(C`objectClass=gotoMenuItem\*(C'\fR. For the subtrees rooted at the object's own node and at all of its containing groups' nodes, an \s-1LDAP\s0 query using this filter will be done. The attributes of all of the objects resulting from these queries will be treated as if they were attributes of the node at which the search was rooted. The names of these pseudo-attributes have the form \f(CW\*(C`foo/bar/attr\*(C'\fR. .IP "\fBsublevel\fR" 4 .IX Item "sublevel" \&\f(CW\*(C`sublevel\*(C'\fR specifies the maximum number of slashes the pseudo-attribute names will contain. If the complete name of a pseudo-attribute has more slashes than the given number, the name will be shortened to the longest suffix that contains this many slashes. Specifying a \f(CW\*(C`sublevel\*(C'\fR of 0 will effectively merge all subquery nodes with the user/object/group node so that in the end result their attributes are indistinguishable from those of the user/object/group node. .Sp Default \f(CW\*(C`sublevel\*(C'\fR is 9999. .Sp Note: attribute regex matching is performed on the full name with all slashes. .IP "\fBsubconflict\fR" 4 .IX Item "subconflict" \&\f(CW\*(C`subconflict\*(C'\fR is a number that determines when 2 pseudo-attributes are treated as being in conflict with each other. 2 pseudo-attributes are treated as conflicting if the results of removing the shortest suffixes containing \&\f(CW\*(C`subconflict\*(C'\fR slashes from their names (shortened according to \f(CW\*(C`sublevel\*(C'\fR) are identical. E.g. with \f(CW\*(C`subconflict=0\*(C'\fR the pseudo-attributes \f(CW\*(C`foo/bar\*(C'\fR and \f(CW\*(C`foo/zoo\*(C'\fR are not conflicting, whereas with \f(CW\*(C`subconflict=1\*(C'\fR they are. Default \f(CW\*(C`subconflict\*(C'\fR is 1. .IP "\fBdebug\fR" 4 .IX Item "debug" If \f(CW\*(C`debug\*(C'\fR is \f(CW\*(C`true\*(C'\fR, then lots of debug output (mostly all of the nodes considered in constructing the result) is printed to stdout. .IP "\fBenctrigger\fR" 4 .IX Item "enctrigger" This parameter is only relevant when \f(CW\*(C`debug\*(C'\fR is \f(CW\*(C`true\*(C'\fR. It affects the way, attribute values are printed. If \f(CW\*(C`enctrigger\*(C'\fR is passed, it is interpreted as a regular expression and all DNs and attribute values will be tested against this regex. Whenever a value matches, it will be output base64 encoded. Matching is performed case-sensitive and unless ^ and $ are used in the regex, matching substrings are enough to trigger encoding. .Sp If no \f(CW\*(C`enctrigger\*(C'\fR is specified, the default \f(CW\*(C`[\ex00\-\ex1f]\*(C'\fR is used (i.e. base64 encoding will be used whenever a value contains a control character). If you pass \f(CW\*(C`enctrigger=none\*(C'\fR, encoding will be completely disabled. .IP "\fBformat\fR" 4 .IX Item "format" This parameter is only relevant when \f(CW\*(C`debug\*(C'\fR is \f(CW\*(C`true\*(C'\fR. It affects the way, attribute values are printed. Format \f(CW"a:v"\fR means to print \&\f(CW\*(C`attributeName: value\*(C'\fR pairs. Format \f(CW\*(C`v\*(C'\fR means to print the values only. goto-common/fix_ldif0000755000175000017500000000075511346132401014352 0ustar benoitbenoit#!/usr/bin/perl -w use strict; use MIME::Base64; my $buffer= ""; while () { chomp; if ($_ =~ /^[a-zA-Z0-9]/) { if ($buffer) { if ($buffer =~ /^dn::/){ $buffer =~ /^([^:]+):: (.*)$/; $buffer= "$1: ".decode_base64($2); } print $buffer."\n"; } $buffer= $_; next; } if ($_ =~ /^ (.*)$/) { $buffer.= $1; next; } } if ($buffer) { if ($buffer =~ /^dn::/){ $buffer =~ /^([^:]+):: (.*)$/; $buffer= "$1: ".decode_base64($2); } print $buffer."\n"; } goto-common/fr-goto-common.mo0000644000175000017500000000114011401403637016031 0ustar benoitbenoitÞ•,<P7Q‹‰JNo readable LDAP information - LDAP functions may fail!Project-Id-Version: goto-common Report-Msgid-Bugs-To: POT-Creation-Date: 2007-09-12 19:10+0200 PO-Revision-Date: 2007-09-12 19:32+0200 Last-Translator: Benoit Mortier Language-Team: Français MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit X-Generator: KBabel 1.11.4 Plural-Forms: nplurals=2; plural=(n > 1); Pas d'informations ldap accessibles - Les fonctions LDAP peuvent échouer!goto-common/fr-goto-common.po0000644000175000017500000000153611346132401016041 0ustar benoitbenoit# translation of goto-common.po to Français # Copyright (C) 2007 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the goto-common package. # # Benoit Mortier , 2007. msgid "" msgstr "" "Project-Id-Version: goto-common\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2007-09-12 19:10+0200\n" "PO-Revision-Date: 2007-09-12 19:32+0200\n" "Last-Translator: Benoit Mortier \n" "Language-Team: Français \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "X-Generator: KBabel 1.11.4\n" "Plural-Forms: nplurals=2; plural=(n > 1);\n" #: goto-support.lib:29 msgid "No readable LDAP information - LDAP functions may fail!" msgstr "Pas d'informations ldap accessibles - Les fonctions LDAP peuvent échouer!" goto-common/de-goto-common.mo0000644000175000017500000000100711401403630016005 0ustar benoitbenoitÞ•,<P7Q=‰?ÇNo readable LDAP information - LDAP functions may fail!Project-Id-Version: goto-common Report-Msgid-Bugs-To: POT-Creation-Date: 2007-09-12 19:10+0200 PO-Revision-Date: 2007-09-12 19:32+0200 Last-Translator: Cajus Pollmeier Language-Team: Deutsch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Keine LDAP-Informationen - LDAP-Funktionen werden fehlschlagen!goto-common/de-goto-common.po0000644000175000017500000000136411346132401016021 0ustar benoitbenoit# translation of goto-common.po to Deutsch # Copyright (C) 2007 THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the goto-common package. # Cajus Pollmeier , 2007. # msgid "" msgstr "" "Project-Id-Version: goto-common\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2007-09-12 19:10+0200\n" "PO-Revision-Date: 2007-09-12 19:32+0200\n" "Last-Translator: Cajus Pollmeier \n" "Language-Team: Deutsch \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" #: goto-support.lib:29 msgid "No readable LDAP information - LDAP functions may fail!" msgstr "Keine LDAP-Informationen - LDAP-Funktionen werden fehlschlagen!" goto-common/ldap_get_object0000755000175000017500000002303711346132401015671 0ustar benoitbenoit#!/usr/bin/perl -l -s # Copyright (c) 2008 Landeshauptstadt München # # Author: Matthias S. Benkmann # # 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, either version 2 of the License, or # (at your option) any later version. # # 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, see . use strict; use warnings; use lib ("/usr/lib/goto"); use Net::LDAP; use Net::LDAP::Util qw(escape_filter_value ldap_explode_dn); use GOto::LDAP qw(ldap_get_object printEntry printAttribute); use GOto::Common qw(:ldap); { # main() our ($user, $timeout, $filter, $debug, $object, $enctrigger, $format, $subquery, $sublevel, $subconflict, $sort); my $USAGE = "USAGE: ldap_get_object -debug -user= -object=/ -filter= -timeout= -subquery= -sublevel= -subconflict= -enctrigger= -format=a:v|v -sort=alpha|precedence attributeRegex [attributeRegex ...] Primary usage: Searches the LDAP directory for information about the user identified by (defaults to the environment variable \$USER). Information may come from the user's own node, a posix group the user belongs to, an object group the user belongs to or an object group that includes a posix group that the user belongs to. Each attributeRegex is a regular expression that selects all attributes with matching names for output. The 1st character of attributeRegex determines what happens if different nodes (e.g. the user's posixAccount and a posixGroup) provide an attribute with the same name. If attributeRegex starts with \@, then the attributes will be merged (i.e. the result will include all values). If attributeRegex does NOT start with \@, then an attribute from the user's posixAccount node beats a posix group, which beats an object group that includes the user which beats an object group that contains a posix group. This determination is done individually for each of the selected attributes, so the output of this program may be a mixture of information from different sources. If 2 sources with the same precedence (e.g. 2 posix groups) provide an attribute of the same name, selected by an attributeRegex that doesn't start with \@, a WARNING is signalled and the program picks one of the conflicting attributes. If multiple attributeRegexes match the same attribute, the 1st matching attributeRegex determines conflict resolution. If no attributeRegex is specified, all attributes will be merged and output. Alternative usage: Instead of searching for user information, you can pass -object=/ and the program will give information on the object with the given object class and the given CN or OU (if no object with the CN exists). attributeRegexes are always matched against the complete attribute name, i.e. an attributeRegex \"name\" will NOT match an attribute \"surname\". Matching is always performed case-insensitive. If there is more than 1 posixAccount node for the given user id, the program will exit with an error. If -timeout is passed, LDAP requests will use a timeout of seconds. Note that this does *not* mean that ldap_get_object will finish within this time limit, since several LDAP requests may be involved. Default timeout is 10s. -filter is an LDAP-Expression that will be ANDed with all user/object/group searches done by this program (use this to select by gosaUnitTag). The -subquery parameter allows treating the contents of subtrees of the user/object/group nodes as if they were attributes of the node itself. The names of these pseudo-attributes have the form \"foo/bar/attr\". The (e.g. \"objectClass=foo\") selects the sub-tree nodes whose attributes should be pulled in. -sublevel specifies the maximum number of slashes the pseudo-attribute names will contain. If the complete name of a pseudo-attribute has more slashes than the name will be shortened to the longest suffix that contains slashes. Specifying -sublevel=0 will effectively merge all subquery nodes with the user/object/group node so that in the end result their attributes are indistinguishable from those of the user/object/group node. Default -sublevel is 9999. Note: attributeRegex matching is performed on the full name with all slashes. -subconflict determines when 2 pseudo-attributes are treated as being in conflict with each other. 2 pseudo-attributes are treated as conflicting if the results of removing the shortest suffixes containing slashes from their names (shortened according to -sublevel) are identical. E.g. with -subconflict=0 the pseudo-attributes \"foo/bar\" and \"foo/bla\" are not conflicting, whereas with -subconflict=1 they are. Default -subconflict is 1. If -enctrigger is set, all DNs and attribute values will be tested against the given . Whenever a value matches the it will be output base64 encoded. Matching is performed case-sensitive and unless ^ and \$ are used in the regex, matching substrings are enough to trigger encoding. If no -enctrigger is specified, the default \"[\\x00-\\x1f]\" is used. If you pass -enctrigger=none, encoding will be completely disabled. -format specifies the output format. Format \"a:v\" means to print \"attributeName: value\" pairs. Format \"v\" means to print the values only. -sort allows you to change the order in which attributes are printed. With -sort=alpha (default) all attributes are printed in alphabetical order of the attribute names. With -sort=precedence attributes from sources with lower precedence will be printed before those with higher precedence. Within each group, alphabetical order is used. The exception is the DN which is always first (if selected at all). -sort=precedence does not affect attributes that are not merged (because only one value is printed for those). If an attribute has multiple values (from the same source), they will all be output in alphabetical order. Unless -sort=precedence is selected, duplicate values will be printed only once. "; if (!defined($user) and !defined($object) and !defined($enctrigger) and !defined($timeout) and !defined($filter) and !defined($sublevel) and !defined($subconflict) and !defined($subquery) and (scalar(@ARGV) == 0)) { print $USAGE; exit 1; } if (not defined($user) and not defined($object)) { $user = $ENV{"USER"}; (defined($user) and $user ne "") or error("Please pass -user=... or -object=... or set \$USER to a non-empty string"); } defined($enctrigger) or $enctrigger="[\x00-\x1f]"; #" $enctrigger eq "none" and $enctrigger="^\x00\$"; if (defined($format)) { if ($format ne "a:v" and $format ne "v") { error("Illegal -format: $format"); } } else { $format="a:v"; } my $mergeResults = 1; if (defined($sort) and not $sort eq "alpha") { if ($sort eq "precedence") { $mergeResults = 0; } else { error("Illegal -sort: $sort"); } } my ($objectClass, $cn); if (defined($object)) { ($objectClass, $cn) = ($object =~ m(^([^/]*)/(.*))); if (!defined($objectClass) or !defined($cn)) { error("Illegal -object= parameter"); } } my @attributeSelectionRegexes = @ARGV; scalar(@attributeSelectionRegexes) == 0 and @attributeSelectionRegexes = ("\@.*"); my ($ldapbase,$ldapuris) = goto_ldap_parse_config(); # Note: $ldapuris is a reference to an array of URIs my $ldap = Net::LDAP->new( $ldapuris, timeout => $timeout ) or error("Could not connect to LDAP server!"); my $results = $ldap->bind() ; # anonymous bind my @results = ldap_get_object(ldap => $ldap, basedn => $ldapbase, user => $user, timeout => $timeout, filter => $filter, debug => $debug, objectClass => $objectClass, cnou => $cn, subquery => $subquery, sublevel => $sublevel, subconflict => $subconflict, attributeSelectionRegexes => \@attributeSelectionRegexes, enctrigger => $enctrigger, format => $format, dups => 1, # duplicate removal is done by printEntry() mergeResults => $mergeResults ); @results or exit 1; defined($debug) and print "x:========================== R E S U L T =========================="; # print DN if selected by a regex foreach my $rx (@attributeSelectionRegexes) { my $regex = $rx; # copy so that we don't change the original value if (substr($regex, 0, 1) eq "\@") { $regex = substr($regex,1); } $regex = "^" . $regex . "\$"; # always match complete string if ("dn" =~ m/$regex/) { my $dn = $results[0]->dn; defined($dn) or $dn = ""; printAttribute("dn", [$dn], $enctrigger, $format); last; } } # print the other attributes foreach my $entry (reverse @results) { printEntry($entry, \@attributeSelectionRegexes, $enctrigger, $format, 1); } $ldap->unbind(); } #main() sub error { print STDERR "ERROR: ", @_; exit 1 }