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