]> git.sur5r.net Git - openldap/blob - clients/tools/common.c
Merge remote-tracking branch 'origin/mdb.master'
[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-2013 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 = LDIF_LINE_WIDTH;
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         rc = ldap_parse_result( ld, result, &err, &matched, &info, &refs,
1624                 &ctrls, 1 );
1625         if ( rc != LDAP_SUCCESS ) {
1626                 tool_perror( "ldap_bind parse result", rc, NULL, matched, info, refs );
1627                 tool_exit( ld, LDAP_LOCAL_ERROR );
1628         }
1629
1630 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1631         if ( ctrls && ppolicy ) {
1632                 LDAPControl *ctrl;
1633                 int expire, grace, len = 0;
1634                 LDAPPasswordPolicyError pErr = -1;
1635                 
1636                 ctrl = ldap_control_find( LDAP_CONTROL_PASSWORDPOLICYRESPONSE,
1637                         ctrls, NULL );
1638
1639                 if ( ctrl && ldap_parse_passwordpolicy_control( ld, ctrl,
1640                         &expire, &grace, &pErr ) == LDAP_SUCCESS )
1641                 {
1642                         if ( pErr != PP_noError ){
1643                                 msgbuf[0] = ';';
1644                                 msgbuf[1] = ' ';
1645                                 strcpy( msgbuf+2, ldap_passwordpolicy_err2txt( pErr ));
1646                                 len = strlen( msgbuf );
1647                         }
1648                         if ( expire >= 0 ) {
1649                                 sprintf( msgbuf+len,
1650                                         " (Password expires in %d seconds)",
1651                                         expire );
1652                         } else if ( grace >= 0 ) {
1653                                 sprintf( msgbuf+len,
1654                                         " (Password expired, %d grace logins remain)",
1655                                         grace );
1656                         }
1657                 }
1658         }
1659 #endif
1660
1661         if ( ctrls && bauthzid ) {
1662                 LDAPControl *ctrl;
1663                 
1664                 ctrl = ldap_control_find( LDAP_CONTROL_AUTHZID_RESPONSE,
1665                         ctrls, NULL );
1666                 if ( ctrl ) {
1667                         LDAPControl *ctmp[2];
1668                         ctmp[0] = ctrl;
1669                         ctmp[1] = NULL;
1670                         tool_print_ctrls( ld, ctmp );
1671                 }
1672         }
1673
1674         if ( ctrls ) {
1675                 ldap_controls_free( ctrls );
1676         }
1677
1678         if ( err != LDAP_SUCCESS
1679                 || msgbuf[0]
1680                 || ( matched && matched[ 0 ] )
1681                 || ( info && info[ 0 ] )
1682                 || refs )
1683         {
1684                 tool_perror( "ldap_bind", err, msgbuf, matched, info, refs );
1685
1686                 if( matched ) ber_memfree( matched );
1687                 if( info ) ber_memfree( info );
1688                 if( refs ) ber_memvfree( (void **)refs );
1689
1690                 if ( err != LDAP_SUCCESS ) tool_exit( ld, err );
1691         }
1692 }
1693
1694 void
1695 tool_unbind( LDAP *ld )
1696 {
1697         int err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, NULL );
1698
1699         if ( err != LDAP_OPT_SUCCESS ) {
1700                 fprintf( stderr, "Could not unset controls\n");
1701         }
1702
1703         (void) ldap_unbind_ext( ld, NULL, NULL );
1704 }
1705
1706 void
1707 tool_exit( LDAP *ld, int status )
1708 {
1709         if ( ld != NULL ) {
1710                 tool_unbind( ld );
1711         }
1712         tool_destroy();
1713         exit( status );
1714 }
1715
1716
1717 /* Set server controls.  Add controls extra_c[0..count-1], if set. */
1718 void
1719 tool_server_controls( LDAP *ld, LDAPControl *extra_c, int count )
1720 {
1721         int i = 0, j, crit = 0, err;
1722         LDAPControl c[16], **ctrls;
1723
1724         if ( ! ( assertctl
1725                 || authzid
1726 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1727                 || proxydn
1728 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1729                 || manageDIT
1730                 || manageDSAit
1731                 || noop
1732 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1733                 || ppolicy
1734 #endif
1735                 || preread
1736                 || postread
1737 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1738                 || chaining
1739 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
1740 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1741                 || sessionTracking
1742 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1743                 || count
1744                 || unknown_ctrls_num ) )
1745         {
1746                 return;
1747         }
1748
1749         ctrls = (LDAPControl**) malloc(sizeof(c) + (count + unknown_ctrls_num + 1)*sizeof(LDAPControl*));
1750         if ( ctrls == NULL ) {
1751                 fprintf( stderr, "No memory\n" );
1752                 tool_exit( ld, EXIT_FAILURE );
1753         }
1754
1755         if ( assertctl ) {
1756                 if ( BER_BVISNULL( &assertionvalue ) ) {
1757                         err = ldap_create_assertion_control_value( ld,
1758                                 assertion, &assertionvalue );
1759                         if ( err ) {
1760                                 fprintf( stderr,
1761                                         "Unable to create assertion value "
1762                                         "\"%s\" (%d)\n", assertion, err );
1763                         }
1764                 }
1765
1766                 c[i].ldctl_oid = LDAP_CONTROL_ASSERT;
1767                 c[i].ldctl_value = assertionvalue;
1768                 c[i].ldctl_iscritical = assertctl > 1;
1769                 ctrls[i] = &c[i];
1770                 i++;
1771         }
1772
1773         if ( authzid ) {
1774                 c[i].ldctl_value.bv_val = authzid;
1775                 c[i].ldctl_value.bv_len = strlen( authzid );
1776                 c[i].ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
1777                 c[i].ldctl_iscritical = authzcrit;
1778                 ctrls[i] = &c[i];
1779                 i++;
1780         }
1781
1782 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1783         /* NOTE: doesn't need an extra count because it's incompatible
1784          * with authzid */
1785         if ( proxydn ) {
1786                 BerElementBuffer berbuf;
1787                 BerElement *ber = (BerElement *)&berbuf;
1788                 
1789                 ber_init2( ber, NULL, LBER_USE_DER );
1790
1791                 if ( ber_printf( ber, "s", proxydn ) == -1 ) {
1792                         tool_exit( ld, EXIT_FAILURE );
1793                 }
1794
1795                 if ( ber_flatten2( ber, &c[i].ldctl_value, 0 ) == -1 ) {
1796                         tool_exit( ld, EXIT_FAILURE );
1797                 }
1798
1799                 c[i].ldctl_oid = LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ;
1800                 c[i].ldctl_iscritical = authzcrit;
1801                 ctrls[i] = &c[i];
1802                 i++;
1803         }
1804 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1805
1806         if ( manageDIT ) {
1807                 c[i].ldctl_oid = LDAP_CONTROL_MANAGEDIT;
1808                 BER_BVZERO( &c[i].ldctl_value );
1809                 c[i].ldctl_iscritical = manageDIT > 1;
1810                 ctrls[i] = &c[i];
1811                 i++;
1812         }
1813
1814         if ( manageDSAit ) {
1815                 c[i].ldctl_oid = LDAP_CONTROL_MANAGEDSAIT;
1816                 BER_BVZERO( &c[i].ldctl_value );
1817                 c[i].ldctl_iscritical = manageDSAit > 1;
1818                 ctrls[i] = &c[i];
1819                 i++;
1820         }
1821
1822         if ( noop ) {
1823                 c[i].ldctl_oid = LDAP_CONTROL_NOOP;
1824                 BER_BVZERO( &c[i].ldctl_value );
1825                 c[i].ldctl_iscritical = noop > 1;
1826                 ctrls[i] = &c[i];
1827                 i++;
1828         }
1829
1830 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1831         if ( ppolicy ) {
1832                 c[i].ldctl_oid = LDAP_CONTROL_PASSWORDPOLICYREQUEST;
1833                 BER_BVZERO( &c[i].ldctl_value );
1834                 c[i].ldctl_iscritical = 0;
1835                 ctrls[i] = &c[i];
1836                 i++;
1837         }
1838 #endif
1839
1840         if ( preread ) {
1841                 BerElementBuffer berbuf;
1842                 BerElement *ber = (BerElement *)&berbuf;
1843                 char **attrs = NULL;
1844
1845                 if( preread_attrs ) {
1846                         attrs = ldap_str2charray( preread_attrs, "," );
1847                 }
1848
1849                 ber_init2( ber, NULL, LBER_USE_DER );
1850
1851                 if( ber_printf( ber, "{v}", attrs ) == -1 ) {
1852                         fprintf( stderr, "preread attrs encode failed.\n" );
1853                         tool_exit( ld, EXIT_FAILURE );
1854                 }
1855
1856                 err = ber_flatten2( ber, &c[i].ldctl_value, 0 );
1857                 if( err < 0 ) {
1858                         fprintf( stderr, "preread flatten failed (%d)\n", err );
1859                         tool_exit( ld, EXIT_FAILURE );
1860                 }
1861
1862                 c[i].ldctl_oid = LDAP_CONTROL_PRE_READ;
1863                 c[i].ldctl_iscritical = preread > 1;
1864                 ctrls[i] = &c[i];
1865                 i++;
1866
1867                 if( attrs ) ldap_charray_free( attrs );
1868         }
1869
1870         if ( postread ) {
1871                 BerElementBuffer berbuf;
1872                 BerElement *ber = (BerElement *)&berbuf;
1873                 char **attrs = NULL;
1874
1875                 if( postread_attrs ) {
1876                         attrs = ldap_str2charray( postread_attrs, "," );
1877                 }
1878
1879                 ber_init2( ber, NULL, LBER_USE_DER );
1880
1881                 if( ber_printf( ber, "{v}", attrs ) == -1 ) {
1882                         fprintf( stderr, "postread attrs encode failed.\n" );
1883                         tool_exit( ld, EXIT_FAILURE );
1884                 }
1885
1886                 err = ber_flatten2( ber, &c[i].ldctl_value, 0 );
1887                 if( err < 0 ) {
1888                         fprintf( stderr, "postread flatten failed (%d)\n", err );
1889                         tool_exit( ld, EXIT_FAILURE );
1890                 }
1891
1892                 c[i].ldctl_oid = LDAP_CONTROL_POST_READ;
1893                 c[i].ldctl_iscritical = postread > 1;
1894                 ctrls[i] = &c[i];
1895                 i++;
1896
1897                 if( attrs ) ldap_charray_free( attrs );
1898         }
1899
1900 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1901         if ( chaining ) {
1902                 if ( chainingResolve > -1 ) {
1903                         BerElementBuffer berbuf;
1904                         BerElement *ber = (BerElement *)&berbuf;
1905
1906                         ber_init2( ber, NULL, LBER_USE_DER );
1907
1908                         err = ber_printf( ber, "{e" /* } */, chainingResolve );
1909                         if ( err == -1 ) {
1910                                 ber_free( ber, 1 );
1911                                 fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1912                                 tool_exit( ld, EXIT_FAILURE );
1913                         }
1914
1915                         if ( chainingContinuation > -1 ) {
1916                                 err = ber_printf( ber, "e", chainingContinuation );
1917                                 if ( err == -1 ) {
1918                                         ber_free( ber, 1 );
1919                                         fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1920                                         tool_exit( ld, EXIT_FAILURE );
1921                                 }
1922                         }
1923
1924                         err = ber_printf( ber, /* { */ "N}" );
1925                         if ( err == -1 ) {
1926                                 ber_free( ber, 1 );
1927                                 fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1928                                 tool_exit( ld, EXIT_FAILURE );
1929                         }
1930
1931                         if ( ber_flatten2( ber, &c[i].ldctl_value, 0 ) == -1 ) {
1932                                 tool_exit( ld, EXIT_FAILURE );
1933                         }
1934
1935                 } else {
1936                         BER_BVZERO( &c[i].ldctl_value );
1937                 }
1938
1939                 c[i].ldctl_oid = LDAP_CONTROL_X_CHAINING_BEHAVIOR;
1940                 c[i].ldctl_iscritical = chaining > 1;
1941                 ctrls[i] = &c[i];
1942                 i++;
1943         }
1944 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
1945
1946 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1947         if ( sessionTracking ) {
1948                 if ( BER_BVISNULL( &stValue ) && st_value( ld, &stValue ) ) {
1949                         tool_exit( ld, EXIT_FAILURE );
1950                 }
1951
1952                 c[i].ldctl_oid = LDAP_CONTROL_X_SESSION_TRACKING;
1953                 c[i].ldctl_iscritical = 0;
1954                 c[i].ldctl_value = stValue;
1955
1956                 ctrls[i] = &c[i];
1957                 i++;
1958         }
1959 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1960
1961         while ( count-- ) {
1962                 ctrls[i++] = extra_c++;
1963         }
1964         for ( count = 0; count < unknown_ctrls_num; count++ ) {
1965                 ctrls[i++] = &unknown_ctrls[count];
1966         }
1967         ctrls[i] = NULL;
1968
1969         err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, ctrls );
1970
1971         if ( err != LDAP_OPT_SUCCESS ) {
1972                 for ( j = 0; j < i; j++ ) {
1973                         if ( ctrls[j]->ldctl_iscritical ) crit = 1;
1974                 }
1975                 fprintf( stderr, "Could not set %scontrols\n",
1976                         crit ? "critical " : "" );
1977         }
1978
1979         free( ctrls );
1980         if ( crit ) {
1981                 tool_exit( ld, EXIT_FAILURE );
1982         }
1983 }
1984
1985 int
1986 tool_check_abandon( LDAP *ld, int msgid )
1987 {
1988         int     rc;
1989
1990         switch ( gotintr ) {
1991         case Intr_Cancel:
1992                 rc = ldap_cancel_s( ld, msgid, NULL, NULL );
1993                 fprintf( stderr, "got interrupt, cancel got %d: %s\n",
1994                                 rc, ldap_err2string( rc ) );
1995                 return -1;
1996
1997         case Intr_Abandon:
1998                 rc = ldap_abandon_ext( ld, msgid, NULL, NULL );
1999                 fprintf( stderr, "got interrupt, abandon got %d: %s\n",
2000                                 rc, ldap_err2string( rc ) );
2001                 return -1;
2002
2003         case Intr_Ignore:
2004                 /* just unbind, ignoring the request */
2005                 return -1;
2006         }
2007
2008         return 0;
2009 }
2010
2011 static int
2012 print_prepostread( LDAP *ld, LDAPControl *ctrl, struct berval *what)
2013 {
2014         BerElement      *ber;
2015         struct berval   bv;
2016
2017         tool_write_ldif( LDIF_PUT_COMMENT, "==> ",
2018                 what->bv_val, what->bv_len );
2019         ber = ber_init( &ctrl->ldctl_value );
2020         if ( ber == NULL ) {
2021                 /* error? */
2022                 return 1;
2023
2024         } else if ( ber_scanf( ber, "{m{" /*}}*/, &bv ) == LBER_ERROR ) {
2025                 /* error? */
2026                 return 1;
2027
2028         } else {
2029                 tool_write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
2030
2031                 while ( ber_scanf( ber, "{m" /*}*/, &bv ) != LBER_ERROR ) {
2032                         int             i;
2033                         BerVarray       vals = NULL;
2034                         char            *str = NULL;
2035
2036                         if ( ber_scanf( ber, "[W]", &vals ) == LBER_ERROR ||
2037                                 vals == NULL )
2038                         {
2039                                 /* error? */
2040                                 return 1;
2041                         }
2042
2043                         if ( ldif ) {
2044                                 char *ptr;
2045
2046                                 str = malloc( bv.bv_len + STRLENOF(": ") + 1 );
2047
2048                                 ptr = str;
2049                                 ptr = lutil_strncopy( ptr, bv.bv_val, bv.bv_len );
2050                                 ptr = lutil_strcopy( ptr, ": " );
2051                         }
2052                 
2053                         for ( i = 0; vals[ i ].bv_val != NULL; i++ ) {
2054                                 tool_write_ldif(
2055                                         ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2056                                         ldif ? str : bv.bv_val, vals[ i ].bv_val, vals[ i ].bv_len );
2057                         }
2058
2059                         ber_bvarray_free( vals );
2060                         if ( str ) free( str );
2061                 }
2062         }
2063
2064         if ( ber != NULL ) {
2065                 ber_free( ber, 1 );
2066         }
2067
2068         tool_write_ldif( LDIF_PUT_COMMENT, "<== ",
2069                 what->bv_val, what->bv_len );
2070
2071         return 0;
2072 }
2073
2074 static int
2075 print_preread( LDAP *ld, LDAPControl *ctrl )
2076 {
2077         static struct berval what = BER_BVC( "preread" );
2078
2079         return print_prepostread( ld, ctrl, &what );
2080 }
2081
2082 static int
2083 print_postread( LDAP *ld, LDAPControl *ctrl )
2084 {
2085         static struct berval what = BER_BVC( "postread" );
2086
2087         return print_prepostread( ld, ctrl, &what );
2088 }
2089
2090 static int
2091 print_paged_results( LDAP *ld, LDAPControl *ctrl )
2092 {
2093         ber_int_t estimate;
2094
2095         /* note: pr_cookie is being malloced; it's freed
2096          * the next time the control is sent, but the last
2097          * time it's not; we don't care too much, because
2098          * the last time an empty value is returned... */
2099         if ( ldap_parse_pageresponse_control( ld, ctrl, &estimate, &pr_cookie )
2100                 != LDAP_SUCCESS )
2101         {
2102                 /* error? */
2103                 return 1;
2104
2105         } else {
2106                 /* FIXME: check buffer overflow */
2107                 char    buf[ BUFSIZ ], *ptr = buf;
2108
2109                 if ( estimate > 0 ) {
2110                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2111                                 "estimate=%d", estimate );
2112                 }
2113
2114                 if ( pr_cookie.bv_len > 0 ) {
2115                         struct berval   bv;
2116
2117                         bv.bv_len = LUTIL_BASE64_ENCODE_LEN(
2118                                 pr_cookie.bv_len ) + 1;
2119                         bv.bv_val = ber_memalloc( bv.bv_len + 1 );
2120
2121                         bv.bv_len = lutil_b64_ntop(
2122                                 (unsigned char *) pr_cookie.bv_val,
2123                                 pr_cookie.bv_len,
2124                                 bv.bv_val, bv.bv_len );
2125
2126                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2127                                 "%scookie=%s", ptr == buf ? "" : " ",
2128                                 bv.bv_val );
2129
2130                         ber_memfree( bv.bv_val );
2131
2132                         pr_morePagedResults = 1;
2133
2134                 } else {
2135                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2136                                 "%scookie=", ptr == buf ? "" : " " );
2137                 }
2138
2139                 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2140                         ldif ? "pagedresults: " : "pagedresults",
2141                         buf, ptr - buf );
2142         }
2143
2144         return 0;
2145 }
2146
2147 static int
2148 print_sss( LDAP *ld, LDAPControl *ctrl )
2149 {
2150         int rc;
2151         ber_int_t err;
2152         char *attr;
2153
2154         rc = ldap_parse_sortresponse_control( ld, ctrl, &err, &attr );
2155         if ( rc == LDAP_SUCCESS ) {
2156                 char buf[ BUFSIZ ];
2157                 rc = snprintf( buf, sizeof(buf), "(%d) %s%s%s",
2158                         err, ldap_err2string(err), attr ? " " : "", attr ? attr : "" );
2159
2160                 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2161                         ldif ? "sortResult: " : "sortResult", buf, rc );
2162         }
2163
2164         return rc;
2165 }
2166
2167 static int
2168 print_vlv( LDAP *ld, LDAPControl *ctrl )
2169 {
2170         int rc;
2171         ber_int_t err;
2172         struct berval bv;
2173
2174         rc = ldap_parse_vlvresponse_control( ld, ctrl, &vlvPos, &vlvCount,
2175                 &vlvContext, &err );
2176         if ( rc == LDAP_SUCCESS ) {
2177                 char buf[ BUFSIZ ];
2178
2179                 if ( vlvContext && vlvContext->bv_len > 0 ) {
2180                         bv.bv_len = LUTIL_BASE64_ENCODE_LEN(
2181                                 vlvContext->bv_len ) + 1;
2182                         bv.bv_val = ber_memalloc( bv.bv_len + 1 );
2183
2184                         bv.bv_len = lutil_b64_ntop(
2185                                 (unsigned char *) vlvContext->bv_val,
2186                                 vlvContext->bv_len,
2187                                 bv.bv_val, bv.bv_len );
2188                 } else {
2189                         bv.bv_val = "";
2190                         bv.bv_len = 0;
2191                 }
2192
2193                 rc = snprintf( buf, sizeof(buf), "pos=%d count=%d context=%s (%d) %s",
2194                         vlvPos, vlvCount, bv.bv_val,
2195                         err, ldap_err2string(err));
2196
2197                 if ( bv.bv_len )
2198                         ber_memfree( bv.bv_val );
2199
2200                 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2201                         ldif ? "vlvResult" : "vlvResult", buf, rc );
2202         }
2203
2204         return rc;
2205 }
2206
2207 #ifdef LDAP_CONTROL_X_DEREF
2208 static int
2209 print_deref( LDAP *ld, LDAPControl *ctrl )
2210 {
2211         LDAPDerefRes    *drhead = NULL, *dr;
2212         int             rc;
2213
2214         rc = ldap_parse_derefresponse_control( ld, ctrl, &drhead );
2215         if ( rc != LDAP_SUCCESS ) {
2216                 return rc;
2217         }
2218
2219         for ( dr = drhead; dr != NULL; dr = dr->next ) {
2220                 LDAPDerefVal    *dv;
2221                 ber_len_t       len;
2222                 char            *buf, *ptr;
2223
2224                 len = strlen( dr->derefAttr ) + STRLENOF(": ");
2225
2226                 for ( dv = dr->attrVals; dv != NULL; dv = dv->next ) {
2227                         if ( dv->vals != NULL ) {
2228                                 int j;
2229                                 ber_len_t tlen = strlen(dv->type);
2230
2231                                 for ( j = 0; dv->vals[ j ].bv_val != NULL; j++ ) {
2232                                         len += STRLENOF("<:=>;") + tlen + 4*((dv->vals[ j ].bv_len - 1)/3 + 1);
2233                                 }
2234                         }
2235                 }
2236                 len += dr->derefVal.bv_len + STRLENOF("\n");
2237                 buf = ldap_memalloc( len + 1 );
2238                 if ( buf == NULL ) {
2239                         rc = LDAP_NO_MEMORY;
2240                         goto done;
2241                 }
2242
2243                 ptr = buf;
2244                 ptr = lutil_strcopy( ptr, dr->derefAttr );
2245                 *ptr++ = ':';
2246                 *ptr++ = ' ';
2247                 for ( dv = dr->attrVals; dv != NULL; dv = dv->next ) {
2248                         if ( dv->vals != NULL ) {
2249                                 int j;
2250                                 for ( j = 0; dv->vals[ j ].bv_val != NULL; j++ ) {
2251                                         int k = ldif_is_not_printable( dv->vals[ j ].bv_val, dv->vals[ j ].bv_len );
2252
2253                                         *ptr++ = '<';
2254                                         ptr = lutil_strcopy( ptr, dv->type );
2255                                         if ( k ) {
2256                                                 *ptr++ = ':';
2257                                         }
2258                                         *ptr++ = '=';
2259                                         if ( k ) {
2260                                                 k = lutil_b64_ntop(
2261                                                         (unsigned char *) dv->vals[ j ].bv_val,
2262                                                         dv->vals[ j ].bv_len,
2263                                                         ptr, buf + len - ptr );
2264                                                 assert( k >= 0 );
2265                                                 ptr += k;
2266                                                 
2267                                         } else {
2268                                                 ptr = lutil_memcopy( ptr, dv->vals[ j ].bv_val, dv->vals[ j ].bv_len );
2269                                         }
2270                                         *ptr++ = '>';
2271                                         *ptr++ = ';';
2272                                 }
2273                         }
2274                 }
2275                 ptr = lutil_strncopy( ptr, dr->derefVal.bv_val, dr->derefVal.bv_len );
2276                 *ptr++ = '\n';
2277                 *ptr = '\0';
2278                 assert( ptr <= buf + len );
2279
2280                 tool_write_ldif( LDIF_PUT_COMMENT, NULL, buf, ptr - buf);
2281
2282                 ldap_memfree( buf );
2283         }
2284
2285         rc = LDAP_SUCCESS;
2286
2287 done:;
2288         ldap_derefresponse_free( drhead );
2289
2290         return rc;
2291 }
2292 #endif
2293
2294 #ifdef LDAP_CONTROL_X_WHATFAILED
2295 static int
2296 print_whatfailed( LDAP *ld, LDAPControl *ctrl )
2297 {
2298         BerElement *ber;
2299         ber_tag_t tag;
2300         ber_len_t siz;
2301         BerVarray bva = NULL;
2302
2303         /* Create a BerElement from the berval returned in the control. */
2304         ber = ber_init( &ctrl->ldctl_value );
2305
2306         if ( ber == NULL ) {
2307                 return LDAP_NO_MEMORY;
2308         }
2309
2310         siz = sizeof(struct berval);
2311         tag = ber_scanf( ber, "[M]", &bva, &siz, 0 );
2312         if ( tag != LBER_ERROR ) {
2313                 int i;
2314
2315                 tool_write_ldif( LDIF_PUT_COMMENT, " what failed:", NULL, 0 );
2316
2317                 for ( i = 0; bva[i].bv_val != NULL; i++ ) {
2318                         tool_write_ldif( LDIF_PUT_COMMENT, NULL, bva[i].bv_val, bva[i].bv_len );
2319                 }
2320
2321                 ldap_memfree( bva );
2322         }
2323
2324         ber_free( ber, 1 );
2325
2326
2327         return 0;
2328 }
2329 #endif
2330
2331 #ifdef LDAP_CONTROL_AUTHZID_RESPONSE
2332 static int
2333 print_authzid( LDAP *ld, LDAPControl *ctrl )
2334 {
2335         if ( ctrl->ldctl_value.bv_len ) {
2336                 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2337                         ldif ? "authzid: " : "authzid",
2338                 ctrl->ldctl_value.bv_val, ctrl->ldctl_value.bv_len );
2339         } else {
2340                 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2341                         ldif ? "authzid: " : "authzid",
2342                         "anonymous",  STRLENOF("anonymous") );
2343         }
2344
2345         return 0;
2346 }
2347 #endif
2348
2349 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
2350 static int
2351 print_ppolicy( LDAP *ld, LDAPControl *ctrl )
2352 {
2353         int expire = 0, grace = 0, rc;
2354         LDAPPasswordPolicyError pperr;
2355
2356         rc = ldap_parse_passwordpolicy_control( ld, ctrl,
2357                 &expire, &grace, &pperr );
2358         if ( rc == LDAP_SUCCESS ) {
2359                 char    buf[ BUFSIZ ], *ptr = buf;
2360
2361                 if ( expire != -1 ) {
2362                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2363                                 "expire=%d", expire );
2364                 }
2365
2366                 if ( grace != -1 ) {
2367                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2368                                 "%sgrace=%d", ptr == buf ? "" : " ", grace );
2369                 }
2370
2371                 if ( pperr != PP_noError ) {
2372                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2373                                 "%serror=%d (%s)", ptr == buf ? "" : " ",
2374                                 pperr,
2375                                 ldap_passwordpolicy_err2txt( pperr ) );
2376                 }
2377
2378                 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2379                         ldif ? "ppolicy: " : "ppolicy", buf, ptr - buf );
2380         }
2381
2382         return rc;
2383 }
2384 #endif
2385
2386 void tool_print_ctrls(
2387         LDAP            *ld,
2388         LDAPControl     **ctrls )
2389 {
2390         int     i;
2391         char    *ptr;
2392
2393         for ( i = 0; ctrls[i] != NULL; i++ ) {
2394                 /* control: OID criticality base64value */
2395                 struct berval b64 = BER_BVNULL;
2396                 ber_len_t len;
2397                 char *str;
2398                 int j;
2399
2400                 /* FIXME: there might be cases where a control has NULL OID;
2401                  * this makes little sense, especially when returned by the
2402                  * server, but libldap happily allows it */
2403                 if ( ctrls[i]->ldctl_oid == NULL ) {
2404                         continue;
2405                 }
2406
2407                 len = ldif ? 2 : 0;
2408                 len += strlen( ctrls[i]->ldctl_oid );
2409
2410                 /* add enough for space after OID and the critical value itself */
2411                 len += ctrls[i]->ldctl_iscritical
2412                         ? sizeof("true") : sizeof("false");
2413
2414                 /* convert to base64 */
2415                 if ( !BER_BVISNULL( &ctrls[i]->ldctl_value ) ) {
2416                         b64.bv_len = LUTIL_BASE64_ENCODE_LEN(
2417                                 ctrls[i]->ldctl_value.bv_len ) + 1;
2418                         b64.bv_val = ber_memalloc( b64.bv_len + 1 );
2419
2420                         b64.bv_len = lutil_b64_ntop(
2421                                 (unsigned char *) ctrls[i]->ldctl_value.bv_val,
2422                                 ctrls[i]->ldctl_value.bv_len,
2423                                 b64.bv_val, b64.bv_len );
2424                 }
2425
2426                 if ( b64.bv_len ) {
2427                         len += 1 + b64.bv_len;
2428                 }
2429
2430                 ptr = str = malloc( len + 1 );
2431                 if ( ldif ) {
2432                         ptr = lutil_strcopy( ptr, ": " );
2433                 }
2434                 ptr = lutil_strcopy( ptr, ctrls[i]->ldctl_oid );
2435                 ptr = lutil_strcopy( ptr, ctrls[i]->ldctl_iscritical
2436                         ? " true" : " false" );
2437
2438                 if ( b64.bv_len ) {
2439                         ptr = lutil_strcopy( ptr, " " );
2440                         ptr = lutil_strcopy( ptr, b64.bv_val );
2441                 }
2442
2443                 if ( ldif < 2 ) {
2444                         tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2445                                 "control", str, len );
2446                 }
2447
2448                 free( str );
2449                 if ( b64.bv_len ) {
2450                         ber_memfree( b64.bv_val );
2451                 }
2452
2453                 /* known controls */
2454                 for ( j = 0; tool_ctrl_response[j].oid != NULL; j++ ) {
2455                         if ( strcmp( tool_ctrl_response[j].oid, ctrls[i]->ldctl_oid ) == 0 ) {
2456                                 if ( !tool_ctrl_response[j].mask & tool_type ) {
2457                                         /* this control should not appear
2458                                          * with this tool; warning? */
2459                                 }
2460                                 break;
2461                         }
2462                 }
2463
2464                 if ( tool_ctrl_response[j].oid != NULL && tool_ctrl_response[j].func ) {
2465                         (void)tool_ctrl_response[j].func( ld, ctrls[i] );
2466                 }
2467         }
2468 }
2469
2470 int
2471 tool_write_ldif( int type, char *name, char *value, ber_len_t vallen )
2472 {
2473         char    *ldif;
2474
2475         if (( ldif = ldif_put_wrap( type, name, value, vallen, ldif_wrap )) == NULL ) {
2476                 return( -1 );
2477         }
2478
2479         fputs( ldif, stdout );
2480         ber_memfree( ldif );
2481
2482         return( 0 );
2483 }
2484
2485 int
2486 tool_is_oid( const char *s )
2487 {
2488         int             first = 1;
2489
2490         if ( !isdigit( (unsigned char) s[ 0 ] ) ) {
2491                 return 0;
2492         }
2493
2494         for ( ; s[ 0 ]; s++ ) {
2495                 if ( s[ 0 ] == '.' ) {
2496                         if ( s[ 1 ] == '\0' ) {
2497                                 return 0;
2498                         }
2499                         first = 1;
2500                         continue;
2501                 }
2502
2503                 if ( !isdigit( (unsigned char) s[ 0 ] ) ) {
2504                         return 0;
2505                 }
2506
2507                 if ( first == 1 && s[ 0 ] == '0' && s[ 1 ] != '.' ) {
2508                         return 0;
2509                 }
2510                 first = 0;
2511         }
2512
2513         return 1;
2514 }