a63ae311eb877df398752163302845e08be4a6f0
[ira/wip.git] / examples / misc / adssearch.pl
1 #!/usr/bin/perl -w
2
3 # adssearch.pl  - query an Active Directory server and
4 #                 display objects in a human readable format
5 #
6 # Copyright (C) Guenther Deschner <gd@samba.org> 2003-2007
7 #
8 # TODO: add range retrieval
9 #       write sddl-converter, decode userParameters
10 #       apparently only win2k3 allows simple-binds with machine-accounts.
11 #       make sasl support independent from Authen::SASL::Cyrus v >0.11
12 use strict;
13
14 use Net::LDAP;
15 use Net::LDAP::Control;
16 use Net::LDAP::Constant qw(LDAP_REFERRAL);
17 use Convert::ASN1;
18 use Time::Local;
19 use POSIX qw(strftime);
20 use Getopt::Long;
21
22 my $have_sasl;
23 my $works_sasl;
24 my $pref_version;
25 BEGIN {
26         my $class = 'Authen::SASL';
27         $pref_version = "0.32";
28         if ( eval "require $class;" ) {
29                 $have_sasl = 1;
30         }
31         if ( eval "Net::LDAP->VERSION($pref_version);" ) {
32                 $works_sasl = 1;
33         }
34 }
35
36 # users may set defaults here
37 my $base        = "";
38 my $binddn      = "";
39 my $password    = "";
40 my $server      = "";
41 my $rebind_url;
42
43
44 my $tdbdump     = "/usr/bin/tdbdump";
45 my $testparm    = "/usr/bin/testparm";
46 my $net         = "/usr/bin/net";
47 my $dig         = "/usr/bin/dig";
48 my $nmblookup   = "/usr/bin/nmblookup";
49 my $secrets_tdb = "/etc/samba/secrets.tdb";
50 my $klist       = "/usr/bin/klist";
51 my $kinit       = "/usr/bin/kinit";
52 my $workgroup   = "";
53 my $machine     = "";
54 my $realm       = "";
55
56 # parse input
57 my (
58         $opt_asq,
59         $opt_base, 
60         $opt_binddn,
61         $opt_debug,
62         $opt_display_extendeddn,
63         $opt_display_metadata,
64         $opt_display_raw,
65         $opt_domain_scope,
66         $opt_dump_rootdse,
67         $opt_dump_schema,
68         $opt_dump_wknguid,
69         $opt_fastbind,
70         $opt_help, 
71         $opt_host, 
72         $opt_machine,
73         $opt_notify, 
74         $opt_notify_nodiffs,
75         $opt_paging,
76         $opt_password,
77         $opt_port,
78         $opt_realm,
79         $opt_saslmech,
80         $opt_search_opt,
81         $opt_scope, 
82         $opt_simpleauth,
83         $opt_starttls,
84         $opt_user,
85         $opt_verbose,
86         $opt_workgroup,
87 );
88
89 GetOptions(
90         'asq=s'         => \$opt_asq,
91         'base|b=s'      => \$opt_base,
92         'D|DN=s'        => \$opt_binddn,
93         'debug=i'       => \$opt_debug,
94         'domain_scope'  => \$opt_domain_scope,
95         'extendeddn|e:i'        => \$opt_display_extendeddn,
96         'fastbind'      => \$opt_fastbind,
97         'help'          => \$opt_help,
98         'host|h=s'      => \$opt_host,
99         'machine|P'     => \$opt_machine,
100         'metadata|m'    => \$opt_display_metadata,
101         'nodiffs'       => \$opt_notify_nodiffs,
102         'notify|n'      => \$opt_notify,
103         'paging:i'      => \$opt_paging,
104         'password|w=s'  => \$opt_password,
105         'port=i'        => \$opt_port,
106         'rawdisplay'    => \$opt_display_raw,
107         'realm|R=s'     => \$opt_realm,
108         'rootDSE'       => \$opt_dump_rootdse,
109         'saslmech|Y=s'  => \$opt_saslmech,
110         'schema|c'      => \$opt_dump_schema,
111         'scope|s=s'     => \$opt_scope,
112         'searchopt:i'   => \$opt_search_opt,
113         'simpleauth|x'  => \$opt_simpleauth,
114         'tls|Z'         => \$opt_starttls,
115         'user|U=s'      => \$opt_user,
116         'verbose|v'     => \$opt_verbose,
117         'wknguid'       => \$opt_dump_wknguid,
118         'workgroup|k=s' => \$opt_workgroup,
119         );
120
121
122 if (!@ARGV && !$opt_dump_schema && !$opt_dump_rootdse && !$opt_notify || $opt_help) {
123         usage();
124         exit 1;
125 }
126
127 if ($opt_fastbind && !$opt_simpleauth) {
128         printf("LDAP fast bind can only be performed with simple binds\n");
129         exit 1;
130 }
131
132 if ($opt_notify) {
133         $opt_paging = undef;
134 }
135
136 # get the query
137 my $query       = shift;
138 my @attrs       = @ARGV;
139
140 # some global vars
141 my $filter = "";
142 my ($dse, $uri);
143 my ($attr, $value);
144 my (@ctrls, @ctrls_s);
145 my ($ctl_paged, $cookie);
146 my ($page_count, $total_entry_count);
147 my ($sasl_hd, $async_ldap_hd, $sync_ldap_hd);
148 my ($mesg, $usn);
149 my (%entry_store);
150 my $async_search;
151
152 # fixed values and vars
153 my $set         = "X";
154 my $unset       = "-";
155 my $tabsize     = "\t\t\t";
156
157 # get defaults
158 my $scope       = $opt_scope    || "sub"; 
159 my $port        = $opt_port;
160
161 my %ads_controls = (
162 "LDAP_SERVER_NOTIFICATION_OID"          => "1.2.840.113556.1.4.528",
163 "LDAP_SERVER_EXTENDED_DN_OID"           => "1.2.840.113556.1.4.529",
164 "LDAP_PAGED_RESULT_OID_STRING"          => "1.2.840.113556.1.4.319",
165 "LDAP_SERVER_SD_FLAGS_OID"              => "1.2.840.113556.1.4.801",
166 "LDAP_SERVER_SORT_OID"                  => "1.2.840.113556.1.4.473",
167 "LDAP_SERVER_RESP_SORT_OID"             => "1.2.840.113556.1.4.474",
168 "LDAP_CONTROL_VLVREQUEST"               => "2.16.840.1.113730.3.4.9",
169 "LDAP_CONTROL_VLVRESPONSE"              => "2.16.840.1.113730.3.4.10",
170 "LDAP_SERVER_RANGE_RETRIEVAL"           => "1.2.840.113556.1.4.802", #unsure
171 "LDAP_SERVER_SHOW_DELETED_OID"          => "1.2.840.113556.1.4.417",
172 "LDAP_SERVER_CROSSDOM_MOVE_TARGET_OID"  => "1.2.840.113556.1.4.521",
173 "LDAP_SERVER_LAZY_COMMIT_OID"           => "1.2.840.113556.1.4.619",
174 "LDAP_SERVER_TREE_DELETE_OID"           => "1.2.840.113556.1.4.805",
175 "LDAP_SERVER_DIRSYNC_OID"               => "1.2.840.113556.1.4.841",
176 "LDAP_SERVER_VERIFY_NAME_OID"           => "1.2.840.113556.1.4.1338",
177 "LDAP_SERVER_DOMAIN_SCOPE_OID"          => "1.2.840.113556.1.4.1339",
178 "LDAP_SERVER_SEARCH_OPTIONS_OID"        => "1.2.840.113556.1.4.1340",
179 "LDAP_SERVER_PERMISSIVE_MODIFY_OID"     => "1.2.840.113556.1.4.1413",
180 "LDAP_SERVER_ASQ_OID"                   => "1.2.840.113556.1.4.1504",
181 "NONE (Get stats control)"              => "1.2.840.113556.1.4.970",
182 "LDAP_SERVER_QUOTA_CONTROL_OID"         => "1.2.840.113556.1.4.1852",
183 "LDAP_SERVER_SHUTDOWN_NOTIFY_OID"       => "1.2.840.113556.1.4.1907",
184 );
185
186 my %ads_capabilities = (
187 "LDAP_CAP_ACTIVE_DIRECTORY_OID"         => "1.2.840.113556.1.4.800",
188 "LDAP_CAP_ACTIVE_DIRECTORY_V51_OID"     => "1.2.840.113556.1.4.1670",
189 "LDAP_CAP_ACTIVE_DIRECTORY_LDAP_INTEG_OID" => "1.2.840.113556.1.4.1791",
190 );
191
192 my %ads_extensions = (
193 "LDAP_START_TLS_OID"                    => "1.3.6.1.4.1.1466.20037",
194 "LDAP_TTL_EXTENDED_OP_OID"              => "1.3.6.1.4.1.1466.101.119.1",
195 "LDAP_SERVER_FAST_BIND_OID"             => "1.2.840.113556.1.4.1781", 
196 "NONE (TTL refresh extended op)"        => "1.3.6.1.4.1.1466.101.119.1",
197 );
198
199 my %ads_matching_rules = (
200 "LDAP_MATCHING_RULE_BIT_AND"            => "1.2.840.113556.1.4.803",
201 "LDAP_MATCHING_RULE_BIT_OR"             => "1.2.840.113556.1.4.804",
202 );
203
204 my %wknguids = (
205 "WELL_KNOWN_GUID_COMPUTERS"             => "AA312825768811D1ADED00C04FD8D5CD",
206 "WELL_KNOWN_GUID_DOMAIN_CONTROLLERS"    => "A361B2FFFFD211D1AA4B00C04FD7D83A",
207 "WELL_KNOWN_GUID_SYSTEM"                => "AB1D30F3768811D1ADED00C04FD8D5CD",
208 "WELL_KNOWN_GUID_USERS"                 => "A9D1CA15768811D1ADED00C04FD8D5CD",
209 );
210
211 my %ads_systemflags = (
212 "FLAG_DONT_REPLICATE"                   => 0x00000001,  # 1
213 "FLAG_REPLICATE_TO_GC"                  => 0x00000002,  # 2
214 "FLAG_ATTRIBUTE_CONSTRUCT"              => 0x00000004,  # 4
215 "FLAG_CATEGORY_1_OBJECT"                => 0x00000010,  # 16
216 "FLAG_DELETE_WITHOUT_TOMBSTONE"         => 0x02000000,  # 33554432
217 "FLAG_DOMAIN_DISALLOW_MOVE"             => 0x04000000,  # 67108864
218 "FLAG_DOMAIN_DISALLOW_RENAME"           => 0x08000000,  # 134217728
219 #"FLAG_CONFIG_CAN_MOVE_RESTRICTED"      => 0x10000000,  # 268435456     # only setable on creation
220 #"FLAG_CONFIG_CAN_MOVE"                 => 0x20000000,  # 536870912     # only setable on creation
221 #"FLAG_CONFIG_CAN_RENAME"               => 0x40000000,  # 1073741824    # only setable on creation
222 "FLAG_DISALLOW_DELETE"                  => 0x80000000,  # 2147483648
223 );
224
225 my %ads_mixed_domain = (
226 "NATIVE_LEVEL_DOMAIN"                   => 0,
227 "MIXED_LEVEL_DOMAIN"                    => 1,
228 );
229
230 my %ads_ds_func = (
231 "DS_BEHAVIOR_WIN2000"                   => 0,   # untested
232 "DS_BEHAVIOR_WIN2003"                   => 2,
233 );
234
235 my %ads_instance_type = (
236 "DS_INSTANCETYPE_IS_NC_HEAD"            => 0x1,
237 "IT_WRITE"                              => 0x4,
238 "IT_NC_ABOVE"                           => 0x8,
239 );
240
241 my %ads_uacc = (
242         "ACCOUNT_NEVER_EXPIRES"         => 0x000000, # 0 
243         "ACCOUNT_OK"                    => 0x800000, # 8388608
244         "ACCOUNT_LOCKED_OUT"            => 0x800010, # 8388624
245 );
246
247 my %ads_gpoptions = (
248         "GPOPTIONS_INHERIT"             => 0,
249         "GPOPTIONS_BLOCK_INHERITANCE"   => 1,
250 );
251
252 my %ads_gplink_opts = (
253         "GPLINK_OPT_NONE"               => 0,
254         "GPLINK_OPT_DISABLED"           => 1,
255         "GPLINK_OPT_ENFORCED"           => 2,
256 );
257
258 my %ads_gpflags = (
259         "GPFLAGS_ALL_ENABLED"                   => 0,
260         "GPFLAGS_USER_SETTINGS_DISABLED"        => 1,
261         "GPFLAGS_MACHINE_SETTINGS_DISABLED"     => 2,
262         "GPFLAGS_ALL_DISABLED"                  => 3,
263 );
264
265 my %ads_serverstate = (
266         "SERVER_ENABLED"                => 1,
267         "SERVER_DISABLED"               => 2,
268 );
269
270 my %ads_sdeffective = (
271         "OWNER_SECURITY_INFORMATION"    => 0x01,
272         "DACL_SECURITY_INFORMATION"     => 0x04,
273         "SACL_SECURITY_INFORMATION"     => 0x10,
274 );
275
276 my %ads_trustattrs = (
277         "TRUST_ATTRIBUTE_NON_TRANSITIVE"        => 1,
278         "TRUST_ATTRIBUTE_TREE_PARENT"           => 2,
279         "TRUST_ATTRIBUTE_TREE_ROOT"             => 3,
280         "TRUST_ATTRIBUTE_UPLEVEL_ONLY"          => 4,
281 );
282
283 my %ads_trustdirection = (
284         "TRUST_DIRECTION_INBOUND"               => 1,
285         "TRUST_DIRECTION_OUTBOUND"              => 2,
286         "TRUST_DIRECTION_BIDIRECTIONAL"         => 3,
287 );
288
289 my %ads_trusttype = (
290         "TRUST_TYPE_DOWNLEVEL"                  => 1,
291         "TRUST_TYPE_UPLEVEL"                    => 2,
292         "TRUST_TYPE_KERBEROS"                   => 3,
293         "TRUST_TYPE_DCE"                        => 4,
294 );
295
296 my %ads_pwdproperties = (
297         "DOMAIN_PASSWORD_COMPLEX"               => 1, 
298         "DOMAIN_PASSWORD_NO_ANON_CHANGE"        => 2, 
299         "DOMAIN_PASSWORD_NO_CLEAR_CHANGE"       => 4, 
300         "DOMAIN_LOCKOUT_ADMINS"                 => 8, 
301         "DOMAIN_PASSWORD_STORE_CLEARTEXT"       => 16, 
302         "DOMAIN_REFUSE_PASSWORD_CHANGE"         => 32,
303 );
304
305 my %ads_uascompat = (
306         "LANMAN_USER_ACCOUNT_SYSTEM_NOLIMITS"   => 0,
307         "LANMAN_USER_ACCOUNT_SYSTEM_COMPAT"     => 1,
308 );
309
310 my %ads_frstypes = (
311         "REPLICA_SET_SYSVOL"            => 2,   # unsure
312         "REPLICA_SET_DFS"               => 1,   # unsure
313         "REPLICA_SET_OTHER"             => 0,   # unsure
314 );
315
316 my %ads_gp_cse_extensions = (
317 "Administrative Templates Extension"    => "35378EAC-683F-11D2-A89A-00C04FBBCFA2",
318 "Disk Quotas"                           => "3610EDA5-77EF-11D2-8DC5-00C04FA31A66",
319 "EFS Recovery"                          => "B1BE8D72-6EAC-11D2-A4EA-00C04F79F83A",
320 "Folder Redirection"                    => "25537BA6-77A8-11D2-9B6C-0000F8080861",
321 "IP Security"                           => "E437BC1C-AA7D-11D2-A382-00C04F991E27",
322 "Internet Explorer Maintenance"         => "A2E30F80-D7DE-11d2-BBDE-00C04F86AE3B",
323 "QoS Packet Scheduler"                  => "426031c0-0b47-4852-b0ca-ac3d37bfcb39",
324 "Scripts"                               => "42B5FAAE-6536-11D2-AE5A-0000F87571E3",
325 "Security"                              => "827D319E-6EAC-11D2-A4EA-00C04F79F83A",
326 "Software Installation"                 => "C6DC5466-785A-11D2-84D0-00C04FB169F7",
327 );
328
329 # guess work
330 my %ads_gpcextensions = (
331 "Administrative Templates"              => "0F6B957D-509E-11D1-A7CC-0000F87571E3",
332 "Certificates"                          => "53D6AB1D-2488-11D1-A28C-00C04FB94F17",
333 "EFS recovery policy processing"        => "B1BE8D72-6EAC-11D2-A4EA-00C04F79F83A",
334 "Folder Redirection policy processing"  => "25537BA6-77A8-11D2-9B6C-0000F8080861",
335 "Folder Redirection"                    => "88E729D6-BDC1-11D1-BD2A-00C04FB9603F",
336 "Registry policy processing"            => "35378EAC-683F-11D2-A89A-00C04FBBCFA2",
337 "Remote Installation Services"          => "3060E8CE-7020-11D2-842D-00C04FA372D4",
338 "Security Settings"                     => "803E14A0-B4FB-11D0-A0D0-00A0C90F574B",
339 "Security policy processing"            => "827D319E-6EAC-11D2-A4EA-00C04F79F83A",
340 "unknown"                               => "3060E8D0-7020-11D2-842D-00C04FA372D4",
341 "unknown2"                              => "53D6AB1B-2488-11D1-A28C-00C04FB94F17",
342 );
343
344 my %ads_gpo_default_guids = (
345 "Default Domain Policy"                 => "31B2F340-016D-11D2-945F-00C04FB984F9",
346 "Default Domain Controllers Policy"     => "6AC1786C-016F-11D2-945F-00C04fB984F9",
347 "mist"                                  => "61718096-3D3F-4398-8318-203A48976F9E",
348 );
349
350 my %ads_uf = (
351         "UF_SCRIPT"                             => 0x00000001,
352         "UF_ACCOUNTDISABLE"                     => 0x00000002,
353 #       "UF_UNUSED_1"                           => 0x00000004,
354         "UF_HOMEDIR_REQUIRED"                   => 0x00000008,
355         "UF_LOCKOUT"                            => 0x00000010,
356         "UF_PASSWD_NOTREQD"                     => 0x00000020,
357         "UF_PASSWD_CANT_CHANGE"                 => 0x00000040,
358         "UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED"    => 0x00000080,
359         "UF_TEMP_DUPLICATE_ACCOUNT"             => 0x00000100,
360         "UF_NORMAL_ACCOUNT"                     => 0x00000200,
361 #       "UF_UNUSED_2"                           => 0x00000400,
362         "UF_INTERDOMAIN_TRUST_ACCOUNT"          => 0x00000800,
363         "UF_WORKSTATION_TRUST_ACCOUNT"          => 0x00001000,
364         "UF_SERVER_TRUST_ACCOUNT"               => 0x00002000,
365 #       "UF_UNUSED_3"                           => 0x00004000,
366 #       "UF_UNUSED_4"                           => 0x00008000,
367         "UF_DONT_EXPIRE_PASSWD"                 => 0x00010000,
368         "UF_MNS_LOGON_ACCOUNT"                  => 0x00020000,
369         "UF_SMARTCARD_REQUIRED"                 => 0x00040000,
370         "UF_TRUSTED_FOR_DELEGATION"             => 0x00080000,
371         "UF_NOT_DELEGATED"                      => 0x00100000,
372         "UF_USE_DES_KEY_ONLY"                   => 0x00200000,
373         "UF_DONT_REQUIRE_PREAUTH"               => 0x00400000,
374         "UF_PASSWORD_EXPIRED"                   => 0x00800000,
375         "UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION" => 0x01000000,
376         "UF_NO_AUTH_DATA_REQUIRED"              => 0x02000000,
377 #       "UF_UNUSED_8"                           => 0x04000000,
378 #       "UF_UNUSED_9"                           => 0x08000000,
379 #       "UF_UNUSED_10"                          => 0x10000000,
380 #       "UF_UNUSED_11"                          => 0x20000000,
381 #       "UF_UNUSED_12"                          => 0x40000000,
382 #       "UF_UNUSED_13"                          => 0x80000000,
383 );
384
385 my %ads_grouptype = (
386         "GROUP_TYPE_BUILTIN_LOCAL_GROUP"        => 0x00000001,
387         "GROUP_TYPE_ACCOUNT_GROUP"              => 0x00000002,
388         "GROUP_TYPE_RESOURCE_GROUP"             => 0x00000004,
389         "GROUP_TYPE_UNIVERSAL_GROUP"            => 0x00000008,
390         "GROUP_TYPE_APP_BASIC_GROUP"            => 0x00000010,
391         "GROUP_TYPE_APP_QUERY_GROUP"            => 0x00000020,
392         "GROUP_TYPE_SECURITY_ENABLED"           => 0x80000000,
393 );
394
395 my %ads_atype = (
396         "ATYPE_NORMAL_ACCOUNT"                  => 0x30000000,
397         "ATYPE_WORKSTATION_TRUST"               => 0x30000001,
398         "ATYPE_INTERDOMAIN_TRUST"               => 0x30000002,
399         "ATYPE_SECURITY_GLOBAL_GROUP"           => 0x10000000,
400         "ATYPE_DISTRIBUTION_GLOBAL_GROUP"       => 0x10000001,
401         "ATYPE_DISTRIBUTION_UNIVERSAL_GROUP"    => 0x10000001, # ATYPE_DISTRIBUTION_GLOBAL_GROUP
402         "ATYPE_SECURITY_LOCAL_GROUP"            => 0x20000000,
403         "ATYPE_DISTRIBUTION_LOCAL_GROUP"        => 0x20000001,
404         "ATYPE_ACCOUNT"                         => 0x30000000, # ATYPE_NORMAL_ACCOUNT
405         "ATYPE_GLOBAL_GROUP"                    => 0x10000000, # ATYPE_SECURITY_GLOBAL_GROUP
406         "ATYPE_LOCAL_GROUP"                     => 0x20000000, # ATYPE_SECURITY_LOCAL_GROUP
407 );
408
409 my %ads_gtype = (
410         "GTYPE_SECURITY_BUILTIN_LOCAL_GROUP"    => 0x80000005,
411         "GTYPE_SECURITY_DOMAIN_LOCAL_GROUP"     => 0x80000004,
412         "GTYPE_SECURITY_GLOBAL_GROUP"           => 0x80000002,
413         "GTYPE_SECURITY_UNIVERSAL_GROUP"        => 0x80000008,
414         "GTYPE_DISTRIBUTION_GLOBAL_GROUP"       => 0x00000002,
415         "GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP" => 0x00000004,
416         "GTYPE_DISTRIBUTION_UNIVERSAL_GROUP"    => 0x00000008,
417 );
418
419 my %munged_dial = (
420         "CtxCfgPresent"         => \&dump_int,
421         "CtxCfgFlags1"          => \&dump_int,
422         "CtxCallback"           => \&dump_string,
423         "CtxShadow"             => \&dump_string,
424         "CtxMaxConnectionTime"  => \&dump_int,
425         "CtxMaxDisconnectionTime"=> \&dump_int,
426         "CtxMaxIdleTime"        => \&dump_int,
427         "CtxKeyboardLayout"     => \&dump_int,
428         "CtxMinEncryptionLevel" => \&dump_int,
429         "CtxWorkDirectory"      => \&dump_string,
430         "CtxNWLogonServer"      => \&dump_string,
431         "CtxWFHomeDir"          => \&dump_string,
432         "CtxWFHomeDirDrive"     => \&dump_string,
433         "CtxWFProfilePath"      => \&dump_string,
434         "CtxInitialProgram"     => \&dump_string,
435         "CtxCallbackNumber"     => \&dump_string,
436 );
437
438 $SIG{__WARN__} = sub {
439         use Carp;
440         Carp::cluck (shift);
441 };
442
443 # if there is data missing, we try to autodetect with samba-tools (if installed)
444 # this might fill up workgroup, machine, realm
445 get_samba_info();
446
447 # get a workgroup
448 $workgroup      = $workgroup || $opt_workgroup || "";
449
450 # get the server
451 $server         = process_servername($opt_host) || 
452                   detect_server($workgroup,$opt_realm) || 
453                   die "please define server to query with -h host\n";
454
455
456 # get the base
457 $base           = defined($opt_base)? $opt_base : "" || 
458                   get_base_from_rootdse($server,$dse);
459
460 # get the realm
461 $realm          = $opt_realm || 
462                   get_realm_from_rootdse($server,$dse);
463
464 # get sasl mechs
465 my @sasl_mechs  = get_sasl_mechs_from_rootdse($server,$dse);
466 my $sasl_mech   = "GSSAPI";
467 if ($opt_saslmech) {
468         $sasl_mech = sprintf("%s", (check_sasl_mech($opt_saslmech) == 0)?uc($opt_saslmech):"");
469 }
470
471 # set bind type
472 my $sasl_bind = 1 if (!$opt_simpleauth);
473
474 # get username
475 my $user        = check_user($opt_user) || $ENV{'USER'} || "";
476
477 # gen upn
478 my $upn         = sprintf("%s", gen_upn($opt_machine ? "$machine\$" : $user, $realm));
479
480 # get binddn
481 $binddn         = $opt_binddn || $upn;
482
483 # get the password
484 $password       = $password || $opt_password;
485 if (!$password) {
486         $password = $opt_machine ? get_machine_password($workgroup) : get_password();
487 }
488
489 my %attr_handler = (
490         "Token-Groups-No-GC-Acceptable" => \&dump_sid,  #wrong name
491         "accountExpires"                => \&dump_nttime,
492         "attributeSecurityGUID"         => \&dump_guid,
493         "badPasswordTime"               => \&dump_nttime,                       
494         "creationTime"                  => \&dump_nttime,
495         "currentTime"                   => \&dump_timestr,
496         "domainControllerFunctionality" => \&dump_ds_func,
497         "domainFunctionality"           => \&dump_ds_func,
498         "fRSReplicaSetGUID"             => \&dump_guid,
499         "fRSReplicaSetType"             => \&dump_frstype,
500         "fRSVersionGUID"                => \&dump_guid,
501         "flags"                         => \&dump_gpflags,      # fixme: possibly only on gpos!
502         "forceLogoff"                   => \&dump_nttime_abs,
503         "forestFunctionality"           => \&dump_ds_func,
504 #       "gPCMachineExtensionNames"      => \&dump_gpcextensions,
505 #       "gPCUserExtensionNames"         => \&dump_gpcextensions,
506         "gPLink"                        => \&dump_gplink,
507         "gPOptions"                     => \&dump_gpoptions,
508         "groupType"                     => \&dump_gtype,
509         "instanceType"                  => \&dump_instance_type,
510         "lastLogon"                     => \&dump_nttime,
511         "lastLogonTimestamp"            => \&dump_nttime,
512         "lockOutObservationWindow"      => \&dump_nttime_abs,
513         "lockoutDuration"               => \&dump_nttime_abs,
514         "lockoutTime"                   => \&dump_nttime,
515 #       "logonHours"                    => \&dump_logonhours,
516         "maxPwdAge"                     => \&dump_nttime_abs,
517         "minPwdAge"                     => \&dump_nttime_abs,
518         "modifyTimeStamp"               => \&dump_timestr,
519         "msDS-Behavior-Version"         => \&dump_ds_func,      #unsure
520         "msDS-User-Account-Control-Computed" => \&dump_uacc,
521         "mS-DS-CreatorSID"              => \&dump_sid,
522 #       "msRADIUSFramedIPAddress"       => \&dump_ipaddr,
523 #       "msRASSavedFramedIPAddress"     => \&dump_ipaddr,
524         "netbootGUID"                   => \&dump_guid,
525         "nTMixedDomain"                 => \&dump_mixed_domain,
526         "nTSecurityDescriptor"          => \&dump_secdesc,
527         "objectGUID"                    => \&dump_guid,
528         "objectSid"                     => \&dump_sid,
529         "pKT"                           => \&dump_pkt,
530         "pKTGuid"                       => \&dump_guid,
531         "pwdLastSet"                    => \&dump_nttime,
532         "pwdProperties"                 => \&dump_pwdproperties,
533         "sAMAccountType"                => \&dump_atype,
534         "schemaIDGUID"                  => \&dump_guid,
535         "sDRightsEffective"             => \&dump_sdeffective,
536         "securityIdentifier"            => \&dump_sid,
537         "serverState"                   => \&dump_serverstate,
538         "supportedCapabilities",        => \&dump_capabilities,
539         "supportedControl",             => \&dump_controls,
540         "supportedExtension",           => \&dump_extension,
541         "systemFlags"                   => \&dump_systemflags,
542         "tokenGroups",                  => \&dump_sid,
543         "tokenGroupsGlobalAndUniversal" => \&dump_sid,
544         "tokenGroupsNoGCAcceptable"     => \&dump_sid,
545         "trustAttributes"               => \&dump_trustattr,
546         "trustDirection"                => \&dump_trustdirection,
547         "trustType"                     => \&dump_trusttype,
548         "uASCompat"                     => \&dump_uascompat,
549         "userAccountControl"            => \&dump_uac,
550         "userCertificate"               => \&dump_cert,
551         "userFlags"                     => \&dump_uf,
552         "userParameters"                => \&dump_munged_dial,
553         "whenChanged"                   => \&dump_timestr,
554         "whenCreated"                   => \&dump_timestr,
555 #       "dSCorePropagationData"         => \&dump_timestr,
556 );
557
558
559
560 ################
561 # subfunctions #
562 ################
563
564 sub usage {
565         print "usage: $0 [--asq] [--base|-b base] [--debug level] [--debug level] [--DN|-D binddn] [--extendeddn|-e] [--help] [--host|-h host] [--machine|-P] [--metadata|-m] [--nodiffs] [--notify|-n] [--password|-w password] [--port port] [--rawdisplay] [--realm|-R realm] [--rootdse] [--saslmech|-Y saslmech] [--schema|-c] [--scope|-s scope] [--simpleauth|-x] [--starttls|-Z] [--user|-U user] [--wknguid] [--workgroup|-k workgroup] filter [attrs]\n";
566         print "\t--asq [attribute]\n\t\tAttribute to use for a attribute scoped query (LDAP_SERVER_ASQ_OID)\n";
567         print "\t--base|-b [base]\n\t\tUse base [base]\n";
568         print "\t--debug [level]\n\t\tUse debuglevel (for Net::LDAP)\n";
569         print "\t--domain_scope\n\t\tLimit LDAP search to local domain (LDAP_SERVER_DOMAIN_SCOPE_OID)\n";
570         print "\t--DN|-D [binddn]\n\t\tUse binddn or principal\n";
571         print "\t--extendeddn|-e [value]\n\t\tDisplay extended dn (LDAP_SERVER_EXTENDED_DN_OID)\n";
572         print "\t--fastbind\n\t\tDo LDAP fast bind using LDAP_SERVER_FAST_BIND_OID extension\n";
573         print "\t--help\n\t\tDisplay help page\n";
574         print "\t--host|-h [host]\n\t\tQuery Host [host] (either a hostname or an LDAP uri)\n";
575         print "\t--machine|-P\n\t\tUse samba3 machine account stored in $secrets_tdb (needs root access)\n";
576         print "\t--metdata|-m\n\t\tDisplay replication metadata\n";
577         print "\t--nodiffs\n\t\tDisplay no diffs but full entry dump when running in notify mode\n";
578         print "\t--notify|-n\n\t\tActivate asynchronous change notification (LDAP_SERVER_NOTIFICATION_OID)\n";
579         print "\t--paging [pagesize]\n\t\tUse paged results when searching\n";
580         print "\t--password|-w [password]\n\t\tUse [password] for binddn\n";
581         print "\t--port [port]\n\t\tUse [port] when connecting ADS\n";
582         print "\t--rawdisplay\n\t\tDo not interpret values\n";
583         print "\t--realm|-R [realm]\n\t\tUse [realm] when trying to construct bind-principal\n";
584         print "\t--rootdse\n\t\tDisplay RootDSE (anonymously)\n";
585         print "\t--saslmech|-Y [saslmech]\n\t\tUse SASL Mechanism [saslmech] when binding\n";
586         print "\t--schema|-c\n\t\tDisplay DSE-Schema\n";
587         print "\t--scope|-s [scope]\n\t\tUse scope [scope] (sub, base, one)\n";
588         print "\t--simpleauth|-x\n\t\tUse simple bind (otherwise SASL binds are performed)\n";
589         print "\t--starttls|-Z\n\t\tUse Start TLS extended operation to secure LDAP traffic\n";
590         print "\t--user|-U [user]\n\t\tUse [user]\n";
591         print "\t--wknguid\n\t\tDisplay well known guids\n";
592         print "\t--workgroup|-k [workgroup]\n\t\tWhen LDAP-Server is not known try to find a Domain-Controller for [workgroup]\n";
593 }
594
595 sub write_ads_list {
596         my ($mod,$attr,$value) = @_;
597         my $ofh = select(STDOUT);
598         $~ = "ADS_LIST";
599         select($ofh);
600         write();
601
602 format ADS_LIST =
603 @<<<< @>>>>>>>>>>>>>>>>>>>>>>>: @*
604 $mod, $attr, $value
605 .
606 }
607
608 sub write_ads {
609         my ($mod,$attr,$value) = @_;
610         my $ofh = select(STDOUT);
611         $~ = "ADS";
612         select($ofh);
613         write();
614
615 format ADS =
616 @<<<< @>>>>>>>>>>>>>>>>>>>>>>>: ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
617 $mod, $attr, $value
618 ~~                              ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
619                                 $value
620 .
621 }
622
623 sub detect_server {
624
625         my $workgroup = shift;
626         my $realm = shift;
627         my $result;
628         my $found;
629
630         # try net cache (nbt records)
631         if ( -x $net && $workgroup ) {
632                 my $key = sprintf("NBT/%s#1C", uc($workgroup));
633                 chomp($result = `$net cache search $key 2>&1 /dev/null`);
634                 $result =~ s/^.*Value: //;
635                 $result =~ s/:.*//;
636                 return $result if $result;
637                 printf("%10s query failed for [%s]\n", "net cache", $key);
638         }
639
640         # try dns SRV entries
641         if ( -x $dig && $realm ) {
642                 my $key = sprintf("_ldap._tcp.%s", lc($realm));
643                 chomp($result = `$dig $key SRV +short +search | egrep "^[0-9]" | head -1`);
644                 $result =~ s/.* //g;
645                 $result =~ s/.$//g;
646                 return $result if $result;
647                 printf("%10s query failed for [%s]\n", "dns", $key);
648         }
649
650         # try netbios broadcast query
651         if ( -x $nmblookup && $workgroup ) {
652                 my $key = sprintf("%s#1C", uc($workgroup));
653                 my $pattern = sprintf("%s<1c>", uc($workgroup));
654                 chomp($result = `$nmblookup $key -d 0 | grep '$pattern'`);
655                 $result =~ s/\s.*//;
656                 return $result if $result;
657                 printf("%10s query failed for [%s]\n", "nmblookup", $key);
658         }
659
660         return "";
661 }
662
663 sub get_samba_info {
664
665         if (! -x $testparm) { return -1; }
666         
667         my $tmp;
668         open(TESTPARM, "$testparm -s -v 2> /dev/null |");
669         while (my $line = <TESTPARM>) {
670                 chomp($line);
671                 if ($line =~ /netbios name/) {
672                         ($tmp, $machine) = split(/=/, $line);
673                         $machine =~ s/\s+|\t+//g;
674                 }
675                 if ($line =~ /realm/) {
676                         ($tmp, $realm) = split(/=/, $line);
677                         $realm =~ s/\s+|\t+//g;
678                 }
679                 if ($line =~ /workgroup/) {
680                         ($tmp, $workgroup) = split(/=/, $line);
681                         $workgroup =~ s/\s+|\t+//g;
682                 }
683         }
684         close(TESTPARM);
685         return 0;
686 }
687
688 sub gen_upn {
689         my $machine = shift;
690         my $realm = shift;
691         if ($machine && $realm) {
692                 return sprintf("%s\@%s", lc($machine), uc($realm));
693         };
694         return undef;
695 }
696
697 sub get_password {
698         if (!$password && $opt_simpleauth && check_ticket($user)) {
699                 return prompt_password($user);
700         }
701         return "";
702 }
703
704 sub get_user {
705         my $user = shift || prompt_user();
706         return $user;
707 }
708
709 sub get_machine_password {
710
711         my $workgroup = shift || "";
712         $workgroup = uc($workgroup);
713
714         my ($found, $tmp);
715         -x $tdbdump || die "tdbdump is not installed. cannot proceed autodetection\n";
716         -r $secrets_tdb || die "cannot read $secrets_tdb. cannot proceed autodetection\n";
717
718         # get machine-password
719         my $key = sprintf("SECRETS/MACHINE_PASSWORD/%s", $workgroup);
720         open(SECRETS,"$tdbdump $secrets_tdb |");
721         while(my $line = <SECRETS>) {
722                 chomp($line);
723                 if ($found) {
724                         $line =~ s/\\00//;
725                         ($line,$password) = split(/"/, $line);
726                         last;
727                 }
728                 if ($line =~ /$key/) {
729                         $found = 1;
730                 }
731         }
732         close(SECRETS);
733
734         if ($found) {
735                 print "Successfully autodetected machine password for workgroup: $workgroup\n";
736                 return $password;
737         } else {
738                 warn "No machine password available for $workgroup\n";
739         }
740         return "";
741 }
742
743 sub prompt_password {
744
745         my $acct = shift || "";
746         if ($acct =~ /\%/) {
747                 ($acct, $password) = split(/\%/, $acct);
748                 return $password;
749         }
750         system "stty -echo";
751         print "Enter password for $acct:";
752         my $password = <STDIN>;
753         chomp($password);
754         print "\n";
755         system "stty echo";
756         return $password;
757 }
758
759 sub prompt_user {
760
761         print "Enter Username:";
762         my $user = <STDIN>;
763         chomp($user);
764         print "\n";
765         return $user;
766 }
767
768 sub check_ticket {
769         return 0;
770         # works only for heimdal
771         return system("$klist -t");
772 }
773
774 sub get_ticket {
775
776         my $KRB5_CONFIG = "/tmp/.krb5.conf.telads-$<";
777
778         open(KRB5CONF, "> $KRB5_CONFIG") || die "cannot write $KRB5_CONFIG";
779         printf  KRB5CONF "# autogenerated by $0\n";
780         printf  KRB5CONF "[libdefaults]\n\tdefault_realm = %s\n\tclockskew = %d\n", uc($realm), 60*60;
781         printf  KRB5CONF "[realms]\n\t%s = {\n\t\tkdc = %s\n\t}\n", uc($realm), $server;
782         close(KRB5CONF);
783
784         if ( system("KRB5_CONFIG=$KRB5_CONFIG $kinit $user") != 0) {
785                 return -1;
786         }
787
788         return 0;
789 }
790
791 sub check_user {
792         my $acct = shift || "";
793         if ($acct =~ /\%/) {
794                 ($acct, $password) = split(/\%/, $acct);
795         }
796         return $acct;
797 }
798
799 sub check_root_dse($$$@) {
800
801         # bogus function??
802         my $server = shift || "";
803         $dse = shift || get_dse($server) || return -1;
804         my $attr = shift || die "unknown query";
805         my @array = @_;
806
807         my $dse_list = $dse->get_value($attr, asref => '1');
808         my @dse_array = @$dse_list;
809
810         foreach my $i (@array) {
811                 # we could use -> supported_control but this 
812                 # is only available in newer versions of perl-ldap
813 #               if ( ! $dse->supported_control( $i ) ) {
814                 if ( grep(/$i->type()/, @dse_array) ) { 
815                         printf("required \"$attr\": %s is not supported by ADS-server.\n", $i->type());
816                         return -1;
817                 }
818         }
819         return 0;
820 }
821
822 sub check_ctrls ($$@) {
823         my $server = shift;
824         my $dse = shift;
825         my @array = @_;
826         return check_root_dse($server, $dse, "supportedControl", @array);
827 }
828
829 sub check_exts ($$@) {
830         my $server = shift;
831         my $dse = shift;
832         my @array = @_;
833         return check_root_dse($server, $dse, "supportedExtension", @array);
834 }
835
836 sub get_base_from_rootdse {
837
838         my $server = shift || "";
839         $dse = shift || get_dse($server,$async_ldap_hd) || return -1;
840         return $dse->get_value($opt_dump_schema ? 'schemaNamingContext':
841                                                   'defaultNamingContext');
842 }
843
844 sub get_realm_from_rootdse {
845
846         my $server = shift || "";
847         $dse = shift || get_dse($server,$async_ldap_hd) || return -1;
848         my $service = $dse->get_value('ldapServiceName') || "";
849         if ($service) {
850                 my ($t,$realm) = split(/\@/, $service);
851                 return $realm;
852         } else {
853                 die "very odd: could not get realm";
854         }
855 }
856
857 sub get_sasl_mechs_from_rootdse {
858
859         my $server = shift || "";
860         $dse = shift || get_dse($server,$async_ldap_hd) || return -1;
861         my $mechs = $dse->get_value('supportedSASLMechanisms', asref => 1);
862         return @$mechs;
863 }
864
865 sub get_dse {
866
867         my $server = shift || return undef;
868         $async_ldap_hd = shift || get_ldap_hd($server,1);
869         if (!$async_ldap_hd) {
870                 print "oh, no connection\n";
871                 return undef;
872         }
873         my $mesg = $async_ldap_hd->bind() || die "cannot bind\n";
874         if ($mesg->code) { die "failed to bind\n"; };
875         my $dse = $async_ldap_hd->root_dse( attrs => ['*', "supportedExtension", "supportedFeatures" ] );
876
877         return $dse;
878 }
879
880 sub process_servername {
881
882         my $name = shift || return "";
883         if ($name =~ /^ldaps:\/\//i ) {
884                 $name =~ s#^ldaps://##i;
885                 $uri = sprintf("%s://%s", "ldaps", $name);
886         } else {
887                 $name =~ s#^ldap://##i;
888                 $uri = sprintf("%s://%s", "ldap", $name);
889         }
890         return $name;
891 }
892
893 sub get_ldap_hd {
894
895         my $server = shift || return undef;
896         my $async = shift || "0";
897         my $hd;
898         die "uri unavailable" if (!$uri);
899         if ($uri =~ /^ldaps:\/\//i ) {
900                 $port = $port || 636;
901                 use Net::LDAPS;
902                 $hd = Net::LDAPS->new( $server, async => $async, port => $port ) || 
903                         die "host $server not available: $!";
904         } else {
905                 $port = $port || 389;
906                 $hd = Net::LDAP->new( $server, async => $async, port => $port ) || 
907                         die "host $server not available: $!";
908         }
909         $hd->debug($opt_debug);
910         if ($opt_starttls) {
911                 $hd->start_tls( verify => 'none' );
912         }
913
914         return $hd;
915 }
916
917 sub get_sasl_hd {
918
919         if (!$have_sasl) {
920                 print "no sasl support\n";
921                 return undef;
922         }
923
924         my $hd;
925         if ($sasl_mech && $sasl_mech eq "GSSAPI") {
926                 my $user = sprintf("%s\@%s", $user, uc($realm));
927                 if (check_ticket($user) != 0 && get_ticket($user) != 0) {
928                         print "Could not get Kerberos ticket for user [$user]\n";
929                         return undef;
930                 }
931
932                 $hd = Authen::SASL->new( mechanism => 'GSSAPI' ) || die "nope";
933                 my $conn = $hd->client_new("ldap", $server);
934                 
935                 if ($conn->code == -1) {
936                         printf "%s\n", $conn->error();
937                         return undef;
938                 };
939
940         } elsif ($sasl_mech) {
941
942                 # here comes generic sasl code
943                 $hd = Authen::SASL->new( mechanism => $sasl_mech, 
944                         callback  => { 
945                                 user => \&get_user, 
946                                 pass => \&get_password 
947                         } 
948                 ) || die "nope";
949         } else {
950                 $sasl_bind = 0;
951                 print "no supported SASL mechanism found (@sasl_mechs).\n";
952                 print "falling back to simple bind.\n";
953                 return undef;
954         }
955
956         return $hd;
957 }
958
959 sub check_sasl_mech {
960         my $mech_check = shift;
961         my $have_mech = 0;
962         foreach my $mech (@sasl_mechs) {
963                 $have_mech = 1 if ($mech eq uc($mech_check));
964         }
965         if (!$have_mech) {
966                 return -1;
967         }
968         return 0;
969 }
970
971 sub store_result ($) {
972
973         my $entry = shift;
974         return if (!$entry);
975         $entry_store{$entry->dn} = $entry;
976 }
977
978 sub display_result_diff ($) {
979
980         my $entry_new = shift;
981         return if ( !$entry_new);
982
983         if ( !exists $entry_store{$entry_new->dn}) {
984                 print "can't display any differences yet. full dump...\n";
985                 display_entry_generic($entry_new);
986                 return;
987         }
988
989         my $entry_old = $entry_store{$entry_new->dn};
990
991         foreach my $attr (sort $entry_new->attributes) {
992                 if ( $entry_new->exists($attr) && ! $entry_old->exists($attr)) {
993                         display_attr_generic("add:\t", $entry_new, $attr);
994                         next;
995                 }
996         }
997
998         foreach my $attr (sort $entry_old->attributes) {
999                 if (! $entry_new->exists($attr) && $entry_old->exists($attr)) {
1000                         display_attr_generic("del:\t", $entry_old, $attr);
1001                         next;
1002                 }
1003
1004                 # now check for all values if they have changed, display changes
1005                 my ($old_vals, $new_vals, @old_vals, @new_vals, %old, %new);
1006
1007                 $old_vals = $entry_old->get_value($attr, asref => 1);
1008                 @old_vals = @$old_vals;
1009                 $new_vals = $entry_new->get_value($attr, asref => 1);
1010                 @new_vals = @$new_vals;
1011
1012                 if (scalar(@old_vals) == 1 && scalar(@new_vals) == 1) {
1013                         if ($old_vals[0] ne $new_vals[0]) {
1014                                 display_attr_generic("old:\t", $entry_old, $attr);
1015                                 display_attr_generic("new:\t", $entry_new, $attr);
1016                         }
1017                         next;
1018                 }
1019
1020                 # handle multivalued diffs
1021                 foreach my $val (@old_vals) { $old{$val} = "dummy"; };
1022                 foreach my $val (@new_vals) { $new{$val} = "dummy"; };
1023                 foreach my $val (sort keys %new) {
1024                         if (!exists $old{$val}) {
1025                                 display_value_generic("add:\t", $attr, $val);
1026                         }
1027                 }
1028                 foreach my $val (sort keys %old) {
1029                         if (!exists $new{$val}) {
1030                                 display_value_generic("del:\t", $attr, $val);
1031                         }
1032                 }
1033         }
1034         print "\n";
1035
1036 }
1037
1038 sub sid2string ($) {
1039
1040         # Fix from Michael James <michael@james.st>
1041         my $binary_sid = shift;
1042         my($sid_rev, $num_auths, $id1, $id2, @ids) = unpack("H2 H2 n N V*", $binary_sid);
1043         my $sid_string = join("-", "S", hex($sid_rev), ($id1<<32)+$id2, @ids);
1044         return $sid_string;
1045                         
1046 }
1047
1048 sub string_to_guid {
1049         my $string = shift;
1050         return undef unless $string =~ /([0-9,a-z]{8})-([0-9,a-z]{4})-([0-9,a-z]{4})-([0-9,a-z]{2})([0-9,a-z]{2})-([0-9,a-z]{2})([0-9,a-z]{2})([0-9,a-z]{2})([0-9,a-z]{2})([0-9,a-z]{2})([0-9,a-z]{2})/i;
1051         
1052         return  pack("I", hex $1) . 
1053                 pack("S", hex $2) . 
1054                 pack("S", hex $3) . 
1055                 pack("C", hex $4) . 
1056                 pack("C", hex $5) .
1057                 pack("C", hex $6) . 
1058                 pack("C", hex $7) . 
1059                 pack("C", hex $8) . 
1060                 pack("C", hex $9) . 
1061                 pack("C", hex $10) . 
1062                 pack("C", hex $11);
1063
1064 #       print "$1\n$2\n$3\n$4\n$5\n$6\n$7\n$8\n$9\n$10\n$11\n";
1065 }
1066                                                                
1067 sub bindstring_to_guid {
1068         my $str = shift;
1069         return pack("H2 H2 H2 H2 H2 H2 H2 H2 H2 H2 H2 H2 H2 H2 H2 H2", 
1070                 substr($str,0,2),
1071                 substr($str,2,2),
1072                 substr($str,4,2),
1073                 substr($str,6,2),
1074                 substr($str,8,2),
1075                 substr($str,10,2),
1076                 substr($str,12,2),
1077                 substr($str,14,2),
1078                 substr($str,16,2),
1079                 substr($str,18,2),
1080                 substr($str,20,2),
1081                 substr($str,22,2),
1082                 substr($str,24,2),
1083                 substr($str,26,2),
1084                 substr($str,28,2),
1085                 substr($str,30,2));
1086 }
1087
1088 sub guid_to_string {
1089         my $guid = shift;
1090         my $string = sprintf "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X", 
1091                 unpack("I", $guid), 
1092                 unpack("S", substr($guid, 4, 2)), 
1093                 unpack("S", substr($guid, 6, 2)),
1094                 unpack("C", substr($guid, 8, 1)),
1095                 unpack("C", substr($guid, 9, 1)),
1096                 unpack("C", substr($guid, 10, 1)),
1097                 unpack("C", substr($guid, 11, 1)),
1098                 unpack("C", substr($guid, 12, 1)),
1099                 unpack("C", substr($guid, 13, 1)),
1100                 unpack("C", substr($guid, 14, 1)),
1101                 unpack("C", substr($guid, 15, 1)); 
1102         return lc($string);
1103 }
1104
1105 sub guid_to_bindstring {
1106         my $guid = shift;
1107         return unpack("H" . 2 * length($guid), $guid),
1108 }
1109
1110 sub dump_wknguid {
1111         print "Dumping Well known GUIDs:\n";
1112         foreach my $wknguid (keys %wknguids) {
1113
1114                 my $guid = bindstring_to_guid($wknguids{$wknguid});
1115                 my $str  = guid_to_string($guid);
1116                 my $back = guid_to_bindstring($guid);
1117
1118                 printf "wkguid:             %s\n", $wknguid;
1119                 printf "bind_string format: %s\n", $wknguids{$wknguid};
1120                 printf "string format:      %s\n", guid_to_string($guid);
1121                 printf "back to bind_string:%s\n", guid_to_bindstring($guid);
1122                                 
1123                 printf "use base: \"<WKGUID=%s,%s>\"\n", guid_to_bindstring($guid), $base;
1124         }
1125 }
1126
1127 sub gen_bitmask_string_format($%) {
1128         my $mod = shift;
1129         my (%tmp) = @_;
1130         my @list;
1131         foreach my $key (sort keys %tmp) {
1132                 push(@list, sprintf("%s %s", $tmp{$key}, $key));
1133         }
1134         return join("\n$mod$tabsize",@list);
1135 }
1136
1137
1138 sub nt_to_unixtime ($) {
1139         # the number of 100 nanosecond intervals since jan. 1. 1601 (utc)
1140         my $t64 = shift;
1141         $t64 =~ s/(.+).{7,7}/$1/;
1142         $t64 -= 11644473600;
1143         return $t64;
1144 }
1145
1146 sub dump_equal {
1147         my $val = shift;
1148         my $mod = shift || die "no mod";
1149         my (%header) = @_;
1150         my %tmp;
1151         my $found = 0;
1152         foreach my $key (keys %header) {
1153                 if ($header{$key} eq $val) {
1154                         $tmp{"($val)"} = $key;
1155                         $found = 1;
1156                         last;
1157                 }
1158         }
1159         if (!$found) { $tmp{$val} = ""; };
1160         return gen_bitmask_string_format($mod,%tmp);
1161 }
1162
1163 sub dump_bitmask {
1164         my $op = shift || die "no op";
1165         my $val = shift; 
1166         my $mod = shift || die "no mod";
1167         my (%header) = @_;
1168         my %tmp;
1169         $tmp{""} = sprintf("%s (0x%08x)", $val, $val);
1170         foreach my $key (sort keys %header) {   # sort by val !
1171                 my $val_hex = sprintf("0x%08x", $header{$key});
1172                 if ($op eq "&") {
1173                         $tmp{"$key ($val_hex)"} = ( $val & $header{$key} ) ? $set:$unset; 
1174                 } elsif ($op eq "==") {
1175                         $tmp{"$key ($val_hex)"} = ( $val == $header{$key} ) ? $set:$unset; 
1176                 } else {
1177                         print "unknown operator: $op\n";
1178                         return;
1179                 }
1180         }
1181         return gen_bitmask_string_format($mod,%tmp);
1182 }
1183
1184 sub dump_bitmask_and {
1185         return dump_bitmask("&",@_);
1186 }
1187
1188 sub dump_bitmask_equal {
1189         return dump_bitmask("==",@_);
1190 }
1191
1192 sub dump_uac {
1193         return dump_bitmask_and(@_,%ads_uf); # ads_uf ?
1194 }
1195
1196 sub dump_uascompat {
1197         return dump_bitmask_equal(@_,%ads_uascompat);
1198 }
1199
1200 sub dump_gpoptions {
1201         return dump_bitmask_equal(@_,%ads_gpoptions);
1202 }
1203
1204 sub dump_gpflags {
1205         return dump_bitmask_equal(@_,%ads_gpflags);
1206 }
1207
1208 sub dump_uacc {
1209         return dump_bitmask_equal(@_,%ads_uacc); 
1210 }
1211
1212 sub dump_uf {
1213         return dump_bitmask_and(@_,%ads_uf);
1214 }
1215
1216 sub dump_gtype {
1217         my $ret = dump_bitmask_and(@_,%ads_grouptype);
1218         $ret .= "\n$tabsize\t";
1219         $ret .= dump_bitmask_equal(@_,%ads_gtype);
1220         return $ret;
1221 }
1222
1223 sub dump_atype {
1224         return dump_bitmask_equal(@_,%ads_atype);
1225 }
1226
1227 sub dump_controls {
1228         return dump_equal(@_,%ads_controls);
1229 }
1230
1231 sub dump_capabilities {
1232         return dump_equal(@_,%ads_capabilities);
1233 }
1234
1235 sub dump_extension {
1236         return dump_equal(@_,%ads_extensions);
1237 }
1238
1239 sub dump_systemflags {
1240         return dump_bitmask_and(@_,%ads_systemflags);
1241 }
1242
1243 sub dump_instance_type {
1244         return dump_bitmask_and(@_,%ads_instance_type);
1245 }
1246
1247 sub dump_ds_func {
1248         return dump_bitmask_equal(@_,%ads_ds_func);
1249 }
1250
1251 sub dump_serverstate {
1252         return dump_bitmask_equal(@_,%ads_serverstate);
1253 }
1254
1255 sub dump_sdeffective {
1256         return dump_bitmask_and(@_,%ads_sdeffective);
1257 }
1258
1259 sub dump_trustattr {
1260         return dump_bitmask_equal(@_,%ads_trustattrs);
1261 }
1262
1263 sub dump_trusttype {
1264         return dump_bitmask_equal(@_,%ads_trusttype);
1265 }
1266
1267 sub dump_trustdirection {
1268         return dump_bitmask_equal(@_,%ads_trustdirection);
1269 }
1270
1271 sub dump_pwdproperties {
1272         return dump_bitmask_and(@_,%ads_pwdproperties);
1273 }
1274
1275 sub dump_frstype {
1276         return dump_bitmask_equal(@_,%ads_frstypes)
1277 }
1278
1279 sub dump_mixed_domain {
1280         return dump_bitmask_equal(@_,%ads_mixed_domain);
1281 }
1282
1283 sub dump_sid {
1284         my $bin_sid = shift;
1285         return sid2string($bin_sid);
1286 }
1287
1288 sub dump_guid {
1289         my $guid = shift;
1290         return guid_to_string($guid);
1291 }
1292
1293 sub dump_secdesc {
1294         my $val = shift;
1295         return "FIXME: write sddl-converter!";
1296 }
1297
1298 sub dump_nttime {
1299         my $nttime = shift;
1300         if ($nttime == 0) {
1301                 return sprintf("%s (%s)", "never", $nttime);
1302         }
1303         my $localtime = localtime(nt_to_unixtime($nttime));
1304         return sprintf("%s (%s)", $localtime, $nttime);
1305 }
1306
1307 sub dump_nttime_abs {
1308         if ($_[0] == 9223372036854775807) {
1309                 return sprintf("%s (%s)", "now", $_[0]);
1310         }
1311         if ($_[0] == -9223372036854775808 || $_[0] == 0) { # 0x7FFFFFFFFFFFFFFF
1312                 return sprintf("%s (%s)", "never", $_[0]);
1313         }
1314         # FIXME: actually *do* abs time !
1315         return dump_nttime($_[0]);
1316 }
1317
1318 sub dump_timestr {
1319         my $time = shift;
1320         if ($time eq "16010101000010.0Z") {
1321                 return sprintf("%s (%s)", "never", $time);
1322         }
1323         my ($year,$mon,$mday,$hour,$min,$sec,$zone) = 
1324                 unpack('a4 a2 a2 a2 a2 a2 a4', $time);
1325         $mon -= 1;
1326         my $localtime = localtime(timegm($sec,$min,$hour,$mday,$mon,$year));
1327         return sprintf("%s (%s)", $localtime, $time);
1328 }
1329
1330 sub dump_string {
1331         return $_[0];
1332 }
1333
1334 sub dump_int {
1335         return sprintf("%d", $_[0]);
1336 }
1337
1338 sub dump_munged_dial {
1339         my $dial = shift;
1340         return "FIXME! decode this";
1341 }
1342
1343 sub dump_cert {
1344  
1345         my $cert = shift;
1346         open(OPENSSL, "| /usr/bin/openssl x509 -text -inform der");
1347         print OPENSSL $cert;
1348         close(OPENSSL);
1349         return "";
1350 }
1351
1352 sub dump_pkt {
1353         my $pkt = shift;
1354         return "not yet";
1355         printf("%s: ", $pkt);
1356         printf("%02X", $pkt);
1357         
1358 }
1359
1360 sub dump_gplink {
1361
1362         my $gplink = shift;
1363         my $gplink_mod = $gplink;
1364         my @links = split("\\]\\[", $gplink_mod);
1365         foreach my $link (@links) {
1366                 $link =~ s/^\[|\]$//g;
1367                 my ($ldap_link, $opt) = split(";", $link);
1368                 my @array = ( "$opt", "\t" );
1369                 printf("%slink: %s, opt: %s\n", $tabsize, $ldap_link, dump_bitmask_and(@array, %ads_gplink_opts));
1370         }
1371         return $gplink;
1372 }
1373
1374 sub construct_filter {
1375
1376         my $tmp = shift;
1377
1378         if (!$tmp || $opt_notify) {
1379                 return "(objectclass=*)";
1380         }
1381
1382         if ($tmp && $tmp !~ /^.*\=/) {
1383                 return "(ANR=$tmp)";
1384         }
1385
1386         return $tmp;
1387         # (&(objectCategory=person)
1388         # (userAccountControl:$ads_matching_rules{LDAP_MATCHING_RULE_BIT_AND}:=2))
1389 }
1390
1391 sub construct_attrs {
1392         
1393         my @attrs = @_;
1394         
1395         if (!@attrs) {
1396                 push(@attrs,"*");
1397         }
1398
1399         if ($opt_notify) {
1400                 push(@attrs,"uSNChanged");
1401         }
1402
1403         if ($opt_display_metadata) {
1404                 push(@attrs,"msDS-ReplAttributeMetaData");
1405                 push(@attrs,"replPropertyMetaData");
1406         }
1407
1408         if ($opt_verbose) {
1409                 push(@attrs,"nTSecurityDescriptor");
1410                 push(@attrs,"msDS-KeyVersionNumber");
1411                 push(@attrs,"msDS-User-Account-Control-Computed");
1412                 push(@attrs,"modifyTimeStamp");
1413         }
1414
1415         return sort @attrs;
1416 }
1417
1418 sub print_header {
1419
1420         print "\n";
1421         printf "%10s: %s\n", "uri", $uri;
1422         printf "%10s: %s\n", "port", $port;
1423         printf "%10s: %s\n", "base", $base;
1424         printf "%10s: %s\n", $sasl_bind ? "principal" : "binddn", $sasl_bind ? $upn : $binddn;
1425         printf "%10s: %s\n", "password", $password;
1426         printf "%10s: %s\n", "bind-type", $sasl_bind ? "SASL" : "simple";
1427         printf "%10s: %s\n", "sasl-mech", $sasl_mech if ($sasl_mech);
1428         printf "%10s: %s\n", "filter", $filter;
1429         printf "%10s: %s\n", "scope", $scope;
1430         printf "%10s: %s\n", "attrs", join(", ", @attrs);
1431         printf "%10s: %s\n", "controls", join(", ", @ctrls_s);
1432         printf "%10s: %s\n", "page_size", $opt_paging if ($opt_paging);
1433         printf "%10s: %s\n", "start_tls", $opt_starttls ? "yes" : "no";
1434         printf "\n";
1435 }
1436
1437 sub gen_controls {
1438
1439         # setup attribute-scoped query control
1440         my $asq_asn = Convert::ASN1->new;
1441         $asq_asn->prepare(
1442                 q<      asq ::= SEQUENCE {
1443                                 sourceAttribute   OCTET_STRING
1444                         }
1445                 >
1446         );
1447         my $ctl_asq_val = $asq_asn->encode( sourceAttribute => $opt_asq);
1448         my $ctl_asq = Net::LDAP::Control->new(
1449                 type => $ads_controls{'LDAP_SERVER_ASQ_OID'},
1450                 critical => 'true',
1451                 value => $ctl_asq_val);
1452
1453
1454         # setup extended dn control
1455         my $asn_extended_dn = Convert::ASN1->new;
1456         $asn_extended_dn->prepare(
1457                 q<      ExtendedDn ::= SEQUENCE {
1458                                 mode     INTEGER
1459                         }
1460                 >
1461         );
1462
1463         # only w2k3 accepts '1' and needs the ctl_val, w2k does not accept a ctl_val
1464         my $ctl_extended_dn_val = $asn_extended_dn->encode( mode => $opt_display_extendeddn);
1465         my $ctl_extended_dn = Net::LDAP::Control->new( 
1466                         type => $ads_controls{'LDAP_SERVER_EXTENDED_DN_OID'},
1467                         critical => 'true',
1468                         value => $opt_display_extendeddn ? $ctl_extended_dn_val : "");
1469
1470         # setup search options
1471         my $search_opt = Convert::ASN1->new;
1472         $search_opt->prepare(
1473                 q<      searchopt ::= SEQUENCE {
1474                                 flags     INTEGER
1475                         }
1476                 >
1477         );
1478
1479         my $tmp = $search_opt->encode( flags => $opt_search_opt);
1480         my $ctl_search_opt = Net::LDAP::Control->new( 
1481                 type => $ads_controls{'LDAP_SERVER_SEARCH_OPTIONS_OID'},
1482                 critical => 'true',
1483                 value => $tmp);
1484
1485         # setup notify control
1486         my $ctl_notification = Net::LDAP::Control->new( 
1487                 type => $ads_controls{'LDAP_SERVER_NOTIFICATION_OID'},
1488                 critical => 'true');
1489
1490
1491         # setup paging control
1492         $ctl_paged = Net::LDAP::Control->new( 
1493                 type => $ads_controls{'LDAP_PAGED_RESULT_OID_STRING'},
1494                 critical => 'true',
1495                 size => $opt_paging ? $opt_paging : 1000);
1496
1497         # setup domscope control
1498         my $ctl_domscope = Net::LDAP::Control->new( 
1499                 type => $ads_controls{'LDAP_SERVER_DOMAIN_SCOPE_OID'},
1500                 critical => 'true',
1501                 value => "");
1502
1503         if (defined($opt_paging) || $opt_dump_schema) {
1504                 push(@ctrls, $ctl_paged);
1505                 push(@ctrls_s, "LDAP_PAGED_RESULT_OID_STRING" );
1506         }
1507
1508         if (defined($opt_display_extendeddn)) {
1509                 push(@ctrls, $ctl_extended_dn);
1510                 push(@ctrls_s, "LDAP_SERVER_EXTENDED_DN_OID");
1511         } 
1512         if ($opt_notify) {
1513                 push(@ctrls, $ctl_notification);
1514                 push(@ctrls_s, "LDAP_SERVER_NOTIFICATION_OID");
1515         }
1516         
1517         if ($opt_asq) {
1518                 push(@ctrls, $ctl_asq);
1519                 push(@ctrls_s, "LDAP_SERVER_ASQ_OID");
1520         }
1521
1522         if ($opt_domain_scope) {
1523                 push(@ctrls, $ctl_domscope);
1524                 push(@ctrls_s, "LDAP_SERVER_DOMAIN_SCOPE_OID");
1525         }
1526
1527         if ($opt_search_opt) {
1528                 push(@ctrls, $ctl_search_opt);
1529                 push(@ctrls_s, "LDAP_SERVER_SEARCH_OPTIONS_OID");
1530         }
1531
1532         return @ctrls;
1533 }
1534
1535 sub display_value_generic ($$$) {
1536
1537         my ($mod,$attr,$value) = @_;
1538         return unless (defined($value) and defined($attr));
1539
1540         if ( ! $opt_display_raw && exists $attr_handler{$attr} ) {
1541                 $value = $attr_handler{$attr}($value,$mod);
1542                 write_ads_list($mod,$attr,$value);
1543                 return;
1544         }
1545         write_ads($mod,$attr,$value);
1546 }
1547
1548 sub display_attr_generic ($$$) {
1549
1550         my ($mod,$entry,$attr) = @_;
1551         return if (!$attr || !$entry);
1552
1553         my $ref = $entry->get_value($attr, asref => 1);
1554         my @values = @$ref;
1555
1556         foreach my $value ( sort @values) {
1557                 display_value_generic($mod,$attr,$value);
1558         }
1559 }
1560
1561 sub display_entry_generic ($) {
1562
1563         my $entry = shift;
1564         return if (!$entry);
1565
1566         foreach my $attr ( sort $entry->attributes) {
1567                 display_attr_generic("\t",$entry,$attr);        
1568         }
1569 }
1570
1571 sub display_ldap_err ($) {
1572
1573         my $msg = shift;
1574         print_header();
1575         my ($package, $filename, $line, $subroutine) = caller(0);
1576
1577         print "got error from ADS:\n";
1578         printf("%s(%d): ERROR (%s): %s\n", 
1579                 $subroutine, $line, $msg->code, $msg->error);
1580
1581 }
1582
1583 sub process_result {
1584
1585         my ($msg,$entry) = @_;
1586
1587         if (!defined($msg)) { 
1588                 return; 
1589         }
1590
1591         if ($msg->code) {
1592                 display_ldap_err($msg);
1593                 exit 1;
1594         }
1595
1596         if (!defined($entry)) {
1597                 return;
1598         }
1599
1600         if ($entry->isa('Net::LDAP::Reference')) {
1601                 foreach my $ref ($entry->references) {
1602                         print "\ngot Reference: [$ref]\n";
1603                 }
1604                 return;
1605         }
1606
1607         print "\nfound entry: ".$entry->dn."\n".("-" x 80)."\n";
1608
1609         display_entry_generic($entry);
1610 }
1611
1612 sub default_callback {
1613
1614         my ($res,$obj) = @_;
1615
1616         if (!$opt_notify && $res->code == LDAP_REFERRAL) {
1617                 return;
1618         }
1619
1620         if (!$opt_notify) {
1621                 return process_result($res,$obj);
1622         } 
1623 }
1624
1625 sub error_callback {
1626
1627         my ($msg,$entry) = @_;
1628
1629         if (!$msg) { 
1630                 return; 
1631         }
1632
1633         if ($msg->code) {
1634                 display_ldap_err($msg);
1635                 exit(1);
1636         }
1637         return;
1638 }
1639
1640 sub notify_callback {
1641
1642         my ($msg, $obj) = @_;
1643
1644         if (! defined($obj)) {
1645                 return;
1646         }
1647
1648         if ($obj->isa('Net::LDAP::Reference')) {
1649                 foreach my $ref ($obj->references) {
1650                         print "\ngot Reference: [$ref]\n";
1651                 }
1652                 return;
1653         }
1654
1655         while (1) {
1656
1657                 my $async_entry = $async_search->pop_entry;
1658
1659                 if (!$async_entry->dn) {
1660                         print "very weird. entry has no dn\n";
1661                         next;
1662                 }
1663         
1664                 printf("\ngot changenotify for dn: [%s]\n%s\n", $async_entry->dn, ("-" x 80));
1665
1666                 my $new_usn = $async_entry->get_value('uSNChanged');
1667                 if (!$new_usn) {
1668                         die "odd, no usnChanged attribute???";
1669                 }
1670                 if (!$usn || $new_usn > $usn) {
1671                         $usn = $new_usn;
1672                         if ($opt_notify_nodiffs) {
1673                                 display_entry_generic($async_entry);
1674                         } else {
1675                                 display_result_diff($async_entry);
1676                         }
1677                 } 
1678                 store_result($async_entry);
1679         }
1680 }
1681
1682 sub do_bind($$) {
1683
1684         my $async_ldap_hd = shift || return undef;
1685         my $sasl_bind = shift;
1686
1687         if ($sasl_bind) {
1688                 if (!$works_sasl) {
1689                         print "this version of Net::LDAP does not have proper SASL support.\n";
1690                         print "Need at least perl-ldap V. $pref_version\n";
1691                 }
1692                 $sasl_hd = get_sasl_hd();
1693                 if (!$sasl_hd) {
1694                         print "failed to create SASL handle\n";
1695                         return -1;
1696                 }
1697                 $mesg = $async_ldap_hd->bind( 
1698                         sasl => $sasl_hd, 
1699                         callback => \&error_callback 
1700                 ) || die "doesnt work"; 
1701         } else {
1702                 $sasl_mech = "";
1703                 $mesg = $async_ldap_hd->bind( 
1704                         $binddn, 
1705                         password => $password, 
1706                         callback => $opt_fastbind ? undef : \&error_callback
1707                 ) || die "doesnt work";
1708         };
1709         if ($mesg->code) { 
1710                 display_ldap_err($mesg) if (!$opt_fastbind);
1711                 return -1;
1712         }
1713         return 0;
1714 }
1715
1716 sub do_fast_bind() {
1717
1718         do_unbind();
1719
1720         my $hd = get_ldap_hd($server,1);
1721
1722         my $mesg = $hd->extension(
1723                 name => $ads_extensions{'LDAP_SERVER_FAST_BIND_OID'});
1724         
1725         if ($mesg->code) { 
1726                 display_ldap_err($mesg);
1727                 return -1;
1728         }
1729
1730         my $ret = do_bind($hd, undef);
1731         $hd->unbind;
1732
1733         printf("bind using 'LDAP_SERVER_FAST_BIND_OID' %s\n", 
1734                 $ret == 0 ? "succeeded" : "failed");
1735
1736         return $ret;
1737 }
1738
1739 sub do_unbind() {
1740         if ($async_ldap_hd) {
1741                 $async_ldap_hd->unbind;
1742         }
1743         if ($sync_ldap_hd) {
1744                 $sync_ldap_hd->unbind;
1745         }
1746 }
1747
1748 ###############################################################################
1749
1750 sub main () {
1751
1752         if ($opt_fastbind) {
1753
1754                 if (check_exts($server,$dse,"LDAP_SERVER_FAST_BIND_OID") == -1) {
1755                         print "LDAP_SERVER_FAST_BIND_OID not supported by this server\n";
1756                         exit 1;
1757                 }
1758
1759                 # fast bind can only bind, not search
1760                 exit do_fast_bind();
1761         }
1762
1763         $filter = construct_filter($query);
1764         @attrs  = construct_attrs(@attrs);
1765         @ctrls  = gen_controls();
1766
1767         if (check_ctrls($server,$dse,@ctrls) == -1) {
1768                 print "not all required LDAP Controls are supported by this server\n";
1769                 exit 1;
1770         }
1771
1772         if ($opt_dump_rootdse) {
1773                 print "Dumping Root-DSE:\n";
1774                 display_entry_generic($dse);
1775                 exit 0;
1776         }
1777
1778         if ($opt_dump_wknguid) {
1779                 dump_wknguid();
1780                 exit 0;
1781         }
1782
1783         if (do_bind($async_ldap_hd, $sasl_bind) == -1) {
1784                 exit 1;
1785         }
1786
1787         print_header();
1788
1789         if ($opt_dump_schema) {
1790                 print "Dumping Schema:\n";
1791 #               my $ads_schema = $async_ldap_hd->schema;
1792 #               $ads_schema->dump;
1793 #               exit 0;
1794         }
1795
1796         while (1) {
1797
1798                 $async_search = $async_ldap_hd->search( 
1799                         base => $base, 
1800                         filter => $filter, 
1801                         attrs => [ @attrs ],
1802                         control => [ @ctrls ], 
1803                         callback => \&default_callback,
1804                         scope => $scope,
1805                                 ) || die "cannot search";
1806
1807                 if (!$opt_notify && ($async_search->code == LDAP_REFERRAL)) {
1808                         foreach my $ref ($async_search->referrals) {
1809                                 print "\ngot Referral: [$ref]\n";
1810                                 my ($prot, $host, $base) = split(/\/+/, $ref);
1811                                 $async_ldap_hd->unbind();
1812                                 $async_ldap_hd = get_ldap_hd($host, 1);
1813                                 if (do_bind($async_ldap_hd, $sasl_bind) == -1) {
1814                                         $async_ldap_hd->unbind();
1815                                         next;
1816                                 }
1817                                 print "\nsuccessful rebind to: [$ref]\n";
1818                                 last;
1819                         }
1820                         next; # repeat the query
1821                 }
1822
1823                 if ($opt_notify) {
1824
1825                         print "Base [$base] is registered now for change-notify\n";
1826                         print "\nWaiting for change-notify...\n";
1827
1828                         my $sync_ldap_hd = get_ldap_hd($server,0);
1829                         if (do_bind($sync_ldap_hd, $sasl_bind) == -1) {
1830                                 exit 2;
1831                         }
1832
1833                         my $sync_search = $sync_ldap_hd->search( 
1834                                 base => $base, 
1835                                 filter => $filter, 
1836                                 attrs => [ @attrs ],
1837                                 callback => \&notify_callback,
1838                                 scope => $scope,
1839                                 ) || die "cannot search";
1840
1841                 }
1842
1843                 $total_entry_count += $async_search->count;
1844                 ++$page_count;
1845                 print "-" x 80 . "\n";
1846                 printf("Got %d Entries in Page %d \n\n", 
1847                         $async_search->count, $page_count);
1848                 my ($resp) = $async_search->control( 
1849                         $ads_controls{'LDAP_PAGED_RESULT_OID_STRING'} ) or last;
1850                 last unless ref $resp && $ctl_paged->cookie($resp->cookie);
1851         }
1852
1853         if ($async_search->entries == 0) {
1854                 print "No entries found with filter $filter\n";
1855         } else {
1856                 print "Got $total_entry_count Entries in $page_count Pages\n" if ($opt_paging);
1857         }
1858
1859         do_unbind()
1860 }
1861
1862 main();
1863
1864 exit 0;