]> git.sur5r.net Git - openldap/blob - clients/tools/common.c
5eb41aaf1ad3c47a6b9d5decfb3ff97e4d80fb04
[openldap] / clients / tools / common.c
1 /* common.c - common routines for the ldap client tools */
2 /* $OpenLDAP$ */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4  *
5  * Copyright 1998-2017 The OpenLDAP Foundation.
6  * Portions Copyright 2003 Kurt D. Zeilenga.
7  * Portions Copyright 2003 IBM Corporation.
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted only as authorized by the OpenLDAP
12  * Public License.
13  *
14  * A copy of this license is available in the file LICENSE in the
15  * top-level directory of the distribution or, alternatively, at
16  * <http://www.OpenLDAP.org/license.html>.
17  */
18 /* ACKNOWLEDGEMENTS:
19  * This file was initially created by Hallvard B. Furuseth based (in
20  * part) upon argument parsing code for individual tools located in
21  * this directory.   Additional contributors include:
22  *   Kurt D. Zeilenga (additional common argument and control support)
23  */
24
25 #include "portable.h"
26
27 #include <stdio.h>
28
29 #include <ac/stdlib.h>
30 #include <ac/signal.h>
31 #include <ac/string.h>
32 #include <ac/ctype.h>
33 #include <ac/unistd.h>
34 #include <ac/errno.h>
35 #include <ac/time.h>
36 #include <ac/socket.h>
37
38 #ifdef HAVE_CYRUS_SASL
39 #ifdef HAVE_SASL_SASL_H
40 #include <sasl/sasl.h>
41 #else
42 #include <sasl.h>
43 #endif
44 #endif
45
46 #include <ldap.h>
47
48 #include "ldif.h"
49 #include "lutil.h"
50 #include "lutil_ldap.h"
51 #include "ldap_defaults.h"
52 #include "ldap_pvt.h"
53 #include "lber_pvt.h"
54
55 #include "common.h"
56
57 /* input-related vars */
58
59 /* misc. parameters */
60 tool_type_t     tool_type;
61 int             contoper = 0;
62 int             debug = 0;
63 char            *infile = NULL;
64 int             dont = 0;
65 int             nocanon = 0;
66 int             referrals = 0;
67 int             verbose = 0;
68 int             ldif = 0;
69 ber_len_t       ldif_wrap = 0;
70 char            *prog = NULL;
71
72 /* connection */
73 char            *ldapuri = NULL;
74 char            *ldaphost = NULL;
75 int             ldapport = 0;
76 int             use_tls = 0;
77 int             protocol = -1;
78 int             version = 0;
79
80 /* authc/authz */
81 int             authmethod = -1;
82 char            *binddn = NULL;
83 int             want_bindpw = 0;
84 struct berval   passwd = { 0, NULL };
85 char            *pw_file = NULL;
86 #ifdef HAVE_CYRUS_SASL
87 unsigned        sasl_flags = LDAP_SASL_AUTOMATIC;
88 char            *sasl_realm = NULL;
89 char            *sasl_authc_id = NULL;
90 char            *sasl_authz_id = NULL;
91 char            *sasl_mech = NULL;
92 char            *sasl_secprops = NULL;
93 #endif
94
95 /* controls */
96 int             assertctl;
97 char            *assertion = NULL;
98 struct berval   assertionvalue = BER_BVNULL;
99 char            *authzid = NULL;
100 int             authzcrit = 1;
101 /* support deprecated early version of proxyAuthz */
102 #define LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ       "2.16.840.1.113730.3.4.12"
103 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
104 char            *proxydn = NULL;
105 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
106 int             manageDIT = 0;
107 int             manageDSAit = 0;
108 int             noop = 0;
109 int             ppolicy = 0;
110 int             preread = 0;
111 static char     *preread_attrs = NULL;
112 int             postread = 0;
113 static char     *postread_attrs = NULL;
114 ber_int_t       pr_morePagedResults = 1;
115 struct berval   pr_cookie = { 0, NULL };
116 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
117 int             chaining = 0;
118 static int      chainingResolve = -1;
119 static int      chainingContinuation = -1;
120 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
121 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
122 static int      sessionTracking = 0;
123 static char     *sessionTrackingName;
124 struct berval   stValue;
125 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
126 ber_int_t vlvPos;
127 ber_int_t vlvCount;
128 struct berval *vlvContext;
129 static int      bauthzid;
130
131 LDAPControl     *unknown_ctrls = NULL;
132 int             unknown_ctrls_num = 0;
133
134 /* options */
135 struct timeval  nettimeout = { -1 , 0 };
136
137 typedef int (*print_ctrl_fn)( LDAP *ld, LDAPControl *ctrl );
138
139 static int print_preread( LDAP *ld, LDAPControl *ctrl );
140 static int print_postread( LDAP *ld, LDAPControl *ctrl );
141 static int print_paged_results( LDAP *ld, LDAPControl *ctrl );
142 #ifdef LDAP_CONTROL_AUTHZID_RESPONSE
143 static int print_authzid( LDAP *ld, LDAPControl *ctrl );
144 #endif
145 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
146 static int print_ppolicy( LDAP *ld, LDAPControl *ctrl );
147 #endif
148 static int print_sss( LDAP *ld, LDAPControl *ctrl );
149 static int print_vlv( LDAP *ld, LDAPControl *ctrl );
150 #ifdef LDAP_CONTROL_X_DEREF
151 static int print_deref( LDAP *ld, LDAPControl *ctrl );
152 #endif
153 #ifdef LDAP_CONTROL_X_WHATFAILED
154 static int print_whatfailed( LDAP *ld, LDAPControl *ctrl );
155 #endif
156
157 static struct tool_ctrls_t {
158         const char      *oid;
159         unsigned        mask;
160         print_ctrl_fn   func;
161 } tool_ctrl_response[] = {
162         { LDAP_CONTROL_PRE_READ,                        TOOL_ALL,       print_preread },
163         { LDAP_CONTROL_POST_READ,                       TOOL_ALL,       print_postread },
164         { LDAP_CONTROL_PAGEDRESULTS,                    TOOL_SEARCH,    print_paged_results },
165 #ifdef LDAP_CONTROL_AUTHZID_RESPONSE
166         /* this is generally deprecated in favor of LDAP WhoAmI? operation, hence only supported as a VC inner control */
167         { LDAP_CONTROL_AUTHZID_RESPONSE,                TOOL_VC,        print_authzid },
168 #endif
169 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
170         { LDAP_CONTROL_PASSWORDPOLICYRESPONSE,          TOOL_ALL,       print_ppolicy },
171 #endif
172         { LDAP_CONTROL_SORTRESPONSE,    TOOL_SEARCH,    print_sss },
173         { LDAP_CONTROL_VLVRESPONSE,             TOOL_SEARCH,    print_vlv },
174 #ifdef LDAP_CONTROL_X_DEREF
175         { LDAP_CONTROL_X_DEREF,                         TOOL_SEARCH,    print_deref },
176 #endif
177 #ifdef LDAP_CONTROL_X_WHATFAILED
178         { LDAP_CONTROL_X_WHATFAILED,                    TOOL_ALL,       print_whatfailed },
179 #endif
180         { NULL,                                         0,              NULL }
181 };
182
183 /* "features" */
184 enum { Intr_None = 0, Intr_Abandon, Intr_Cancel, Intr_Ignore }; 
185 static volatile sig_atomic_t    gotintr, abcan;
186
187
188 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
189 static int
190 st_value( LDAP *ld, struct berval *value )
191 {
192         char            *ip = NULL, *name = NULL;
193         struct berval   id = { 0 };
194         char            namebuf[ MAXHOSTNAMELEN ];
195
196         if ( gethostname( namebuf, sizeof( namebuf ) ) == 0 ) {
197                 struct hostent  *h;
198                 struct in_addr  addr;
199
200                 name = namebuf;
201
202                 h = gethostbyname( name );
203                 if ( h != NULL ) {
204                         AC_MEMCPY( &addr, h->h_addr, sizeof( addr ) );
205                         ip = inet_ntoa( addr );
206                 }
207         }
208
209         if ( sessionTrackingName != NULL ) {
210                 ber_str2bv( sessionTrackingName , 0, 0, &id );
211         } else
212 #ifdef HAVE_CYRUS_SASL
213         if ( sasl_authz_id != NULL ) {
214                 ber_str2bv( sasl_authz_id, 0, 0, &id );
215
216         } else if ( sasl_authc_id != NULL ) {
217                 ber_str2bv( sasl_authc_id, 0, 0, &id );
218
219         } else 
220 #endif /* HAVE_CYRUS_SASL */
221         if ( binddn != NULL ) {
222                 ber_str2bv( binddn, 0, 0, &id );
223         }
224
225         if ( ldap_create_session_tracking_value( ld,
226                 ip, name, LDAP_CONTROL_X_SESSION_TRACKING_USERNAME,
227                 &id, &stValue ) )
228         {
229                 fprintf( stderr, _("Session tracking control encoding error!\n") );
230                 return -1;
231         }
232
233         return 0;
234 }
235 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
236
237 RETSIGTYPE
238 do_sig( int sig )
239 {
240         gotintr = abcan;
241 }
242
243 void
244 tool_init( tool_type_t type )
245 {
246         tool_type = type;
247         ldap_pvt_setlocale(LC_MESSAGES, "");
248         ldap_pvt_bindtextdomain(OPENLDAP_PACKAGE, LDAP_LOCALEDIR);
249         ldap_pvt_textdomain(OPENLDAP_PACKAGE);
250 }
251
252 void
253 tool_destroy( void )
254 {
255         static int destroyed;
256         if ( destroyed++ )
257                 return;
258
259 #ifdef HAVE_CYRUS_SASL
260         sasl_done();
261 #endif
262 #ifdef HAVE_TLS
263         ldap_pvt_tls_destroy();
264 #endif
265
266         if ( ldapuri != NULL ) {
267                 ber_memfree( ldapuri );
268                 ldapuri = NULL;
269         }
270
271         if ( pr_cookie.bv_val != NULL ) {
272                 ber_memfree( pr_cookie.bv_val );
273                 BER_BVZERO( &pr_cookie );
274         }
275
276         if ( binddn != NULL ) {
277                 ber_memfree( binddn );
278                 binddn = NULL;
279         }
280
281         if ( passwd.bv_val != NULL ) {
282                 ber_memfree( passwd.bv_val );
283                 BER_BVZERO( &passwd );
284         }
285
286 #ifdef HAVE_CYRUS_SASL
287         if ( sasl_mech != NULL ) {
288                 ber_memfree( sasl_mech );
289                 sasl_mech = NULL;
290         }
291 #endif /* HAVE_CYRUS_SASL */
292
293         if ( infile != NULL ) {
294                 ber_memfree( infile );
295                 infile = NULL;
296         }
297
298         if ( assertion ) {
299                 ber_memfree( assertion );
300                 assertion = NULL;
301         }
302
303         if ( authzid ) {
304                 ber_memfree( authzid );
305                 authzid = NULL;
306         }
307
308         if ( proxydn ) {
309                 ber_memfree( proxydn );
310                 proxydn = NULL;
311         }
312
313         if ( preread_attrs ) {
314                 ber_memfree( preread_attrs );
315                 preread_attrs = NULL;
316         }
317
318         if ( postread_attrs ) {
319                 ber_memfree( postread_attrs );
320                 postread_attrs = NULL;
321         }
322
323 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
324         if ( !BER_BVISNULL( &stValue ) ) {
325                 ber_memfree( stValue.bv_val );
326                 BER_BVZERO( &stValue );
327         }
328
329         if ( sessionTrackingName ) {
330                 ber_memfree( sessionTrackingName );
331                 sessionTrackingName = NULL;
332         }
333 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
334 }
335
336 void
337 tool_common_usage( void )
338 {
339         static const char *const descriptions[] = {
340 N_("  -d level   set LDAP debugging level to `level'\n"),
341 N_("  -D binddn  bind DN\n"),
342 N_("  -e [!]<ext>[=<extparam>] general extensions (! indicates criticality)\n")
343 N_("             [!]assert=<filter>     (RFC 4528; a RFC 4515 Filter string)\n")
344 N_("             [!]authzid=<authzid>   (RFC 4370; \"dn:<dn>\" or \"u:<user>\")\n")
345 N_("             [!]bauthzid            (RFC 3829)\n")
346 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
347 #if 0
348                  /* non-advertized support for proxyDN */
349 N_("             [!]proxydn=<dn>        (a RFC 4514 DN string)\n")
350 #endif
351 #endif
352 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
353 N_("             [!]chaining[=<resolveBehavior>[/<continuationBehavior>]]\n")
354 N_("                     one of \"chainingPreferred\", \"chainingRequired\",\n")
355 N_("                     \"referralsPreferred\", \"referralsRequired\"\n")
356 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
357 N_("             [!]manageDSAit         (RFC 3296)\n")
358 N_("             [!]noop\n")
359 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
360 N_("             ppolicy\n")
361 #endif
362 N_("             [!]postread[=<attrs>]  (RFC 4527; comma-separated attr list)\n")
363 N_("             [!]preread[=<attrs>]   (RFC 4527; comma-separated attr list)\n")
364 N_("             [!]relax\n")
365 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
366 N_("             [!]sessiontracking[=<username>]\n")
367 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
368 N_("             abandon, cancel, ignore (SIGINT sends abandon/cancel,\n"
369    "             or ignores response; if critical, doesn't wait for SIGINT.\n"
370    "             not really controls)\n")
371 N_("  -h host    LDAP server\n"),
372 N_("  -H URI     LDAP Uniform Resource Identifier(s)\n"),
373 N_("  -I         use SASL Interactive mode\n"),
374 N_("  -n         show what would be done but don't actually do it\n"),
375 N_("  -N         do not use reverse DNS to canonicalize SASL host name\n"),
376 N_("  -O props   SASL security properties\n"),
377 N_("  -o <opt>[=<optparam>] general options\n"),
378 N_("             nettimeout=<timeout> (in seconds, or \"none\" or \"max\")\n"),
379 N_("             ldif-wrap=<width> (in columns, or \"no\" for no wrapping)\n"),
380 N_("  -p port    port on LDAP server\n"),
381 N_("  -Q         use SASL Quiet mode\n"),
382 N_("  -R realm   SASL realm\n"),
383 N_("  -U authcid SASL authentication identity\n"),
384 N_("  -v         run in verbose mode (diagnostics to standard output)\n"),
385 N_("  -V         print version info (-VV only)\n"),
386 N_("  -w passwd  bind password (for simple authentication)\n"),
387 N_("  -W         prompt for bind password\n"),
388 N_("  -x         Simple authentication\n"),
389 N_("  -X authzid SASL authorization identity (\"dn:<dn>\" or \"u:<user>\")\n"),
390 N_("  -y file    Read password from file\n"),
391 N_("  -Y mech    SASL mechanism\n"),
392 N_("  -Z         Start TLS request (-ZZ to require successful response)\n"),
393 NULL
394         };
395         const char *const *cpp;
396
397         fputs( _("Common options:\n"), stderr );
398         for( cpp = descriptions; *cpp != NULL; cpp++ ) {
399                 if( strchr( options, (*cpp)[3] ) || (*cpp)[3] == ' ' ) {
400                         fputs( _(*cpp), stderr );
401                 }
402         }
403
404         tool_destroy();
405 }
406
407 void tool_perror(
408         const char *func,
409         int err,
410         const char *extra,
411         const char *matched,
412         const char *info,
413         char **refs )
414 {
415         fprintf( stderr, "%s: %s (%d)%s\n",
416                 func, ldap_err2string( err ), err, extra ? extra : "" );
417
418         if ( matched && *matched ) {
419                 fprintf( stderr, _("\tmatched DN: %s\n"), matched );
420         }
421
422         if ( info && *info ) {
423                 fprintf( stderr, _("\tadditional info: %s\n"), info );
424         }
425
426         if ( refs && *refs ) {
427                 int i;
428                 fprintf( stderr, _("\treferrals:\n") );
429                 for( i=0; refs[i]; i++ ) {
430                         fprintf( stderr, "\t\t%s\n", refs[i] );
431                 }
432         }
433 }
434
435
436 void
437 tool_args( int argc, char **argv )
438 {
439         int i;
440
441         while (( i = getopt( argc, argv, options )) != EOF ) {
442                 int crit, ival;
443                 char *control, *cvalue, *next;
444                 switch( i ) {
445                 case 'c':       /* continuous operation mode */
446                         contoper++;
447                         break;
448                 case 'C':       /* referrals: obsolete */
449                         referrals++;
450                         break;
451                 case 'd':
452                         ival = strtol( optarg, &next, 10 );
453                         if (next == NULL || next[0] != '\0') {
454                                 fprintf( stderr, "%s: unable to parse debug value \"%s\"\n", prog, optarg);
455                                 exit(EXIT_FAILURE);
456                         }
457                         debug |= ival;
458                         break;
459                 case 'D':       /* bind DN */
460                         if( binddn != NULL ) {
461                                 fprintf( stderr, "%s: -D previously specified\n", prog );
462                                 exit( EXIT_FAILURE );
463                         }
464                         binddn = ber_strdup( optarg );
465                         break;
466                 case 'e':       /* general extensions (controls and such) */
467                         /* should be extended to support comma separated list of
468                          *      [!]key[=value] parameters, e.g.  -e !foo,bar=567
469                          */
470
471                         crit = 0;
472                         cvalue = NULL;
473                         while ( optarg[0] == '!' ) {
474                                 crit++;
475                                 optarg++;
476                         }
477
478                         control = ber_strdup( optarg );
479                         if ( (cvalue = strchr( control, '=' )) != NULL ) {
480                                 *cvalue++ = '\0';
481                         }
482
483                         if ( strcasecmp( control, "assert" ) == 0 ) {
484                                 if( assertctl ) {
485                                         fprintf( stderr, "assert control previously specified\n");
486                                         exit( EXIT_FAILURE );
487                                 }
488                                 if( cvalue == NULL ) {
489                                         fprintf( stderr, "assert: control value expected\n" );
490                                         usage();
491                                 }
492
493                                 assertctl = 1 + crit;
494
495                                 assert( assertion == NULL );
496                                 assertion = ber_strdup( cvalue );
497
498                         } else if ( strcasecmp( control, "authzid" ) == 0 ) {
499                                 if( authzid != NULL ) {
500                                         fprintf( stderr, "authzid control previously specified\n");
501                                         exit( EXIT_FAILURE );
502                                 }
503 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
504                                 if( proxydn != NULL ) {
505                                         fprintf( stderr, "authzid control incompatible with proxydn\n");
506                                         exit( EXIT_FAILURE );
507                                 }
508 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
509                                 if( cvalue == NULL ) {
510                                         fprintf( stderr, "authzid: control value expected\n" );
511                                         usage();
512                                 }
513                                 if( !crit ) {
514                                         fprintf( stderr, "authzid: must be marked critical\n" );
515                                         usage();
516                                 } else if ( crit > 1 ) {
517                                         /* purposely flag proxied authorization
518                                          * as non-critical, to test DSA */
519                                         authzcrit = 0;
520                                 }
521
522                                 assert( authzid == NULL );
523                                 authzid = ber_strdup( cvalue );
524
525 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
526                         } else if ( strcasecmp( control, "proxydn" ) == 0 ) {
527                                 if( proxydn != NULL ) {
528                                         fprintf( stderr, "proxydn control previously specified\n");
529                                         exit( EXIT_FAILURE );
530                                 }
531                                 if( authzid != NULL ) {
532                                         fprintf( stderr, "proxydn control incompatible with authzid\n");
533                                         exit( EXIT_FAILURE );
534                                 }
535                                 if( cvalue == NULL ) {
536                                         fprintf( stderr, "proxydn: control value expected\n" );
537                                         usage();
538                                 }
539                                 if( !crit ) {
540                                         fprintf( stderr, "proxydn: must be marked critical\n" );
541                                         usage();
542                                 } else if ( crit > 1 ) {
543                                         /* purposely flag proxied authorization
544                                          * as non-critical, to test DSA */
545                                         authzcrit = 0;
546                                 }
547
548                                 assert( proxydn == NULL );
549                                 proxydn = ber_strdup( cvalue );
550 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
551
552                         } else if ( strcasecmp( control, "bauthzid" ) == 0 ) {
553                                 if( bauthzid ) {
554                                         fprintf( stderr, "bauthzid control previously specified\n");
555                                         exit( EXIT_FAILURE );
556                                 }
557                                 if( cvalue != NULL ) {
558                                         fprintf( stderr, "bauthzid: no control value expected\n" );
559                                         usage();
560                                 }
561                                 bauthzid = 1 + crit;
562
563                         } else if ( ( strcasecmp( control, "relax" ) == 0 ) ||
564                                 ( strcasecmp( control, "manageDIT" ) == 0 ) )
565                         {
566                                 if( manageDIT ) {
567                                         fprintf( stderr,
568                                                 "relax control previously specified\n");
569                                         exit( EXIT_FAILURE );
570                                 }
571                                 if( cvalue != NULL ) {
572                                         fprintf( stderr,
573                                                 "relax: no control value expected\n" );
574                                         usage();
575                                 }
576
577                                 manageDIT = 1 + crit;
578
579                         } else if ( strcasecmp( control, "manageDSAit" ) == 0 ) {
580                                 if( manageDSAit ) {
581                                         fprintf( stderr,
582                                                 "manageDSAit control previously specified\n");
583                                         exit( EXIT_FAILURE );
584                                 }
585                                 if( cvalue != NULL ) {
586                                         fprintf( stderr,
587                                                 "manageDSAit: no control value expected\n" );
588                                         usage();
589                                 }
590
591                                 manageDSAit = 1 + crit;
592
593                         } else if ( strcasecmp( control, "noop" ) == 0 ) {
594                                 if( noop ) {
595                                         fprintf( stderr, "noop control previously specified\n");
596                                         exit( EXIT_FAILURE );
597                                 }
598                                 if( cvalue != NULL ) {
599                                         fprintf( stderr, "noop: no control value expected\n" );
600                                         usage();
601                                 }
602
603                                 noop = 1 + crit;
604
605 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
606                         } else if ( strcasecmp( control, "ppolicy" ) == 0 ) {
607                                 if( ppolicy ) {
608                                         fprintf( stderr, "ppolicy control previously specified\n");
609                                         exit( EXIT_FAILURE );
610                                 }
611                                 if( cvalue != NULL ) {
612                                         fprintf( stderr, "ppolicy: no control value expected\n" );
613                                         usage();
614                                 }
615                                 if( crit ) {
616                                         fprintf( stderr, "ppolicy: critical flag not allowed\n" );
617                                         usage();
618                                 }
619
620                                 ppolicy = 1;
621 #endif
622
623                         } else if ( strcasecmp( control, "preread" ) == 0 ) {
624                                 if( preread ) {
625                                         fprintf( stderr, "preread control previously specified\n");
626                                         exit( EXIT_FAILURE );
627                                 }
628
629                                 preread = 1 + crit;
630                                 preread_attrs = ber_strdup( cvalue );
631
632                         } else if ( strcasecmp( control, "postread" ) == 0 ) {
633                                 if( postread ) {
634                                         fprintf( stderr, "postread control previously specified\n");
635                                         exit( EXIT_FAILURE );
636                                 }
637
638                                 postread = 1 + crit;
639                                 postread_attrs = ber_strdup( cvalue );
640
641 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
642                         } else if ( strcasecmp( control, "chaining" ) == 0 ) {
643                                 if ( chaining ) {
644                                         fprintf( stderr, "chaining control previously specified\n");
645                                         exit( EXIT_FAILURE );
646                                 }
647
648                                 chaining = 1 + crit;
649
650                                 if ( cvalue != NULL ) {
651                                         char    *continuation;
652
653                                         continuation = strchr( cvalue, '/' );
654                                         if ( continuation ) {
655                                                 /* FIXME: this makes sense only in searches */
656                                                 *continuation++ = '\0';
657                                                 if ( strcasecmp( continuation, "chainingPreferred" ) == 0 ) {
658                                                         chainingContinuation = LDAP_CHAINING_PREFERRED;
659                                                 } else if ( strcasecmp( continuation, "chainingRequired" ) == 0 ) {
660                                                         chainingContinuation = LDAP_CHAINING_REQUIRED;
661                                                 } else if ( strcasecmp( continuation, "referralsPreferred" ) == 0 ) {
662                                                         chainingContinuation = LDAP_REFERRALS_PREFERRED;
663                                                 } else if ( strcasecmp( continuation, "referralsRequired" ) == 0 ) {
664                                                         chainingContinuation = LDAP_REFERRALS_REQUIRED;
665                                                 } else {
666                                                         fprintf( stderr,
667                                                                 "chaining behavior control "
668                                                                 "continuation value \"%s\" invalid\n",
669                                                                 continuation );
670                                                         exit( EXIT_FAILURE );
671                                                 }
672                                         }
673         
674                                         if ( strcasecmp( cvalue, "chainingPreferred" ) == 0 ) {
675                                                 chainingResolve = LDAP_CHAINING_PREFERRED;
676                                         } else if ( strcasecmp( cvalue, "chainingRequired" ) == 0 ) {
677                                                 chainingResolve = LDAP_CHAINING_REQUIRED;
678                                         } else if ( strcasecmp( cvalue, "referralsPreferred" ) == 0 ) {
679                                                 chainingResolve = LDAP_REFERRALS_PREFERRED;
680                                         } else if ( strcasecmp( cvalue, "referralsRequired" ) == 0 ) {
681                                                 chainingResolve = LDAP_REFERRALS_REQUIRED;
682                                         } else {
683                                                 fprintf( stderr,
684                                                         "chaining behavior control "
685                                                         "resolve value \"%s\" invalid\n",
686                                                         cvalue);
687                                                 exit( EXIT_FAILURE );
688                                         }
689                                 }
690 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
691
692 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
693                         } else if ( strcasecmp( control, "sessiontracking" ) == 0 ) {
694                                 if ( sessionTracking ) {
695                                         fprintf( stderr, "%s: session tracking can be only specified once\n", prog );
696                                         exit( EXIT_FAILURE );
697                                 }
698                                 sessionTracking = 1;
699                                 if ( crit ) {
700                                         fprintf( stderr, "sessiontracking: critical flag not allowed\n" );
701                                         usage();
702                                 }
703                                 if ( cvalue ) {
704                                         sessionTrackingName = ber_strdup( cvalue );
705                                 }
706 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
707
708                         /* this shouldn't go here, really; but it's a feature... */
709                         } else if ( strcasecmp( control, "abandon" ) == 0 ) {
710                                 abcan = Intr_Abandon;
711                                 if ( crit ) {
712                                         gotintr = abcan;
713                                 }
714
715                         } else if ( strcasecmp( control, "cancel" ) == 0 ) {
716                                 abcan = Intr_Cancel;
717                                 if ( crit ) {
718                                         gotintr = abcan;
719                                 }
720
721                         } else if ( strcasecmp( control, "ignore" ) == 0 ) {
722                                 abcan = Intr_Ignore;
723                                 if ( crit ) {
724                                         gotintr = abcan;
725                                 }
726
727                         } else if ( tool_is_oid( control ) ) {
728                                 LDAPControl     *tmpctrls, ctrl;
729
730                                 if ( unknown_ctrls != NULL ) {
731                                         int i;
732                                         for ( i = 0; unknown_ctrls[ i ].ldctl_oid != NULL; i++ ) {
733                                                 if ( strcmp( control, unknown_ctrls[ i ].ldctl_oid ) == 0 ) {
734                                                         fprintf( stderr, "%s control previously specified\n", control );
735                                                         exit( EXIT_FAILURE );
736                                                 }
737                                         }
738                                 }
739
740                                 tmpctrls = (LDAPControl *)ber_memrealloc( unknown_ctrls,
741                                         (unknown_ctrls_num + 1)*sizeof( LDAPControl ) );
742                                 if ( tmpctrls == NULL ) {
743                                         fprintf( stderr, "%s: no memory?\n", prog );
744                                         exit( EXIT_FAILURE );
745                                 }
746                                 unknown_ctrls = tmpctrls;
747                                 ctrl.ldctl_oid = control;
748                                 /* don't free it */
749                                 control = NULL;
750                                 ctrl.ldctl_value.bv_val = NULL;
751                                 ctrl.ldctl_value.bv_len = 0;
752                                 ctrl.ldctl_iscritical = crit;
753
754                                 if ( cvalue != NULL ) {
755                                         struct berval   bv;
756                                         size_t          len = strlen( cvalue );
757                                         int             retcode;
758
759                                         bv.bv_len = LUTIL_BASE64_DECODE_LEN( len );
760                                         bv.bv_val = ber_memalloc( bv.bv_len + 1 );
761
762                                         retcode = lutil_b64_pton( cvalue,
763                                                 (unsigned char *)bv.bv_val,
764                                                 bv.bv_len );
765
766                                         if ( retcode == -1 || (unsigned) retcode > bv.bv_len ) {
767                                                 fprintf( stderr, "Unable to parse value of general control %s\n",
768                                                         control );
769                                                 usage();
770                                         }
771
772                                         bv.bv_len = retcode;
773                                         ctrl.ldctl_value = bv;
774                                 }
775
776                                 unknown_ctrls[ unknown_ctrls_num ] = ctrl;
777                                 unknown_ctrls_num++;
778
779                         } else {
780                                 fprintf( stderr, "Invalid general control name: %s\n",
781                                         control );
782                                 usage();
783                         }
784                         if ( control ) {
785                                 ber_memfree( control );  
786                                 control = NULL;
787                         }
788                         break;
789                 case 'f':       /* read from file */
790                         if( infile != NULL ) {
791                                 fprintf( stderr, "%s: -f previously specified\n", prog );
792                                 exit( EXIT_FAILURE );
793                         }
794                         infile = ber_strdup( optarg );
795                         break;
796                 case 'h':       /* ldap host */
797                         if( ldaphost != NULL ) {
798                                 fprintf( stderr, "%s: -h previously specified\n", prog );
799                                 exit( EXIT_FAILURE );
800                         }
801                         ldaphost = ber_strdup( optarg );
802                         break;
803                 case 'H':       /* ldap URI */
804                         if( ldapuri != NULL ) {
805                                 fprintf( stderr, "%s: -H previously specified\n", prog );
806                                 exit( EXIT_FAILURE );
807                         }
808                         ldapuri = ber_strdup( optarg );
809                         break;
810                 case 'I':
811 #ifdef HAVE_CYRUS_SASL
812                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
813                                 fprintf( stderr, "%s: incompatible previous "
814                                         "authentication choice\n",
815                                         prog );
816                                 exit( EXIT_FAILURE );
817                         }
818                         authmethod = LDAP_AUTH_SASL;
819                         sasl_flags = LDAP_SASL_INTERACTIVE;
820                         break;
821 #else
822                         fprintf( stderr, "%s: was not compiled with SASL support\n",
823                                 prog );
824                         exit( EXIT_FAILURE );
825 #endif
826                 case 'M':
827                         /* enable Manage DSA IT */
828                         manageDSAit++;
829                         break;
830                 case 'n':       /* print operations, don't actually do them */
831                         dont++;
832                         break;
833                 case 'N':
834                         nocanon++;
835                         break;
836                 case 'o':
837                         control = ber_strdup( optarg );
838                         if ( (cvalue = strchr( control, '=' )) != NULL ) {
839                                 *cvalue++ = '\0';
840                         }
841
842                         if ( strcasecmp( control, "nettimeout" ) == 0 ) {
843                                 if( nettimeout.tv_sec != -1 ) {
844                                         fprintf( stderr, "nettimeout option previously specified\n");
845                                         exit( EXIT_FAILURE );
846                                 }
847                                 if( cvalue == NULL || cvalue[0] == '\0' ) {
848                                         fprintf( stderr, "nettimeout: option value expected\n" );
849                                         usage();
850                                 }
851                                 if ( strcasecmp( cvalue, "none" ) == 0 ) {
852                                         nettimeout.tv_sec = 0;
853                                 } else if ( strcasecmp( cvalue, "max" ) == 0 ) {
854                                         nettimeout.tv_sec = LDAP_MAXINT;
855                                 } else {
856                                         ival = strtol( cvalue, &next, 10 );
857                                         if ( next == NULL || next[0] != '\0' ) {
858                                                 fprintf( stderr,
859                                                         _("Unable to parse network timeout \"%s\"\n"), cvalue );
860                                                 exit( EXIT_FAILURE );
861                                         }
862                                         nettimeout.tv_sec = ival;
863                                 }
864                                 if( nettimeout.tv_sec < 0 || nettimeout.tv_sec > LDAP_MAXINT ) {
865                                         fprintf( stderr, _("%s: invalid network timeout (%ld) specified\n"),
866                                                 prog, (long)nettimeout.tv_sec );
867                                         exit( EXIT_FAILURE );
868                                 }
869
870                         } else if ( strcasecmp( control, "ldif-wrap" ) == 0 ) {
871                                 if ( cvalue == 0 ) {
872                                         ldif_wrap = LDIF_LINE_WIDTH;
873
874                                 } else if ( strcasecmp( cvalue, "no" ) == 0 ) {
875                                         ldif_wrap = LDIF_LINE_WIDTH_MAX;
876
877                                 } else {
878                                         unsigned int u;
879                                         if ( lutil_atou( &u, cvalue ) ) {
880                                                 fprintf( stderr,
881                                                         _("Unable to parse ldif-wrap=\"%s\"\n"), cvalue );
882                                                 exit( EXIT_FAILURE );
883                                         }
884                                         ldif_wrap = (ber_len_t)u;
885                                 }
886
887                         } else {
888                                 fprintf( stderr, "Invalid general option name: %s\n",
889                                         control );
890                                 usage();
891                         }
892                         ber_memfree(control);
893                         break;
894                 case 'O':
895 #ifdef HAVE_CYRUS_SASL
896                         if( sasl_secprops != NULL ) {
897                                 fprintf( stderr, "%s: -O previously specified\n", prog );
898                                 exit( EXIT_FAILURE );
899                         }
900                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
901                                 fprintf( stderr, "%s: incompatible previous "
902                                         "authentication choice\n", prog );
903                                 exit( EXIT_FAILURE );
904                         }
905                         authmethod = LDAP_AUTH_SASL;
906                         sasl_secprops = ber_strdup( optarg );
907 #else
908                         fprintf( stderr, "%s: not compiled with SASL support\n", prog );
909                         exit( EXIT_FAILURE );
910 #endif
911                         break;
912                 case 'p':
913                         if( ldapport ) {
914                                 fprintf( stderr, "%s: -p previously specified\n", prog );
915                                 exit( EXIT_FAILURE );
916                         }
917                         ival = strtol( optarg, &next, 10 );
918                         if ( next == NULL || next[0] != '\0' ) {
919                                 fprintf( stderr, "%s: unable to parse port number \"%s\"\n", prog, optarg );
920                                 exit( EXIT_FAILURE );
921                         }
922                         ldapport = ival;
923                         break;
924                 case 'P':
925                         ival = strtol( optarg, &next, 10 );
926                         if ( next == NULL || next[0] != '\0' ) {
927                                 fprintf( stderr, "%s: unable to parse protocol version \"%s\"\n", prog, optarg );
928                                 exit( EXIT_FAILURE );
929                         }
930                         switch( ival ) {
931                         case 2:
932                                 if( protocol == LDAP_VERSION3 ) {
933                                         fprintf( stderr, "%s: -P 2 incompatible with version %d\n",
934                                                 prog, protocol );
935                                         exit( EXIT_FAILURE );
936                                 }
937                                 protocol = LDAP_VERSION2;
938                                 break;
939                         case 3:
940                                 if( protocol == LDAP_VERSION2 ) {
941                                         fprintf( stderr, "%s: -P 2 incompatible with version %d\n",
942                                                 prog, protocol );
943                                         exit( EXIT_FAILURE );
944                                 }
945                                 protocol = LDAP_VERSION3;
946                                 break;
947                         default:
948                                 fprintf( stderr, "%s: protocol version should be 2 or 3\n",
949                                         prog );
950                                 usage();
951                         }
952                         break;
953                 case 'Q':
954 #ifdef HAVE_CYRUS_SASL
955                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
956                                 fprintf( stderr, "%s: incompatible previous "
957                                         "authentication choice\n",
958                                         prog );
959                                 exit( EXIT_FAILURE );
960                         }
961                         authmethod = LDAP_AUTH_SASL;
962                         sasl_flags = LDAP_SASL_QUIET;
963                         break;
964 #else
965                         fprintf( stderr, "%s: not compiled with SASL support\n",
966                                 prog );
967                         exit( EXIT_FAILURE );
968 #endif
969                 case 'R':
970 #ifdef HAVE_CYRUS_SASL
971                         if( sasl_realm != NULL ) {
972                                 fprintf( stderr, "%s: -R previously specified\n", prog );
973                                 exit( EXIT_FAILURE );
974                         }
975                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
976                                 fprintf( stderr, "%s: incompatible previous "
977                                         "authentication choice\n",
978                                         prog );
979                                 exit( EXIT_FAILURE );
980                         }
981                         authmethod = LDAP_AUTH_SASL;
982                         sasl_realm = ber_strdup( optarg );
983 #else
984                         fprintf( stderr, "%s: not compiled with SASL support\n",
985                                 prog );
986                         exit( EXIT_FAILURE );
987 #endif
988                         break;
989                 case 'U':
990 #ifdef HAVE_CYRUS_SASL
991                         if( sasl_authc_id != NULL ) {
992                                 fprintf( stderr, "%s: -U previously specified\n", prog );
993                                 exit( EXIT_FAILURE );
994                         }
995                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
996                                 fprintf( stderr, "%s: incompatible previous "
997                                         "authentication choice\n",
998                                         prog );
999                                 exit( EXIT_FAILURE );
1000                         }
1001                         authmethod = LDAP_AUTH_SASL;
1002                         sasl_authc_id = ber_strdup( optarg );
1003 #else
1004                         fprintf( stderr, "%s: not compiled with SASL support\n",
1005                                 prog );
1006                         exit( EXIT_FAILURE );
1007 #endif
1008                         break;
1009                 case 'v':       /* verbose mode */
1010                         verbose++;
1011                         break;
1012                 case 'V':       /* version */
1013                         version++;
1014                         break;
1015                 case 'w':       /* password */
1016                         passwd.bv_val = ber_strdup( optarg );
1017                         {
1018                                 char* p;
1019
1020                                 for( p = optarg; *p != '\0'; p++ ) {
1021                                         *p = '\0';
1022                                 }
1023                         }
1024                         passwd.bv_len = strlen( passwd.bv_val );
1025                         break;
1026                 case 'W':
1027                         want_bindpw++;
1028                         break;
1029                 case 'y':
1030                         pw_file = optarg;
1031                         break;
1032                 case 'Y':
1033 #ifdef HAVE_CYRUS_SASL
1034                         if( sasl_mech != NULL ) {
1035                                 fprintf( stderr, "%s: -Y previously specified\n", prog );
1036                                 exit( EXIT_FAILURE );
1037                         }
1038                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
1039                                 fprintf( stderr,
1040                                         "%s: incompatible with authentication choice\n", prog );
1041                                 exit( EXIT_FAILURE );
1042                         }
1043                         authmethod = LDAP_AUTH_SASL;
1044                         sasl_mech = ber_strdup( optarg );
1045 #else
1046                         fprintf( stderr, "%s: not compiled with SASL support\n", prog );
1047                         exit( EXIT_FAILURE );
1048 #endif
1049                         break;
1050                 case 'x':
1051                         if( authmethod != -1 && authmethod != LDAP_AUTH_SIMPLE ) {
1052                                 fprintf( stderr, "%s: incompatible with previous "
1053                                         "authentication choice\n", prog );
1054                                 exit( EXIT_FAILURE );
1055                         }
1056                         authmethod = LDAP_AUTH_SIMPLE;
1057                         break;
1058                 case 'X':
1059 #ifdef HAVE_CYRUS_SASL
1060                         if( sasl_authz_id != NULL ) {
1061                                 fprintf( stderr, "%s: -X previously specified\n", prog );
1062                                 exit( EXIT_FAILURE );
1063                         }
1064                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
1065                                 fprintf( stderr, "%s: -X incompatible with "
1066                                         "authentication choice\n", prog );
1067                                 exit( EXIT_FAILURE );
1068                         }
1069                         authmethod = LDAP_AUTH_SASL;
1070                         sasl_authz_id = ber_strdup( optarg );
1071 #else
1072                         fprintf( stderr, "%s: not compiled with SASL support\n", prog );
1073                         exit( EXIT_FAILURE );
1074 #endif
1075                         break;
1076                 case 'Z':
1077 #ifdef HAVE_TLS
1078                         use_tls++;
1079 #else
1080                         fprintf( stderr, "%s: not compiled with TLS support\n", prog );
1081                         exit( EXIT_FAILURE );
1082 #endif
1083                         break;
1084                 default:
1085                         if( handle_private_option( i ) ) break;
1086                         fprintf( stderr, "%s: unrecognized option -%c\n",
1087                                 prog, optopt );
1088                         usage();
1089                 }
1090         }
1091
1092         {
1093                 /* prevent bad linking */
1094                 LDAPAPIInfo api;
1095                 api.ldapai_info_version = LDAP_API_INFO_VERSION;
1096
1097                 if ( ldap_get_option(NULL, LDAP_OPT_API_INFO, &api)
1098                         != LDAP_OPT_SUCCESS )
1099                 {
1100                         fprintf( stderr, "%s: ldap_get_option(API_INFO) failed\n", prog );
1101                         exit( EXIT_FAILURE );
1102                 }
1103
1104                 if (api.ldapai_info_version != LDAP_API_INFO_VERSION) {
1105                         fprintf( stderr, "LDAP APIInfo version mismatch: "
1106                                 "library %d, header %d\n",
1107                                 api.ldapai_info_version, LDAP_API_INFO_VERSION );
1108                         exit( EXIT_FAILURE );
1109                 }
1110
1111                 if( api.ldapai_api_version != LDAP_API_VERSION ) {
1112                         fprintf( stderr, "LDAP API version mismatch: "
1113                                 "library %d, header %d\n",
1114                                 api.ldapai_api_version, LDAP_API_VERSION );
1115                         exit( EXIT_FAILURE );
1116                 }
1117
1118                 if( strcmp(api.ldapai_vendor_name, LDAP_VENDOR_NAME ) != 0 ) {
1119                         fprintf( stderr, "LDAP vendor name mismatch: "
1120                                 "library %s, header %s\n",
1121                                 api.ldapai_vendor_name, LDAP_VENDOR_NAME );
1122                         exit( EXIT_FAILURE );
1123                 }
1124
1125                 if( api.ldapai_vendor_version != LDAP_VENDOR_VERSION ) {
1126                         fprintf( stderr, "LDAP vendor version mismatch: "
1127                                 "library %d, header %d\n",
1128                                 api.ldapai_vendor_version, LDAP_VENDOR_VERSION );
1129                         exit( EXIT_FAILURE );
1130                 }
1131
1132                 if (version) {
1133                         fprintf( stderr, "%s: %s\t(LDAP library: %s %d)\n",
1134                                 prog, __Version,
1135                                 LDAP_VENDOR_NAME, LDAP_VENDOR_VERSION );
1136                         if (version > 1) exit( EXIT_SUCCESS );
1137                 }
1138
1139                 ldap_memfree( api.ldapai_vendor_name );
1140                 ber_memvfree( (void **)api.ldapai_extensions );
1141         }
1142
1143         if (protocol == -1)
1144                 protocol = LDAP_VERSION3;
1145
1146         if (authmethod == -1 && protocol > LDAP_VERSION2) {
1147 #ifdef HAVE_CYRUS_SASL
1148                 if ( binddn != NULL ) {
1149                         authmethod = LDAP_AUTH_SIMPLE;
1150                 } else {
1151                         authmethod = LDAP_AUTH_SASL;
1152                 }
1153 #else
1154                 authmethod = LDAP_AUTH_SIMPLE;
1155 #endif
1156         }
1157
1158         if( ldapuri == NULL ) {
1159                 if( ldapport && ( ldaphost == NULL )) {
1160                         fprintf( stderr, "%s: -p without -h is invalid.\n", prog );
1161                         exit( EXIT_FAILURE );
1162                 }
1163         } else {
1164                 if( ldaphost != NULL ) {
1165                         fprintf( stderr, "%s: -H incompatible with -h\n", prog );
1166                         exit( EXIT_FAILURE );
1167                 }
1168                 if( ldapport ) {
1169                         fprintf( stderr, "%s: -H incompatible with -p\n", prog );
1170                         exit( EXIT_FAILURE );
1171                 }
1172         }
1173
1174         if( protocol == LDAP_VERSION2 ) {
1175                 if( assertctl || authzid || manageDIT || manageDSAit ||
1176 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1177                         proxydn ||
1178 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1179 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1180                         chaining ||
1181 #endif
1182 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1183                         sessionTracking ||
1184 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1185                         noop || ppolicy || preread || postread )
1186                 {
1187                         fprintf( stderr, "%s: -e/-M incompatible with LDAPv2\n", prog );
1188                         exit( EXIT_FAILURE );
1189                 }
1190 #ifdef HAVE_TLS
1191                 if( use_tls ) {
1192                         fprintf( stderr, "%s: -Z incompatible with LDAPv2\n", prog );
1193                         exit( EXIT_FAILURE );
1194                 }
1195 #endif
1196 #ifdef HAVE_CYRUS_SASL
1197                 if( authmethod == LDAP_AUTH_SASL ) {
1198                         fprintf( stderr, "%s: -[IOQRUXY] incompatible with LDAPv2\n",
1199                                 prog );
1200                         exit( EXIT_FAILURE );
1201                 }
1202 #endif
1203         }
1204
1205         if ( ( pw_file || want_bindpw ) && !BER_BVISNULL( &passwd ) ) {
1206                 fprintf( stderr, "%s: -%c incompatible with -w\n",
1207                         prog, ( pw_file ? 'y' : 'W' ) );
1208                 exit( EXIT_FAILURE );
1209         }
1210 }
1211
1212
1213 LDAP *
1214 tool_conn_setup( int dont, void (*private_setup)( LDAP * ) )
1215 {
1216         LDAP *ld = NULL;
1217
1218         if ( debug ) {
1219                 if( ber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &debug )
1220                         != LBER_OPT_SUCCESS )
1221                 {
1222                         fprintf( stderr,
1223                                 "Could not set LBER_OPT_DEBUG_LEVEL %d\n", debug );
1224                 }
1225                 if( ldap_set_option( NULL, LDAP_OPT_DEBUG_LEVEL, &debug )
1226                         != LDAP_OPT_SUCCESS )
1227                 {
1228                         fprintf( stderr,
1229                                 "Could not set LDAP_OPT_DEBUG_LEVEL %d\n", debug );
1230                 }
1231         }
1232
1233 #ifdef SIGPIPE
1234         (void) SIGNAL( SIGPIPE, SIG_IGN );
1235 #endif
1236
1237         if ( abcan ) {
1238                 SIGNAL( SIGINT, do_sig );
1239         }
1240
1241         if ( !dont ) {
1242                 int rc;
1243
1244                 if( ( ldaphost != NULL || ldapport ) && ( ldapuri == NULL ) ) {
1245                         /* construct URL */
1246                         LDAPURLDesc url;
1247                         memset( &url, 0, sizeof(url));
1248
1249                         url.lud_scheme = "ldap";
1250                         url.lud_host = ldaphost;
1251                         url.lud_port = ldapport;
1252                         url.lud_scope = LDAP_SCOPE_DEFAULT;
1253
1254                         ldapuri = ldap_url_desc2str( &url );
1255
1256                 } else if ( ldapuri != NULL ) {
1257                         LDAPURLDesc     *ludlist, **ludp;
1258                         char            **urls = NULL;
1259                         int             nurls = 0;
1260
1261                         rc = ldap_url_parselist( &ludlist, ldapuri );
1262                         if ( rc != LDAP_URL_SUCCESS ) {
1263                                 fprintf( stderr,
1264                                         "Could not parse LDAP URI(s)=%s (%d)\n",
1265                                         ldapuri, rc );
1266                                 exit( EXIT_FAILURE );
1267                         }
1268
1269                         for ( ludp = &ludlist; *ludp != NULL; ) {
1270                                 LDAPURLDesc     *lud = *ludp;
1271                                 char            **tmp;
1272
1273                                 if ( lud->lud_dn != NULL && lud->lud_dn[ 0 ] != '\0' &&
1274                                         ( lud->lud_host == NULL || lud->lud_host[0] == '\0' ) )
1275                                 {
1276                                         /* if no host but a DN is provided,
1277                                          * use DNS SRV to gather the host list
1278                                          * and turn it into a list of URIs
1279                                          * using the scheme provided */
1280                                         char    *domain = NULL,
1281                                                 *hostlist = NULL,
1282                                                 **hosts = NULL;
1283                                         int     i,
1284                                                 len_proto = strlen( lud->lud_scheme );
1285
1286                                         if ( ldap_dn2domain( lud->lud_dn, &domain )
1287                                                 || domain == NULL )
1288                                         {
1289                                                 fprintf( stderr,
1290                                                         "DNS SRV: Could not turn "
1291                                                         "DN=\"%s\" into a domain\n",
1292                                                         lud->lud_dn );
1293                                                 goto dnssrv_free;
1294                                         }
1295                                         
1296                                         rc = ldap_domain2hostlist( domain, &hostlist );
1297                                         if ( rc ) {
1298                                                 fprintf( stderr,
1299                                                         "DNS SRV: Could not turn "
1300                                                         "domain=%s into a hostlist\n",
1301                                                         domain );
1302                                                 goto dnssrv_free;
1303                                         }
1304
1305                                         hosts = ldap_str2charray( hostlist, " " );
1306                                         if ( hosts == NULL ) {
1307                                                 fprintf( stderr,
1308                                                         "DNS SRV: Could not parse "
1309                                                         "hostlist=\"%s\"\n",
1310                                                         hostlist );
1311                                                 goto dnssrv_free;
1312                                         }
1313
1314                                         for ( i = 0; hosts[ i ] != NULL; i++ )
1315                                                 /* count'em */ ;
1316
1317                                         tmp = (char **)ber_memrealloc( urls, sizeof( char * ) * ( nurls + i + 1 ) );
1318                                         if ( tmp == NULL ) {
1319                                                 fprintf( stderr,
1320                                                         "DNS SRV: out of memory?\n" );
1321                                                 goto dnssrv_free;
1322                                         }
1323                                         urls = tmp;
1324                                         urls[ nurls ] = NULL;
1325
1326                                         for ( i = 0; hosts[ i ] != NULL; i++ ) {
1327                                                 size_t  len = len_proto
1328                                                         + STRLENOF( "://" )
1329                                                         + strlen( hosts[ i ] )
1330                                                         + 1;
1331
1332                                                 urls[ nurls + i + 1 ] = NULL;
1333                                                 urls[ nurls + i ] = (char *)malloc( sizeof( char ) * len );
1334                                                 if ( urls[ nurls + i ] == NULL ) {
1335                                                         fprintf( stderr,
1336                                                                 "DNS SRV: out of memory?\n" );
1337                                                         goto dnssrv_free;
1338                                                 }
1339
1340                                                 snprintf( urls[ nurls + i ], len, "%s://%s",
1341                                                         lud->lud_scheme, hosts[ i ] );
1342                                         }
1343                                         nurls += i;
1344
1345 dnssrv_free:;
1346                                         ber_memvfree( (void **)hosts );
1347                                         ber_memfree( hostlist );
1348                                         ber_memfree( domain );
1349
1350                                 } else {
1351                                         tmp = (char **)ber_memrealloc( urls, sizeof( char * ) * ( nurls + 2 ) );
1352                                         if ( tmp == NULL ) {
1353                                                 fprintf( stderr,
1354                                                         "DNS SRV: out of memory?\n" );
1355                                                 break;
1356                                         }
1357                                         urls = tmp;
1358                                         urls[ nurls + 1 ] = NULL;
1359
1360                                         urls[ nurls ] = ldap_url_desc2str( lud );
1361                                         if ( urls[ nurls ] == NULL ) {
1362                                                 fprintf( stderr,
1363                                                         "DNS SRV: out of memory?\n" );
1364                                                 break;
1365                                         }
1366                                         nurls++;
1367                                 }
1368
1369                                 *ludp = lud->lud_next;
1370
1371                                 lud->lud_next = NULL;
1372                                 ldap_free_urldesc( lud );
1373                         }
1374
1375                         if ( ludlist != NULL ) {
1376                                 ldap_free_urllist( ludlist );
1377                                 exit( EXIT_FAILURE );
1378
1379                         } else if ( urls == NULL ) {
1380                                 exit( EXIT_FAILURE );
1381                         }
1382
1383                         ldap_memfree( ldapuri );
1384                         ldapuri = ldap_charray2str( urls, " " );
1385                         ber_memvfree( (void **)urls );
1386                 }
1387
1388                 if ( verbose ) {
1389                         fprintf( stderr, "ldap_initialize( %s )\n",
1390                                 ldapuri != NULL ? ldapuri : "<DEFAULT>" );
1391                 }
1392                 rc = ldap_initialize( &ld, ldapuri );
1393                 if( rc != LDAP_SUCCESS ) {
1394                         fprintf( stderr,
1395                                 "Could not create LDAP session handle for URI=%s (%d): %s\n",
1396                                 ldapuri, rc, ldap_err2string(rc) );
1397                         exit( EXIT_FAILURE );
1398                 }
1399
1400                 if( private_setup ) private_setup( ld );
1401
1402                 /* referrals: obsolete */
1403                 if( ldap_set_option( ld, LDAP_OPT_REFERRALS,
1404                         referrals ? LDAP_OPT_ON : LDAP_OPT_OFF ) != LDAP_OPT_SUCCESS )
1405                 {
1406                         fprintf( stderr, "Could not set LDAP_OPT_REFERRALS %s\n",
1407                                 referrals ? "on" : "off" );
1408                         tool_exit( ld, EXIT_FAILURE );
1409                 }
1410
1411 #ifdef HAVE_CYRUS_SASL
1412                 /* canon */
1413                 if( nocanon ) {
1414                         if( ldap_set_option( ld, LDAP_OPT_X_SASL_NOCANON,
1415                                 LDAP_OPT_ON ) != LDAP_OPT_SUCCESS )
1416                         {
1417                                 fprintf( stderr, "Could not set LDAP_OPT_X_SASL_NOCANON on\n" );
1418                                 tool_exit( ld, EXIT_FAILURE );
1419                         }
1420                 }
1421 #endif
1422                 if( ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &protocol )
1423                         != LDAP_OPT_SUCCESS )
1424                 {
1425                         fprintf( stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n",
1426                                 protocol );
1427                         tool_exit( ld, EXIT_FAILURE );
1428                 }
1429
1430                 if ( use_tls ) {
1431                         rc = ldap_start_tls_s( ld, NULL, NULL );
1432                         if ( rc != LDAP_SUCCESS ) {
1433                                 char *msg=NULL;
1434                                 ldap_get_option( ld, LDAP_OPT_DIAGNOSTIC_MESSAGE, (void*)&msg);
1435                                 tool_perror( "ldap_start_tls", rc, NULL, NULL, msg, NULL );
1436                                 ldap_memfree(msg);
1437                                 if ( use_tls > 1 ) {
1438                                         tool_exit( ld, EXIT_FAILURE );
1439                                 }
1440                         }
1441                 }
1442
1443                 if ( nettimeout.tv_sec > 0 ) {
1444                         if ( ldap_set_option( ld, LDAP_OPT_NETWORK_TIMEOUT, (void *) &nettimeout )
1445                                 != LDAP_OPT_SUCCESS )
1446                         {
1447                                 fprintf( stderr, "Could not set LDAP_OPT_NETWORK_TIMEOUT %ld\n",
1448                                         (long)nettimeout.tv_sec );
1449                                 tool_exit( ld, EXIT_FAILURE );
1450                         }
1451                 }
1452         }
1453
1454         return ld;
1455 }
1456
1457
1458 void
1459 tool_bind( LDAP *ld )
1460 {
1461         LDAPControl     **sctrlsp = NULL;
1462         LDAPControl     *sctrls[4];
1463         LDAPControl     sctrl[3];
1464         int             nsctrls = 0;
1465
1466         int rc, msgid;
1467         LDAPMessage *result = NULL;
1468
1469         int err;
1470         char *matched = NULL;
1471         char *info = NULL;
1472         char **refs = NULL;
1473         LDAPControl **ctrls = NULL;
1474         char msgbuf[256];
1475
1476         msgbuf[0] = 0;
1477
1478 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1479         if ( ppolicy ) {
1480                 LDAPControl c;
1481                 c.ldctl_oid = LDAP_CONTROL_PASSWORDPOLICYREQUEST;
1482                 c.ldctl_value.bv_val = NULL;
1483                 c.ldctl_value.bv_len = 0;
1484                 c.ldctl_iscritical = 0;
1485                 sctrl[nsctrls] = c;
1486                 sctrls[nsctrls] = &sctrl[nsctrls];
1487                 sctrls[++nsctrls] = NULL;
1488         }
1489 #endif
1490
1491         if ( bauthzid ) {
1492                 LDAPControl c;
1493
1494                 c.ldctl_oid = LDAP_CONTROL_AUTHZID_REQUEST;
1495                 c.ldctl_iscritical = bauthzid > 1;
1496                 BER_BVZERO( &c.ldctl_value );
1497
1498                 sctrl[nsctrls] = c;
1499                 sctrls[nsctrls] = &sctrl[nsctrls];
1500                 sctrls[++nsctrls] = NULL;
1501         }
1502
1503 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1504         if ( sessionTracking ) {
1505                 LDAPControl c;
1506
1507                 if ( BER_BVISNULL( &stValue) && st_value( ld, &stValue ) ) {
1508                         tool_exit( ld, EXIT_FAILURE );
1509                 }
1510
1511                 c.ldctl_oid = LDAP_CONTROL_X_SESSION_TRACKING;
1512                 c.ldctl_iscritical = 0;
1513                 c.ldctl_value = stValue;
1514
1515                 sctrl[nsctrls] = c;
1516                 sctrls[nsctrls] = &sctrl[nsctrls];
1517                 sctrls[++nsctrls] = NULL;
1518         }
1519 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1520
1521         if ( nsctrls ) {
1522                 sctrlsp = sctrls;
1523         }
1524
1525         assert( nsctrls < (int) (sizeof(sctrls)/sizeof(sctrls[0])) );
1526
1527         if ( pw_file || want_bindpw ) {
1528                 assert( passwd.bv_val == NULL && passwd.bv_len == 0 );
1529
1530                 if ( pw_file ) {
1531                         if ( lutil_get_filed_password( pw_file, &passwd ) ) {
1532                                 tool_exit( ld, EXIT_FAILURE );
1533                         }
1534
1535                 } else {
1536                         char *pw = getpassphrase( _("Enter LDAP Password: ") );
1537                         if ( pw ) {
1538                                 passwd.bv_val = ber_strdup( pw );
1539                                 passwd.bv_len = strlen( passwd.bv_val );
1540                         }
1541                 }
1542         }
1543
1544         if ( authmethod == LDAP_AUTH_SASL ) {
1545 #ifdef HAVE_CYRUS_SASL
1546                 void *defaults;
1547                 const char *rmech = NULL;
1548
1549                 if( sasl_secprops != NULL ) {
1550                         rc = ldap_set_option( ld, LDAP_OPT_X_SASL_SECPROPS,
1551                                 (void *) sasl_secprops );
1552
1553                         if( rc != LDAP_OPT_SUCCESS ) {
1554                                 fprintf( stderr,
1555                                         "Could not set LDAP_OPT_X_SASL_SECPROPS: %s\n",
1556                                         sasl_secprops );
1557                                 tool_exit( ld, LDAP_LOCAL_ERROR );
1558                         }
1559                 }
1560
1561                 defaults = lutil_sasl_defaults( ld,
1562                         sasl_mech,
1563                         sasl_realm,
1564                         sasl_authc_id,
1565                         passwd.bv_val,
1566                         sasl_authz_id );
1567
1568                 do {
1569                         rc = ldap_sasl_interactive_bind( ld, binddn, sasl_mech,
1570                                 sctrlsp, NULL, sasl_flags, lutil_sasl_interact, defaults,
1571                                 result, &rmech, &msgid );
1572
1573                         if ( rc != LDAP_SASL_BIND_IN_PROGRESS )
1574                                 break;
1575
1576                         ldap_msgfree( result );
1577
1578                         if ( ldap_result( ld, msgid, LDAP_MSG_ALL, NULL, &result ) == -1 || !result ) {
1579                                 ldap_get_option( ld, LDAP_OPT_RESULT_CODE, (void*)&err );
1580                                 ldap_get_option( ld, LDAP_OPT_DIAGNOSTIC_MESSAGE, (void*)&info );
1581                                 tool_perror( "ldap_sasl_interactive_bind",
1582                                         err, NULL, NULL, info, NULL );
1583                                 ldap_memfree( info );
1584                                 tool_exit( ld, err );
1585                         }
1586                 } while ( rc == LDAP_SASL_BIND_IN_PROGRESS );
1587
1588                 lutil_sasl_freedefs( defaults );
1589
1590                 if ( rc != LDAP_SUCCESS ) {
1591                         ldap_get_option( ld, LDAP_OPT_DIAGNOSTIC_MESSAGE, (void*)&info );
1592                         tool_perror( "ldap_sasl_interactive_bind",
1593                                 rc, NULL, NULL, info, NULL );
1594                         ldap_memfree( info );
1595                         tool_exit( ld, rc );
1596                 }
1597 #else
1598                 fprintf( stderr, "%s: not compiled with SASL support\n", prog );
1599                 tool_exit( ld, LDAP_NOT_SUPPORTED );
1600 #endif
1601         } else {
1602                 /* simple bind */
1603                 rc = ldap_sasl_bind( ld, binddn, LDAP_SASL_SIMPLE, &passwd,
1604                         sctrlsp, NULL, &msgid );
1605                 if ( msgid == -1 ) {
1606                         tool_perror( "ldap_sasl_bind(SIMPLE)", rc,
1607                                 NULL, NULL, NULL, NULL );
1608                         tool_exit( ld, rc );
1609                 }
1610
1611                 rc = ldap_result( ld, msgid, LDAP_MSG_ALL, NULL, &result );
1612                 if ( rc == -1 ) {
1613                         tool_perror( "ldap_result", -1, NULL, NULL, NULL, NULL );
1614                         tool_exit( ld, LDAP_LOCAL_ERROR );
1615                 }
1616
1617                 if ( rc == 0 ) {
1618                         tool_perror( "ldap_result", LDAP_TIMEOUT, NULL, NULL, NULL, NULL );
1619                         tool_exit( ld, LDAP_LOCAL_ERROR );
1620                 }
1621         }
1622
1623         if ( result ) {
1624                 rc = ldap_parse_result( ld, result, &err, &matched, &info, &refs,
1625                                         &ctrls, 1 );
1626                 if ( rc != LDAP_SUCCESS ) {
1627                         tool_perror( "ldap_bind parse result", rc, NULL, matched, info, refs );
1628                         tool_exit( ld, LDAP_LOCAL_ERROR );
1629                 }
1630         }
1631
1632 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1633         if ( ctrls && ppolicy ) {
1634                 LDAPControl *ctrl;
1635                 int expire, grace, len = 0;
1636                 LDAPPasswordPolicyError pErr = -1;
1637                 
1638                 ctrl = ldap_control_find( LDAP_CONTROL_PASSWORDPOLICYRESPONSE,
1639                         ctrls, NULL );
1640
1641                 if ( ctrl && ldap_parse_passwordpolicy_control( ld, ctrl,
1642                         &expire, &grace, &pErr ) == LDAP_SUCCESS )
1643                 {
1644                         if ( pErr != PP_noError ){
1645                                 msgbuf[0] = ';';
1646                                 msgbuf[1] = ' ';
1647                                 strcpy( msgbuf+2, ldap_passwordpolicy_err2txt( pErr ));
1648                                 len = strlen( msgbuf );
1649                         }
1650                         if ( expire >= 0 ) {
1651                                 sprintf( msgbuf+len,
1652                                         " (Password expires in %d seconds)",
1653                                         expire );
1654                         } else if ( grace >= 0 ) {
1655                                 sprintf( msgbuf+len,
1656                                         " (Password expired, %d grace logins remain)",
1657                                         grace );
1658                         }
1659                 }
1660         }
1661 #endif
1662
1663         if ( ctrls && bauthzid ) {
1664                 LDAPControl *ctrl;
1665                 
1666                 ctrl = ldap_control_find( LDAP_CONTROL_AUTHZID_RESPONSE,
1667                         ctrls, NULL );
1668                 if ( ctrl ) {
1669                         LDAPControl *ctmp[2];
1670                         ctmp[0] = ctrl;
1671                         ctmp[1] = NULL;
1672                         tool_print_ctrls( ld, ctmp );
1673                 }
1674         }
1675
1676         if ( ctrls ) {
1677                 ldap_controls_free( ctrls );
1678         }
1679
1680         if ( err != LDAP_SUCCESS
1681                 || msgbuf[0]
1682                 || ( matched && matched[ 0 ] )
1683                 || ( info && info[ 0 ] )
1684                 || refs )
1685         {
1686                 tool_perror( "ldap_bind", err, msgbuf, matched, info, refs );
1687
1688                 if( matched ) ber_memfree( matched );
1689                 if( info ) ber_memfree( info );
1690                 if( refs ) ber_memvfree( (void **)refs );
1691
1692                 if ( err != LDAP_SUCCESS ) tool_exit( ld, err );
1693         }
1694 }
1695
1696 void
1697 tool_unbind( LDAP *ld )
1698 {
1699         int err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, NULL );
1700
1701         if ( err != LDAP_OPT_SUCCESS ) {
1702                 fprintf( stderr, "Could not unset controls\n");
1703         }
1704
1705         (void) ldap_unbind_ext( ld, NULL, NULL );
1706 }
1707
1708 void
1709 tool_exit( LDAP *ld, int status )
1710 {
1711         if ( ld != NULL ) {
1712                 tool_unbind( ld );
1713         }
1714         tool_destroy();
1715         exit( status );
1716 }
1717
1718
1719 /* Set server controls.  Add controls extra_c[0..count-1], if set. */
1720 void
1721 tool_server_controls( LDAP *ld, LDAPControl *extra_c, int count )
1722 {
1723         int i = 0, j, crit = 0, err;
1724         LDAPControl c[16], **ctrls;
1725
1726         if ( ! ( assertctl
1727                 || authzid
1728 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1729                 || proxydn
1730 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1731                 || manageDIT
1732                 || manageDSAit
1733                 || noop
1734 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1735                 || ppolicy
1736 #endif
1737                 || preread
1738                 || postread
1739 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1740                 || chaining
1741 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
1742 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1743                 || sessionTracking
1744 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1745                 || count
1746                 || unknown_ctrls_num ) )
1747         {
1748                 return;
1749         }
1750
1751         ctrls = (LDAPControl**) malloc(sizeof(c) + (count + unknown_ctrls_num + 1)*sizeof(LDAPControl*));
1752         if ( ctrls == NULL ) {
1753                 fprintf( stderr, "No memory\n" );
1754                 tool_exit( ld, EXIT_FAILURE );
1755         }
1756
1757         if ( assertctl ) {
1758                 if ( BER_BVISNULL( &assertionvalue ) ) {
1759                         err = ldap_create_assertion_control_value( ld,
1760                                 assertion, &assertionvalue );
1761                         if ( err ) {
1762                                 fprintf( stderr,
1763                                         "Unable to create assertion value "
1764                                         "\"%s\" (%d)\n", assertion, err );
1765                         }
1766                 }
1767
1768                 c[i].ldctl_oid = LDAP_CONTROL_ASSERT;
1769                 c[i].ldctl_value = assertionvalue;
1770                 c[i].ldctl_iscritical = assertctl > 1;
1771                 ctrls[i] = &c[i];
1772                 i++;
1773         }
1774
1775         if ( authzid ) {
1776                 c[i].ldctl_value.bv_val = authzid;
1777                 c[i].ldctl_value.bv_len = strlen( authzid );
1778                 c[i].ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
1779                 c[i].ldctl_iscritical = authzcrit;
1780                 ctrls[i] = &c[i];
1781                 i++;
1782         }
1783
1784 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1785         /* NOTE: doesn't need an extra count because it's incompatible
1786          * with authzid */
1787         if ( proxydn ) {
1788                 BerElementBuffer berbuf;
1789                 BerElement *ber = (BerElement *)&berbuf;
1790                 
1791                 ber_init2( ber, NULL, LBER_USE_DER );
1792
1793                 if ( ber_printf( ber, "s", proxydn ) == -1 ) {
1794                         tool_exit( ld, EXIT_FAILURE );
1795                 }
1796
1797                 if ( ber_flatten2( ber, &c[i].ldctl_value, 0 ) == -1 ) {
1798                         tool_exit( ld, EXIT_FAILURE );
1799                 }
1800
1801                 c[i].ldctl_oid = LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ;
1802                 c[i].ldctl_iscritical = authzcrit;
1803                 ctrls[i] = &c[i];
1804                 i++;
1805         }
1806 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1807
1808         if ( manageDIT ) {
1809                 c[i].ldctl_oid = LDAP_CONTROL_MANAGEDIT;
1810                 BER_BVZERO( &c[i].ldctl_value );
1811                 c[i].ldctl_iscritical = manageDIT > 1;
1812                 ctrls[i] = &c[i];
1813                 i++;
1814         }
1815
1816         if ( manageDSAit ) {
1817                 c[i].ldctl_oid = LDAP_CONTROL_MANAGEDSAIT;
1818                 BER_BVZERO( &c[i].ldctl_value );
1819                 c[i].ldctl_iscritical = manageDSAit > 1;
1820                 ctrls[i] = &c[i];
1821                 i++;
1822         }
1823
1824         if ( noop ) {
1825                 c[i].ldctl_oid = LDAP_CONTROL_NOOP;
1826                 BER_BVZERO( &c[i].ldctl_value );
1827                 c[i].ldctl_iscritical = noop > 1;
1828                 ctrls[i] = &c[i];
1829                 i++;
1830         }
1831
1832 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1833         if ( ppolicy ) {
1834                 c[i].ldctl_oid = LDAP_CONTROL_PASSWORDPOLICYREQUEST;
1835                 BER_BVZERO( &c[i].ldctl_value );
1836                 c[i].ldctl_iscritical = 0;
1837                 ctrls[i] = &c[i];
1838                 i++;
1839         }
1840 #endif
1841
1842         if ( preread ) {
1843                 BerElementBuffer berbuf;
1844                 BerElement *ber = (BerElement *)&berbuf;
1845                 char **attrs = NULL;
1846
1847                 if( preread_attrs ) {
1848                         attrs = ldap_str2charray( preread_attrs, "," );
1849                 }
1850
1851                 ber_init2( ber, NULL, LBER_USE_DER );
1852
1853                 if( ber_printf( ber, "{v}", attrs ) == -1 ) {
1854                         fprintf( stderr, "preread attrs encode failed.\n" );
1855                         tool_exit( ld, EXIT_FAILURE );
1856                 }
1857
1858                 err = ber_flatten2( ber, &c[i].ldctl_value, 0 );
1859                 if( err < 0 ) {
1860                         fprintf( stderr, "preread flatten failed (%d)\n", err );
1861                         tool_exit( ld, EXIT_FAILURE );
1862                 }
1863
1864                 c[i].ldctl_oid = LDAP_CONTROL_PRE_READ;
1865                 c[i].ldctl_iscritical = preread > 1;
1866                 ctrls[i] = &c[i];
1867                 i++;
1868
1869                 if( attrs ) ldap_charray_free( attrs );
1870         }
1871
1872         if ( postread ) {
1873                 BerElementBuffer berbuf;
1874                 BerElement *ber = (BerElement *)&berbuf;
1875                 char **attrs = NULL;
1876
1877                 if( postread_attrs ) {
1878                         attrs = ldap_str2charray( postread_attrs, "," );
1879                 }
1880
1881                 ber_init2( ber, NULL, LBER_USE_DER );
1882
1883                 if( ber_printf( ber, "{v}", attrs ) == -1 ) {
1884                         fprintf( stderr, "postread attrs encode failed.\n" );
1885                         tool_exit( ld, EXIT_FAILURE );
1886                 }
1887
1888                 err = ber_flatten2( ber, &c[i].ldctl_value, 0 );
1889                 if( err < 0 ) {
1890                         fprintf( stderr, "postread flatten failed (%d)\n", err );
1891                         tool_exit( ld, EXIT_FAILURE );
1892                 }
1893
1894                 c[i].ldctl_oid = LDAP_CONTROL_POST_READ;
1895                 c[i].ldctl_iscritical = postread > 1;
1896                 ctrls[i] = &c[i];
1897                 i++;
1898
1899                 if( attrs ) ldap_charray_free( attrs );
1900         }
1901
1902 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1903         if ( chaining ) {
1904                 if ( chainingResolve > -1 ) {
1905                         BerElementBuffer berbuf;
1906                         BerElement *ber = (BerElement *)&berbuf;
1907
1908                         ber_init2( ber, NULL, LBER_USE_DER );
1909
1910                         err = ber_printf( ber, "{e" /* } */, chainingResolve );
1911                         if ( err == -1 ) {
1912                                 ber_free( ber, 1 );
1913                                 fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1914                                 tool_exit( ld, EXIT_FAILURE );
1915                         }
1916
1917                         if ( chainingContinuation > -1 ) {
1918                                 err = ber_printf( ber, "e", chainingContinuation );
1919                                 if ( err == -1 ) {
1920                                         ber_free( ber, 1 );
1921                                         fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1922                                         tool_exit( ld, EXIT_FAILURE );
1923                                 }
1924                         }
1925
1926                         err = ber_printf( ber, /* { */ "N}" );
1927                         if ( err == -1 ) {
1928                                 ber_free( ber, 1 );
1929                                 fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1930                                 tool_exit( ld, EXIT_FAILURE );
1931                         }
1932
1933                         if ( ber_flatten2( ber, &c[i].ldctl_value, 0 ) == -1 ) {
1934                                 tool_exit( ld, EXIT_FAILURE );
1935                         }
1936
1937                 } else {
1938                         BER_BVZERO( &c[i].ldctl_value );
1939                 }
1940
1941                 c[i].ldctl_oid = LDAP_CONTROL_X_CHAINING_BEHAVIOR;
1942                 c[i].ldctl_iscritical = chaining > 1;
1943                 ctrls[i] = &c[i];
1944                 i++;
1945         }
1946 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
1947
1948 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1949         if ( sessionTracking ) {
1950                 if ( BER_BVISNULL( &stValue ) && st_value( ld, &stValue ) ) {
1951                         tool_exit( ld, EXIT_FAILURE );
1952                 }
1953
1954                 c[i].ldctl_oid = LDAP_CONTROL_X_SESSION_TRACKING;
1955                 c[i].ldctl_iscritical = 0;
1956                 c[i].ldctl_value = stValue;
1957
1958                 ctrls[i] = &c[i];
1959                 i++;
1960         }
1961 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1962
1963         while ( count-- ) {
1964                 ctrls[i++] = extra_c++;
1965         }
1966         for ( count = 0; count < unknown_ctrls_num; count++ ) {
1967                 ctrls[i++] = &unknown_ctrls[count];
1968         }
1969         ctrls[i] = NULL;
1970
1971         err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, ctrls );
1972
1973         if ( err != LDAP_OPT_SUCCESS ) {
1974                 for ( j = 0; j < i; j++ ) {
1975                         if ( ctrls[j]->ldctl_iscritical ) crit = 1;
1976                 }
1977                 fprintf( stderr, "Could not set %scontrols\n",
1978                         crit ? "critical " : "" );
1979         }
1980
1981         free( ctrls );
1982         if ( crit ) {
1983                 tool_exit( ld, EXIT_FAILURE );
1984         }
1985 }
1986
1987 int
1988 tool_check_abandon( LDAP *ld, int msgid )
1989 {
1990         int     rc;
1991
1992         switch ( gotintr ) {
1993         case Intr_Cancel:
1994                 rc = ldap_cancel_s( ld, msgid, NULL, NULL );
1995                 fprintf( stderr, "got interrupt, cancel got %d: %s\n",
1996                                 rc, ldap_err2string( rc ) );
1997                 return -1;
1998
1999         case Intr_Abandon:
2000                 rc = ldap_abandon_ext( ld, msgid, NULL, NULL );
2001                 fprintf( stderr, "got interrupt, abandon got %d: %s\n",
2002                                 rc, ldap_err2string( rc ) );
2003                 return -1;
2004
2005         case Intr_Ignore:
2006                 /* just unbind, ignoring the request */
2007                 return -1;
2008         }
2009
2010         return 0;
2011 }
2012
2013 static int
2014 print_prepostread( LDAP *ld, LDAPControl *ctrl, struct berval *what)
2015 {
2016         BerElement      *ber;
2017         struct berval   bv;
2018
2019         tool_write_ldif( LDIF_PUT_COMMENT, "==> ",
2020                 what->bv_val, what->bv_len );
2021         ber = ber_init( &ctrl->ldctl_value );
2022         if ( ber == NULL ) {
2023                 /* error? */
2024                 return 1;
2025
2026         } else if ( ber_scanf( ber, "{m{" /*}}*/, &bv ) == LBER_ERROR ) {
2027                 /* error? */
2028                 return 1;
2029
2030         } else {
2031                 tool_write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
2032
2033                 while ( ber_scanf( ber, "{m" /*}*/, &bv ) != LBER_ERROR ) {
2034                         int             i;
2035                         BerVarray       vals = NULL;
2036                         char            *str = NULL;
2037
2038                         if ( ber_scanf( ber, "[W]", &vals ) == LBER_ERROR ||
2039                                 vals == NULL )
2040                         {
2041                                 /* error? */
2042                                 return 1;
2043                         }
2044
2045                         if ( ldif ) {
2046                                 char *ptr;
2047
2048                                 str = malloc( bv.bv_len + STRLENOF(": ") + 1 );
2049
2050                                 ptr = str;
2051                                 ptr = lutil_strncopy( ptr, bv.bv_val, bv.bv_len );
2052                                 ptr = lutil_strcopy( ptr, ": " );
2053                         }
2054                 
2055                         for ( i = 0; vals[ i ].bv_val != NULL; i++ ) {
2056                                 tool_write_ldif(
2057                                         ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2058                                         ldif ? str : bv.bv_val, vals[ i ].bv_val, vals[ i ].bv_len );
2059                         }
2060
2061                         ber_bvarray_free( vals );
2062                         if ( str ) free( str );
2063                 }
2064         }
2065
2066         if ( ber != NULL ) {
2067                 ber_free( ber, 1 );
2068         }
2069
2070         tool_write_ldif( LDIF_PUT_COMMENT, "<== ",
2071                 what->bv_val, what->bv_len );
2072
2073         return 0;
2074 }
2075
2076 static int
2077 print_preread( LDAP *ld, LDAPControl *ctrl )
2078 {
2079         static struct berval what = BER_BVC( "preread" );
2080
2081         return print_prepostread( ld, ctrl, &what );
2082 }
2083
2084 static int
2085 print_postread( LDAP *ld, LDAPControl *ctrl )
2086 {
2087         static struct berval what = BER_BVC( "postread" );
2088
2089         return print_prepostread( ld, ctrl, &what );
2090 }
2091
2092 static int
2093 print_paged_results( LDAP *ld, LDAPControl *ctrl )
2094 {
2095         ber_int_t estimate;
2096
2097         /* note: pr_cookie is being malloced; it's freed
2098          * the next time the control is sent, but the last
2099          * time it's not; we don't care too much, because
2100          * the last time an empty value is returned... */
2101         if ( ldap_parse_pageresponse_control( ld, ctrl, &estimate, &pr_cookie )
2102                 != LDAP_SUCCESS )
2103         {
2104                 /* error? */
2105                 return 1;
2106
2107         } else {
2108                 /* FIXME: check buffer overflow */
2109                 char    buf[ BUFSIZ ], *ptr = buf;
2110
2111                 if ( estimate > 0 ) {
2112                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2113                                 "estimate=%d", estimate );
2114                 }
2115
2116                 if ( pr_cookie.bv_len > 0 ) {
2117                         struct berval   bv;
2118
2119                         bv.bv_len = LUTIL_BASE64_ENCODE_LEN(
2120                                 pr_cookie.bv_len ) + 1;
2121                         bv.bv_val = ber_memalloc( bv.bv_len + 1 );
2122
2123                         bv.bv_len = lutil_b64_ntop(
2124                                 (unsigned char *) pr_cookie.bv_val,
2125                                 pr_cookie.bv_len,
2126                                 bv.bv_val, bv.bv_len );
2127
2128                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2129                                 "%scookie=%s", ptr == buf ? "" : " ",
2130                                 bv.bv_val );
2131
2132                         ber_memfree( bv.bv_val );
2133
2134                         pr_morePagedResults = 1;
2135
2136                 } else {
2137                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2138                                 "%scookie=", ptr == buf ? "" : " " );
2139                 }
2140
2141                 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2142                         ldif ? "pagedresults: " : "pagedresults",
2143                         buf, ptr - buf );
2144         }
2145
2146         return 0;
2147 }
2148
2149 static int
2150 print_sss( LDAP *ld, LDAPControl *ctrl )
2151 {
2152         int rc;
2153         ber_int_t err;
2154         char *attr;
2155
2156         rc = ldap_parse_sortresponse_control( ld, ctrl, &err, &attr );
2157         if ( rc == LDAP_SUCCESS ) {
2158                 char buf[ BUFSIZ ];
2159                 rc = snprintf( buf, sizeof(buf), "(%d) %s%s%s",
2160                         err, ldap_err2string(err), attr ? " " : "", attr ? attr : "" );
2161
2162                 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2163                         ldif ? "sortResult: " : "sortResult", buf, rc );
2164         }
2165
2166         return rc;
2167 }
2168
2169 static int
2170 print_vlv( LDAP *ld, LDAPControl *ctrl )
2171 {
2172         int rc;
2173         ber_int_t err;
2174         struct berval bv;
2175
2176         rc = ldap_parse_vlvresponse_control( ld, ctrl, &vlvPos, &vlvCount,
2177                 &vlvContext, &err );
2178         if ( rc == LDAP_SUCCESS ) {
2179                 char buf[ BUFSIZ ];
2180
2181                 if ( vlvContext && vlvContext->bv_len > 0 ) {
2182                         bv.bv_len = LUTIL_BASE64_ENCODE_LEN(
2183                                 vlvContext->bv_len ) + 1;
2184                         bv.bv_val = ber_memalloc( bv.bv_len + 1 );
2185
2186                         bv.bv_len = lutil_b64_ntop(
2187                                 (unsigned char *) vlvContext->bv_val,
2188                                 vlvContext->bv_len,
2189                                 bv.bv_val, bv.bv_len );
2190                 } else {
2191                         bv.bv_val = "";
2192                         bv.bv_len = 0;
2193                 }
2194
2195                 rc = snprintf( buf, sizeof(buf), "pos=%d count=%d context=%s (%d) %s",
2196                         vlvPos, vlvCount, bv.bv_val,
2197                         err, ldap_err2string(err));
2198
2199                 if ( bv.bv_len )
2200                         ber_memfree( bv.bv_val );
2201
2202                 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2203                         ldif ? "vlvResult" : "vlvResult", buf, rc );
2204         }
2205
2206         return rc;
2207 }
2208
2209 #ifdef LDAP_CONTROL_X_DEREF
2210 static int
2211 print_deref( LDAP *ld, LDAPControl *ctrl )
2212 {
2213         LDAPDerefRes    *drhead = NULL, *dr;
2214         int             rc;
2215
2216         rc = ldap_parse_derefresponse_control( ld, ctrl, &drhead );
2217         if ( rc != LDAP_SUCCESS ) {
2218                 return rc;
2219         }
2220
2221         for ( dr = drhead; dr != NULL; dr = dr->next ) {
2222                 LDAPDerefVal    *dv;
2223                 ber_len_t       len;
2224                 char            *buf, *ptr;
2225
2226                 len = strlen( dr->derefAttr ) + STRLENOF(": ");
2227
2228                 for ( dv = dr->attrVals; dv != NULL; dv = dv->next ) {
2229                         if ( dv->vals != NULL ) {
2230                                 int j;
2231                                 ber_len_t tlen = strlen(dv->type);
2232
2233                                 for ( j = 0; dv->vals[ j ].bv_val != NULL; j++ ) {
2234                                         len += STRLENOF("<:=>;") + tlen + 4*((dv->vals[ j ].bv_len - 1)/3 + 1);
2235                                 }
2236                         }
2237                 }
2238                 len += dr->derefVal.bv_len + STRLENOF("\n");
2239                 buf = ldap_memalloc( len + 1 );
2240                 if ( buf == NULL ) {
2241                         rc = LDAP_NO_MEMORY;
2242                         goto done;
2243                 }
2244
2245                 ptr = buf;
2246                 ptr = lutil_strcopy( ptr, dr->derefAttr );
2247                 *ptr++ = ':';
2248                 *ptr++ = ' ';
2249                 for ( dv = dr->attrVals; dv != NULL; dv = dv->next ) {
2250                         if ( dv->vals != NULL ) {
2251                                 int j;
2252                                 for ( j = 0; dv->vals[ j ].bv_val != NULL; j++ ) {
2253                                         int k = ldif_is_not_printable( dv->vals[ j ].bv_val, dv->vals[ j ].bv_len );
2254
2255                                         *ptr++ = '<';
2256                                         ptr = lutil_strcopy( ptr, dv->type );
2257                                         if ( k ) {
2258                                                 *ptr++ = ':';
2259                                         }
2260                                         *ptr++ = '=';
2261                                         if ( k ) {
2262                                                 k = lutil_b64_ntop(
2263                                                         (unsigned char *) dv->vals[ j ].bv_val,
2264                                                         dv->vals[ j ].bv_len,
2265                                                         ptr, buf + len - ptr );
2266                                                 assert( k >= 0 );
2267                                                 ptr += k;
2268                                                 
2269                                         } else {
2270                                                 ptr = lutil_memcopy( ptr, dv->vals[ j ].bv_val, dv->vals[ j ].bv_len );
2271                                         }
2272                                         *ptr++ = '>';
2273                                         *ptr++ = ';';
2274                                 }
2275                         }
2276                 }
2277                 ptr = lutil_strncopy( ptr, dr->derefVal.bv_val, dr->derefVal.bv_len );
2278                 *ptr++ = '\n';
2279                 *ptr = '\0';
2280                 assert( ptr <= buf + len );
2281
2282                 tool_write_ldif( LDIF_PUT_COMMENT, NULL, buf, ptr - buf);
2283
2284                 ldap_memfree( buf );
2285         }
2286
2287         rc = LDAP_SUCCESS;
2288
2289 done:;
2290         ldap_derefresponse_free( drhead );
2291
2292         return rc;
2293 }
2294 #endif
2295
2296 #ifdef LDAP_CONTROL_X_WHATFAILED
2297 static int
2298 print_whatfailed( LDAP *ld, LDAPControl *ctrl )
2299 {
2300         BerElement *ber;
2301         ber_tag_t tag;
2302         ber_len_t siz;
2303         BerVarray bva = NULL;
2304
2305         /* Create a BerElement from the berval returned in the control. */
2306         ber = ber_init( &ctrl->ldctl_value );
2307
2308         if ( ber == NULL ) {
2309                 return LDAP_NO_MEMORY;
2310         }
2311
2312         siz = sizeof(struct berval);
2313         tag = ber_scanf( ber, "[M]", &bva, &siz, 0 );
2314         if ( tag != LBER_ERROR ) {
2315                 int i;
2316
2317                 tool_write_ldif( LDIF_PUT_COMMENT, " what failed:", NULL, 0 );
2318
2319                 for ( i = 0; bva[i].bv_val != NULL; i++ ) {
2320                         tool_write_ldif( LDIF_PUT_COMMENT, NULL, bva[i].bv_val, bva[i].bv_len );
2321                 }
2322
2323                 ldap_memfree( bva );
2324         }
2325
2326         ber_free( ber, 1 );
2327
2328
2329         return 0;
2330 }
2331 #endif
2332
2333 #ifdef LDAP_CONTROL_AUTHZID_RESPONSE
2334 static int
2335 print_authzid( LDAP *ld, LDAPControl *ctrl )
2336 {
2337         if ( ctrl->ldctl_value.bv_len ) {
2338                 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2339                         ldif ? "authzid: " : "authzid",
2340                 ctrl->ldctl_value.bv_val, ctrl->ldctl_value.bv_len );
2341         } else {
2342                 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2343                         ldif ? "authzid: " : "authzid",
2344                         "anonymous",  STRLENOF("anonymous") );
2345         }
2346
2347         return 0;
2348 }
2349 #endif
2350
2351 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
2352 static int
2353 print_ppolicy( LDAP *ld, LDAPControl *ctrl )
2354 {
2355         int expire = 0, grace = 0, rc;
2356         LDAPPasswordPolicyError pperr;
2357
2358         rc = ldap_parse_passwordpolicy_control( ld, ctrl,
2359                 &expire, &grace, &pperr );
2360         if ( rc == LDAP_SUCCESS ) {
2361                 char    buf[ BUFSIZ ], *ptr = buf;
2362
2363                 if ( expire != -1 ) {
2364                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2365                                 "expire=%d", expire );
2366                 }
2367
2368                 if ( grace != -1 ) {
2369                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2370                                 "%sgrace=%d", ptr == buf ? "" : " ", grace );
2371                 }
2372
2373                 if ( pperr != PP_noError ) {
2374                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2375                                 "%serror=%d (%s)", ptr == buf ? "" : " ",
2376                                 pperr,
2377                                 ldap_passwordpolicy_err2txt( pperr ) );
2378                 }
2379
2380                 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2381                         ldif ? "ppolicy: " : "ppolicy", buf, ptr - buf );
2382         }
2383
2384         return rc;
2385 }
2386 #endif
2387
2388 void tool_print_ctrls(
2389         LDAP            *ld,
2390         LDAPControl     **ctrls )
2391 {
2392         int     i;
2393         char    *ptr;
2394
2395         for ( i = 0; ctrls[i] != NULL; i++ ) {
2396                 /* control: OID criticality base64value */
2397                 struct berval b64 = BER_BVNULL;
2398                 ber_len_t len;
2399                 char *str;
2400                 int j;
2401
2402                 /* FIXME: there might be cases where a control has NULL OID;
2403                  * this makes little sense, especially when returned by the
2404                  * server, but libldap happily allows it */
2405                 if ( ctrls[i]->ldctl_oid == NULL ) {
2406                         continue;
2407                 }
2408
2409                 len = ldif ? 2 : 0;
2410                 len += strlen( ctrls[i]->ldctl_oid );
2411
2412                 /* add enough for space after OID and the critical value itself */
2413                 len += ctrls[i]->ldctl_iscritical
2414                         ? sizeof("true") : sizeof("false");
2415
2416                 /* convert to base64 */
2417                 if ( !BER_BVISNULL( &ctrls[i]->ldctl_value ) ) {
2418                         b64.bv_len = LUTIL_BASE64_ENCODE_LEN(
2419                                 ctrls[i]->ldctl_value.bv_len ) + 1;
2420                         b64.bv_val = ber_memalloc( b64.bv_len + 1 );
2421
2422                         b64.bv_len = lutil_b64_ntop(
2423                                 (unsigned char *) ctrls[i]->ldctl_value.bv_val,
2424                                 ctrls[i]->ldctl_value.bv_len,
2425                                 b64.bv_val, b64.bv_len );
2426                 }
2427
2428                 if ( b64.bv_len ) {
2429                         len += 1 + b64.bv_len;
2430                 }
2431
2432                 ptr = str = malloc( len + 1 );
2433                 if ( ldif ) {
2434                         ptr = lutil_strcopy( ptr, ": " );
2435                 }
2436                 ptr = lutil_strcopy( ptr, ctrls[i]->ldctl_oid );
2437                 ptr = lutil_strcopy( ptr, ctrls[i]->ldctl_iscritical
2438                         ? " true" : " false" );
2439
2440                 if ( b64.bv_len ) {
2441                         ptr = lutil_strcopy( ptr, " " );
2442                         ptr = lutil_strcopy( ptr, b64.bv_val );
2443                 }
2444
2445                 if ( ldif < 2 ) {
2446                         tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2447                                 "control", str, len );
2448                 }
2449
2450                 free( str );
2451                 if ( b64.bv_len ) {
2452                         ber_memfree( b64.bv_val );
2453                 }
2454
2455                 /* known controls */
2456                 for ( j = 0; tool_ctrl_response[j].oid != NULL; j++ ) {
2457                         if ( strcmp( tool_ctrl_response[j].oid, ctrls[i]->ldctl_oid ) == 0 ) {
2458                                 if ( !tool_ctrl_response[j].mask & tool_type ) {
2459                                         /* this control should not appear
2460                                          * with this tool; warning? */
2461                                 }
2462                                 break;
2463                         }
2464                 }
2465
2466                 if ( tool_ctrl_response[j].oid != NULL && tool_ctrl_response[j].func ) {
2467                         (void)tool_ctrl_response[j].func( ld, ctrls[i] );
2468                 }
2469         }
2470 }
2471
2472 int
2473 tool_write_ldif( int type, char *name, char *value, ber_len_t vallen )
2474 {
2475         char    *ldif;
2476
2477         if (( ldif = ldif_put_wrap( type, name, value, vallen, ldif_wrap )) == NULL ) {
2478                 return( -1 );
2479         }
2480
2481         fputs( ldif, stdout );
2482         ber_memfree( ldif );
2483
2484         return( 0 );
2485 }
2486
2487 int
2488 tool_is_oid( const char *s )
2489 {
2490         int             first = 1;
2491
2492         if ( !isdigit( (unsigned char) s[ 0 ] ) ) {
2493                 return 0;
2494         }
2495
2496         for ( ; s[ 0 ]; s++ ) {
2497                 if ( s[ 0 ] == '.' ) {
2498                         if ( s[ 1 ] == '\0' ) {
2499                                 return 0;
2500                         }
2501                         first = 1;
2502                         continue;
2503                 }
2504
2505                 if ( !isdigit( (unsigned char) s[ 0 ] ) ) {
2506                         return 0;
2507                 }
2508
2509                 if ( first == 1 && s[ 0 ] == '0' && s[ 1 ] != '.' ) {
2510                         return 0;
2511                 }
2512                 first = 0;
2513         }
2514
2515         return 1;
2516 }