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