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