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