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