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