]> git.sur5r.net Git - openldap/blob - clients/tools/common.c
More for ITS#6645
[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                         break;
676                 case 'f':       /* read from file */
677                         if( infile != NULL ) {
678                                 fprintf( stderr, "%s: -f previously specified\n", prog );
679                                 exit( EXIT_FAILURE );
680                         }
681                         infile = ber_strdup( optarg );
682                         break;
683                 case 'h':       /* ldap host */
684                         if( ldaphost != NULL ) {
685                                 fprintf( stderr, "%s: -h previously specified\n", prog );
686                                 exit( EXIT_FAILURE );
687                         }
688                         ldaphost = ber_strdup( optarg );
689                         break;
690                 case 'H':       /* ldap URI */
691                         if( ldapuri != NULL ) {
692                                 fprintf( stderr, "%s: -H previously specified\n", prog );
693                                 exit( EXIT_FAILURE );
694                         }
695                         ldapuri = ber_strdup( optarg );
696                         break;
697                 case 'I':
698 #ifdef HAVE_CYRUS_SASL
699                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
700                                 fprintf( stderr, "%s: incompatible previous "
701                                         "authentication choice\n",
702                                         prog );
703                                 exit( EXIT_FAILURE );
704                         }
705                         authmethod = LDAP_AUTH_SASL;
706                         sasl_flags = LDAP_SASL_INTERACTIVE;
707                         break;
708 #else
709                         fprintf( stderr, "%s: was not compiled with SASL support\n",
710                                 prog );
711                         exit( EXIT_FAILURE );
712 #endif
713                 case 'M':
714                         /* enable Manage DSA IT */
715                         manageDSAit++;
716                         break;
717                 case 'n':       /* print operations, don't actually do them */
718                         dont++;
719                         break;
720                 case 'N':
721                         nocanon++;
722                         break;
723                 case 'o':
724                         control = ber_strdup( optarg );
725                         if ( (cvalue = strchr( control, '=' )) != NULL ) {
726                                 *cvalue++ = '\0';
727                         }
728
729                         if ( strcasecmp( control, "nettimeout" ) == 0 ) {
730                                 if( nettimeout.tv_sec != -1 ) {
731                                         fprintf( stderr, "nettimeout option previously specified\n");
732                                         exit( EXIT_FAILURE );
733                                 }
734                                 if( cvalue == NULL || cvalue[0] == '\0' ) {
735                                         fprintf( stderr, "nettimeout: option value expected\n" );
736                                         usage();
737                                 }
738                                 if ( strcasecmp( cvalue, "none" ) == 0 ) {
739                                         nettimeout.tv_sec = 0;
740                                 } else if ( strcasecmp( cvalue, "max" ) == 0 ) {
741                                         nettimeout.tv_sec = LDAP_MAXINT;
742                                 } else {
743                                         ival = strtol( cvalue, &next, 10 );
744                                         if ( next == NULL || next[0] != '\0' ) {
745                                                 fprintf( stderr,
746                                                         _("Unable to parse network timeout \"%s\"\n"), cvalue );
747                                                 exit( EXIT_FAILURE );
748                                         }
749                                         nettimeout.tv_sec = ival;
750                                 }
751                                 if( nettimeout.tv_sec < 0 || nettimeout.tv_sec > LDAP_MAXINT ) {
752                                         fprintf( stderr, _("%s: invalid network timeout (%ld) specified\n"),
753                                                 prog, (long)nettimeout.tv_sec );
754                                         exit( EXIT_FAILURE );
755                                 }
756
757                         } else if ( strcasecmp( control, "ldif-wrap" ) == 0 ) {
758                                 if ( cvalue == 0 ) {
759                                         ldif_wrap = LDIF_LINE_WIDTH;
760
761                                 } else if ( strcasecmp( cvalue, "no" ) == 0 ) {
762                                         ldif_wrap = LDIF_LINE_WIDTH_MAX;
763
764                                 } else {
765                                         unsigned int u;
766                                         if ( lutil_atou( &u, cvalue ) ) {
767                                                 fprintf( stderr,
768                                                         _("Unable to parse ldif-wrap=\"%s\"\n"), cvalue );
769                                                 exit( EXIT_FAILURE );
770                                         }
771                                         ldif_wrap = (ber_len_t)u;
772                                 }
773
774                         } else {
775                                 fprintf( stderr, "Invalid general option name: %s\n",
776                                         control );
777                                 usage();
778                         }
779                         ber_memfree(control);
780                         break;
781                 case 'O':
782 #ifdef HAVE_CYRUS_SASL
783                         if( sasl_secprops != NULL ) {
784                                 fprintf( stderr, "%s: -O previously specified\n", prog );
785                                 exit( EXIT_FAILURE );
786                         }
787                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
788                                 fprintf( stderr, "%s: incompatible previous "
789                                         "authentication choice\n", prog );
790                                 exit( EXIT_FAILURE );
791                         }
792                         authmethod = LDAP_AUTH_SASL;
793                         sasl_secprops = ber_strdup( optarg );
794 #else
795                         fprintf( stderr, "%s: not compiled with SASL support\n", prog );
796                         exit( EXIT_FAILURE );
797 #endif
798                         break;
799                 case 'p':
800                         if( ldapport ) {
801                                 fprintf( stderr, "%s: -p previously specified\n", prog );
802                                 exit( EXIT_FAILURE );
803                         }
804                         ival = strtol( optarg, &next, 10 );
805                         if ( next == NULL || next[0] != '\0' ) {
806                                 fprintf( stderr, "%s: unable to parse port number \"%s\"\n", prog, optarg );
807                                 exit( EXIT_FAILURE );
808                         }
809                         ldapport = ival;
810                         break;
811                 case 'P':
812                         ival = strtol( optarg, &next, 10 );
813                         if ( next == NULL || next[0] != '\0' ) {
814                                 fprintf( stderr, "%s: unable to parse protocol version \"%s\"\n", prog, optarg );
815                                 exit( EXIT_FAILURE );
816                         }
817                         switch( ival ) {
818                         case 2:
819                                 if( protocol == LDAP_VERSION3 ) {
820                                         fprintf( stderr, "%s: -P 2 incompatible with version %d\n",
821                                                 prog, protocol );
822                                         exit( EXIT_FAILURE );
823                                 }
824                                 protocol = LDAP_VERSION2;
825                                 break;
826                         case 3:
827                                 if( protocol == LDAP_VERSION2 ) {
828                                         fprintf( stderr, "%s: -P 2 incompatible with version %d\n",
829                                                 prog, protocol );
830                                         exit( EXIT_FAILURE );
831                                 }
832                                 protocol = LDAP_VERSION3;
833                                 break;
834                         default:
835                                 fprintf( stderr, "%s: protocol version should be 2 or 3\n",
836                                         prog );
837                                 usage();
838                         }
839                         break;
840                 case 'Q':
841 #ifdef HAVE_CYRUS_SASL
842                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
843                                 fprintf( stderr, "%s: incompatible previous "
844                                         "authentication choice\n",
845                                         prog );
846                                 exit( EXIT_FAILURE );
847                         }
848                         authmethod = LDAP_AUTH_SASL;
849                         sasl_flags = LDAP_SASL_QUIET;
850                         break;
851 #else
852                         fprintf( stderr, "%s: not compiled with SASL support\n",
853                                 prog );
854                         exit( EXIT_FAILURE );
855 #endif
856                 case 'R':
857 #ifdef HAVE_CYRUS_SASL
858                         if( sasl_realm != NULL ) {
859                                 fprintf( stderr, "%s: -R previously specified\n", prog );
860                                 exit( EXIT_FAILURE );
861                         }
862                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
863                                 fprintf( stderr, "%s: incompatible previous "
864                                         "authentication choice\n",
865                                         prog );
866                                 exit( EXIT_FAILURE );
867                         }
868                         authmethod = LDAP_AUTH_SASL;
869                         sasl_realm = ber_strdup( optarg );
870 #else
871                         fprintf( stderr, "%s: not compiled with SASL support\n",
872                                 prog );
873                         exit( EXIT_FAILURE );
874 #endif
875                         break;
876                 case 'U':
877 #ifdef HAVE_CYRUS_SASL
878                         if( sasl_authc_id != NULL ) {
879                                 fprintf( stderr, "%s: -U previously specified\n", prog );
880                                 exit( EXIT_FAILURE );
881                         }
882                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
883                                 fprintf( stderr, "%s: incompatible previous "
884                                         "authentication choice\n",
885                                         prog );
886                                 exit( EXIT_FAILURE );
887                         }
888                         authmethod = LDAP_AUTH_SASL;
889                         sasl_authc_id = ber_strdup( optarg );
890 #else
891                         fprintf( stderr, "%s: not compiled with SASL support\n",
892                                 prog );
893                         exit( EXIT_FAILURE );
894 #endif
895                         break;
896                 case 'v':       /* verbose mode */
897                         verbose++;
898                         break;
899                 case 'V':       /* version */
900                         version++;
901                         break;
902                 case 'w':       /* password */
903                         passwd.bv_val = ber_strdup( optarg );
904                         {
905                                 char* p;
906
907                                 for( p = optarg; *p != '\0'; p++ ) {
908                                         *p = '\0';
909                                 }
910                         }
911                         passwd.bv_len = strlen( passwd.bv_val );
912                         break;
913                 case 'W':
914                         want_bindpw++;
915                         break;
916                 case 'y':
917                         pw_file = optarg;
918                         break;
919                 case 'Y':
920 #ifdef HAVE_CYRUS_SASL
921                         if( sasl_mech != NULL ) {
922                                 fprintf( stderr, "%s: -Y previously specified\n", prog );
923                                 exit( EXIT_FAILURE );
924                         }
925                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
926                                 fprintf( stderr,
927                                         "%s: incompatible with authentication choice\n", prog );
928                                 exit( EXIT_FAILURE );
929                         }
930                         authmethod = LDAP_AUTH_SASL;
931                         sasl_mech = ber_strdup( optarg );
932 #else
933                         fprintf( stderr, "%s: not compiled with SASL support\n", prog );
934                         exit( EXIT_FAILURE );
935 #endif
936                         break;
937                 case 'x':
938                         if( authmethod != -1 && authmethod != LDAP_AUTH_SIMPLE ) {
939                                 fprintf( stderr, "%s: incompatible with previous "
940                                         "authentication choice\n", prog );
941                                 exit( EXIT_FAILURE );
942                         }
943                         authmethod = LDAP_AUTH_SIMPLE;
944                         break;
945                 case 'X':
946 #ifdef HAVE_CYRUS_SASL
947                         if( sasl_authz_id != NULL ) {
948                                 fprintf( stderr, "%s: -X previously specified\n", prog );
949                                 exit( EXIT_FAILURE );
950                         }
951                         if( authmethod != -1 && authmethod != LDAP_AUTH_SASL ) {
952                                 fprintf( stderr, "%s: -X incompatible with "
953                                         "authentication choice\n", prog );
954                                 exit( EXIT_FAILURE );
955                         }
956                         authmethod = LDAP_AUTH_SASL;
957                         sasl_authz_id = ber_strdup( optarg );
958 #else
959                         fprintf( stderr, "%s: not compiled with SASL support\n", prog );
960                         exit( EXIT_FAILURE );
961 #endif
962                         break;
963                 case 'Z':
964 #ifdef HAVE_TLS
965                         use_tls++;
966 #else
967                         fprintf( stderr, "%s: not compiled with TLS support\n", prog );
968                         exit( EXIT_FAILURE );
969 #endif
970                         break;
971                 default:
972                         if( handle_private_option( i ) ) break;
973                         fprintf( stderr, "%s: unrecognized option -%c\n",
974                                 prog, optopt );
975                         usage();
976                 }
977         }
978
979         {
980                 /* prevent bad linking */
981                 LDAPAPIInfo api;
982                 api.ldapai_info_version = LDAP_API_INFO_VERSION;
983
984                 if ( ldap_get_option(NULL, LDAP_OPT_API_INFO, &api)
985                         != LDAP_OPT_SUCCESS )
986                 {
987                         fprintf( stderr, "%s: ldap_get_option(API_INFO) failed\n", prog );
988                         exit( EXIT_FAILURE );
989                 }
990
991                 if (api.ldapai_info_version != LDAP_API_INFO_VERSION) {
992                         fprintf( stderr, "LDAP APIInfo version mismatch: "
993                                 "library %d, header %d\n",
994                                 api.ldapai_info_version, LDAP_API_INFO_VERSION );
995                         exit( EXIT_FAILURE );
996                 }
997
998                 if( api.ldapai_api_version != LDAP_API_VERSION ) {
999                         fprintf( stderr, "LDAP API version mismatch: "
1000                                 "library %d, header %d\n",
1001                                 api.ldapai_api_version, LDAP_API_VERSION );
1002                         exit( EXIT_FAILURE );
1003                 }
1004
1005                 if( strcmp(api.ldapai_vendor_name, LDAP_VENDOR_NAME ) != 0 ) {
1006                         fprintf( stderr, "LDAP vendor name mismatch: "
1007                                 "library %s, header %s\n",
1008                                 api.ldapai_vendor_name, LDAP_VENDOR_NAME );
1009                         exit( EXIT_FAILURE );
1010                 }
1011
1012                 if( api.ldapai_vendor_version != LDAP_VENDOR_VERSION ) {
1013                         fprintf( stderr, "LDAP vendor version mismatch: "
1014                                 "library %d, header %d\n",
1015                                 api.ldapai_vendor_version, LDAP_VENDOR_VERSION );
1016                         exit( EXIT_FAILURE );
1017                 }
1018
1019                 if (version) {
1020                         fprintf( stderr, "%s: %s\t(LDAP library: %s %d)\n",
1021                                 prog, __Version,
1022                                 LDAP_VENDOR_NAME, LDAP_VENDOR_VERSION );
1023                         if (version > 1) exit( EXIT_SUCCESS );
1024                 }
1025
1026                 ldap_memfree( api.ldapai_vendor_name );
1027                 ber_memvfree( (void **)api.ldapai_extensions );
1028         }
1029
1030         if (protocol == -1)
1031                 protocol = LDAP_VERSION3;
1032
1033         if (authmethod == -1 && protocol > LDAP_VERSION2) {
1034 #ifdef HAVE_CYRUS_SASL
1035                 if ( binddn != NULL ) {
1036                         authmethod = LDAP_AUTH_SIMPLE;
1037                 } else {
1038                         authmethod = LDAP_AUTH_SASL;
1039                 }
1040 #else
1041                 authmethod = LDAP_AUTH_SIMPLE;
1042 #endif
1043         }
1044
1045         if( ldapuri == NULL ) {
1046                 if( ldapport && ( ldaphost == NULL )) {
1047                         fprintf( stderr, "%s: -p without -h is invalid.\n", prog );
1048                         exit( EXIT_FAILURE );
1049                 }
1050         } else {
1051                 if( ldaphost != NULL ) {
1052                         fprintf( stderr, "%s: -H incompatible with -h\n", prog );
1053                         exit( EXIT_FAILURE );
1054                 }
1055                 if( ldapport ) {
1056                         fprintf( stderr, "%s: -H incompatible with -p\n", prog );
1057                         exit( EXIT_FAILURE );
1058                 }
1059         }
1060
1061         if( protocol == LDAP_VERSION2 ) {
1062                 if( assertctl || authzid || manageDIT || manageDSAit ||
1063 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1064                         proxydn ||
1065 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1066 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1067                         chaining ||
1068 #endif
1069 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1070                         sessionTracking ||
1071 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1072                         noop || ppolicy || preread || postread )
1073                 {
1074                         fprintf( stderr, "%s: -e/-M incompatible with LDAPv2\n", prog );
1075                         exit( EXIT_FAILURE );
1076                 }
1077 #ifdef HAVE_TLS
1078                 if( use_tls ) {
1079                         fprintf( stderr, "%s: -Z incompatible with LDAPv2\n", prog );
1080                         exit( EXIT_FAILURE );
1081                 }
1082 #endif
1083 #ifdef HAVE_CYRUS_SASL
1084                 if( authmethod == LDAP_AUTH_SASL ) {
1085                         fprintf( stderr, "%s: -[IOQRUXY] incompatible with LDAPv2\n",
1086                                 prog );
1087                         exit( EXIT_FAILURE );
1088                 }
1089 #endif
1090         }
1091 }
1092
1093
1094 LDAP *
1095 tool_conn_setup( int dont, void (*private_setup)( LDAP * ) )
1096 {
1097         LDAP *ld = NULL;
1098
1099         if ( debug ) {
1100                 if( ber_set_option( NULL, LBER_OPT_DEBUG_LEVEL, &debug )
1101                         != LBER_OPT_SUCCESS )
1102                 {
1103                         fprintf( stderr,
1104                                 "Could not set LBER_OPT_DEBUG_LEVEL %d\n", debug );
1105                 }
1106                 if( ldap_set_option( NULL, LDAP_OPT_DEBUG_LEVEL, &debug )
1107                         != LDAP_OPT_SUCCESS )
1108                 {
1109                         fprintf( stderr,
1110                                 "Could not set LDAP_OPT_DEBUG_LEVEL %d\n", debug );
1111                 }
1112         }
1113
1114 #ifdef SIGPIPE
1115         (void) SIGNAL( SIGPIPE, SIG_IGN );
1116 #endif
1117
1118         if ( abcan ) {
1119                 SIGNAL( SIGINT, do_sig );
1120         }
1121
1122         if ( !dont ) {
1123                 int rc;
1124
1125                 if( ( ldaphost != NULL || ldapport ) && ( ldapuri == NULL ) ) {
1126                         /* construct URL */
1127                         LDAPURLDesc url;
1128                         memset( &url, 0, sizeof(url));
1129
1130                         url.lud_scheme = "ldap";
1131                         url.lud_host = ldaphost;
1132                         url.lud_port = ldapport;
1133                         url.lud_scope = LDAP_SCOPE_DEFAULT;
1134
1135                         ldapuri = ldap_url_desc2str( &url );
1136
1137                 } else if ( ldapuri != NULL ) {
1138                         LDAPURLDesc     *ludlist, **ludp;
1139                         char            **urls = NULL;
1140                         int             nurls = 0;
1141
1142                         rc = ldap_url_parselist( &ludlist, ldapuri );
1143                         if ( rc != LDAP_URL_SUCCESS ) {
1144                                 fprintf( stderr,
1145                                         "Could not parse LDAP URI(s)=%s (%d)\n",
1146                                         ldapuri, rc );
1147                                 exit( EXIT_FAILURE );
1148                         }
1149
1150                         for ( ludp = &ludlist; *ludp != NULL; ) {
1151                                 LDAPURLDesc     *lud = *ludp;
1152                                 char            **tmp;
1153
1154                                 if ( lud->lud_dn != NULL && lud->lud_dn[ 0 ] != '\0' &&
1155                                         ( lud->lud_host == NULL || lud->lud_host[0] == '\0' ) )
1156                                 {
1157                                         /* if no host but a DN is provided,
1158                                          * use DNS SRV to gather the host list
1159                                          * and turn it into a list of URIs
1160                                          * using the scheme provided */
1161                                         char    *domain = NULL,
1162                                                 *hostlist = NULL,
1163                                                 **hosts = NULL;
1164                                         int     i,
1165                                                 len_proto = strlen( lud->lud_scheme );
1166
1167                                         if ( ldap_dn2domain( lud->lud_dn, &domain )
1168                                                 || domain == NULL )
1169                                         {
1170                                                 fprintf( stderr,
1171                                                         "DNS SRV: Could not turn "
1172                                                         "DN=\"%s\" into a domain\n",
1173                                                         lud->lud_dn );
1174                                                 goto dnssrv_free;
1175                                         }
1176                                         
1177                                         rc = ldap_domain2hostlist( domain, &hostlist );
1178                                         if ( rc ) {
1179                                                 fprintf( stderr,
1180                                                         "DNS SRV: Could not turn "
1181                                                         "domain=%s into a hostlist\n",
1182                                                         domain );
1183                                                 goto dnssrv_free;
1184                                         }
1185
1186                                         hosts = ldap_str2charray( hostlist, " " );
1187                                         if ( hosts == NULL ) {
1188                                                 fprintf( stderr,
1189                                                         "DNS SRV: Could not parse "
1190                                                         "hostlist=\"%s\"\n",
1191                                                         hostlist );
1192                                                 goto dnssrv_free;
1193                                         }
1194
1195                                         for ( i = 0; hosts[ i ] != NULL; i++ )
1196                                                 /* count'em */ ;
1197
1198                                         tmp = (char **)ber_memrealloc( urls, sizeof( char * ) * ( nurls + i + 1 ) );
1199                                         if ( tmp == NULL ) {
1200                                                 fprintf( stderr,
1201                                                         "DNS SRV: out of memory?\n" );
1202                                                 goto dnssrv_free;
1203                                         }
1204                                         urls = tmp;
1205                                         urls[ nurls ] = NULL;
1206
1207                                         for ( i = 0; hosts[ i ] != NULL; i++ ) {
1208                                                 size_t  len = len_proto
1209                                                         + STRLENOF( "://" )
1210                                                         + strlen( hosts[ i ] )
1211                                                         + 1;
1212
1213                                                 urls[ nurls + i + 1 ] = NULL;
1214                                                 urls[ nurls + i ] = (char *)malloc( sizeof( char ) * len );
1215                                                 if ( urls[ nurls + i ] == NULL ) {
1216                                                         fprintf( stderr,
1217                                                                 "DNS SRV: out of memory?\n" );
1218                                                         goto dnssrv_free;
1219                                                 }
1220
1221                                                 snprintf( urls[ nurls + i ], len, "%s://%s",
1222                                                         lud->lud_scheme, hosts[ i ] );
1223                                         }
1224                                         nurls += i;
1225
1226 dnssrv_free:;
1227                                         ber_memvfree( (void **)hosts );
1228                                         ber_memfree( hostlist );
1229                                         ber_memfree( domain );
1230
1231                                 } else {
1232                                         tmp = (char **)ber_memrealloc( urls, sizeof( char * ) * ( nurls + 2 ) );
1233                                         if ( tmp == NULL ) {
1234                                                 fprintf( stderr,
1235                                                         "DNS SRV: out of memory?\n" );
1236                                                 break;
1237                                         }
1238                                         urls = tmp;
1239                                         urls[ nurls + 1 ] = NULL;
1240
1241                                         urls[ nurls ] = ldap_url_desc2str( lud );
1242                                         if ( urls[ nurls ] == NULL ) {
1243                                                 fprintf( stderr,
1244                                                         "DNS SRV: out of memory?\n" );
1245                                                 break;
1246                                         }
1247                                         nurls++;
1248                                 }
1249
1250                                 *ludp = lud->lud_next;
1251
1252                                 lud->lud_next = NULL;
1253                                 ldap_free_urldesc( lud );
1254                         }
1255
1256                         if ( ludlist != NULL ) {
1257                                 ldap_free_urllist( ludlist );
1258                                 exit( EXIT_FAILURE );
1259
1260                         } else if ( urls == NULL ) {
1261                                 exit( EXIT_FAILURE );
1262                         }
1263
1264                         ldap_memfree( ldapuri );
1265                         ldapuri = ldap_charray2str( urls, " " );
1266                         ber_memvfree( (void **)urls );
1267                 }
1268
1269                 if ( verbose ) {
1270                         fprintf( stderr, "ldap_initialize( %s )\n",
1271                                 ldapuri != NULL ? ldapuri : "<DEFAULT>" );
1272                 }
1273                 rc = ldap_initialize( &ld, ldapuri );
1274                 if( rc != LDAP_SUCCESS ) {
1275                         fprintf( stderr,
1276                                 "Could not create LDAP session handle for URI=%s (%d): %s\n",
1277                                 ldapuri, rc, ldap_err2string(rc) );
1278                         exit( EXIT_FAILURE );
1279                 }
1280
1281                 if( private_setup ) private_setup( ld );
1282
1283                 /* referrals */
1284                 if( ldap_set_option( ld, LDAP_OPT_REFERRALS,
1285                         referrals ? LDAP_OPT_ON : LDAP_OPT_OFF ) != LDAP_OPT_SUCCESS )
1286                 {
1287                         fprintf( stderr, "Could not set LDAP_OPT_REFERRALS %s\n",
1288                                 referrals ? "on" : "off" );
1289                         exit( EXIT_FAILURE );
1290                 }
1291
1292 #ifdef HAVE_CYRUS_SASL
1293                 /* canon */
1294                 if( ldap_set_option( ld, LDAP_OPT_X_SASL_NOCANON,
1295                         nocanon ? LDAP_OPT_ON : LDAP_OPT_OFF ) != LDAP_OPT_SUCCESS )
1296                 {
1297                         fprintf( stderr, "Could not set LDAP_OPT_X_SASL_NOCANON %s\n",
1298                                 nocanon ? "on" : "off" );
1299                         exit( EXIT_FAILURE );
1300                 }
1301 #endif
1302                 if( ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &protocol )
1303                         != LDAP_OPT_SUCCESS )
1304                 {
1305                         fprintf( stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n",
1306                                 protocol );
1307                         exit( EXIT_FAILURE );
1308                 }
1309
1310                 if ( use_tls ) {
1311                         rc = ldap_start_tls_s( ld, NULL, NULL );
1312                         if ( rc != LDAP_SUCCESS ) {
1313                                 char *msg=NULL;
1314                                 ldap_get_option( ld, LDAP_OPT_DIAGNOSTIC_MESSAGE, (void*)&msg);
1315                                 tool_perror( "ldap_start_tls", rc, NULL, NULL, msg, NULL );
1316                                 ldap_memfree(msg);
1317                                 if ( use_tls > 1 ) {
1318                                         exit( EXIT_FAILURE );
1319                                 }
1320                         }
1321                 }
1322
1323                 if ( nettimeout.tv_sec > 0 ) {
1324                         if ( ldap_set_option( ld, LDAP_OPT_NETWORK_TIMEOUT, (void *) &nettimeout )
1325                                 != LDAP_OPT_SUCCESS )
1326                         {
1327                                 fprintf( stderr, "Could not set LDAP_OPT_NETWORK_TIMEOUT %ld\n",
1328                                         (long)nettimeout.tv_sec );
1329                                 exit( EXIT_FAILURE );
1330                         }
1331                 }
1332         }
1333
1334         return ld;
1335 }
1336
1337
1338 void
1339 tool_bind( LDAP *ld )
1340 {
1341         LDAPControl     **sctrlsp = NULL;
1342         LDAPControl     *sctrls[3];
1343         LDAPControl     sctrl[3];
1344         int             nsctrls = 0;
1345
1346 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1347         if ( ppolicy ) {
1348                 LDAPControl c;
1349                 c.ldctl_oid = LDAP_CONTROL_PASSWORDPOLICYREQUEST;
1350                 c.ldctl_value.bv_val = NULL;
1351                 c.ldctl_value.bv_len = 0;
1352                 c.ldctl_iscritical = 0;
1353                 sctrl[nsctrls] = c;
1354                 sctrls[nsctrls] = &sctrl[nsctrls];
1355                 sctrls[++nsctrls] = NULL;
1356         }
1357 #endif
1358
1359 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1360         if ( sessionTracking ) {
1361                 LDAPControl c;
1362
1363                 if (stValue.bv_val == NULL && st_value( ld, &stValue ) ) {
1364                         exit( EXIT_FAILURE );
1365                 }
1366
1367                 c.ldctl_oid = LDAP_CONTROL_X_SESSION_TRACKING;
1368                 c.ldctl_iscritical = 0;
1369                 ber_dupbv( &c.ldctl_value, &stValue );
1370
1371                 sctrl[nsctrls] = c;
1372                 sctrls[nsctrls] = &sctrl[nsctrls];
1373                 sctrls[++nsctrls] = NULL;
1374         }
1375 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1376
1377         if ( nsctrls ) {
1378                 sctrlsp = sctrls;
1379         }
1380
1381         assert( nsctrls < (int) (sizeof(sctrls)/sizeof(sctrls[0])) );
1382
1383         if ( pw_file || want_bindpw ) {
1384                 assert( passwd.bv_val == NULL && passwd.bv_len == 0 );
1385
1386                 if ( pw_file ) {
1387                         if ( lutil_get_filed_password( pw_file, &passwd ) ) {
1388                                 exit( EXIT_FAILURE );
1389                         }
1390
1391                 } else {
1392                         char *pw = getpassphrase( _("Enter LDAP Password: ") );
1393                         if ( pw ) {
1394                                 passwd.bv_val = ber_strdup( pw );
1395                                 passwd.bv_len = strlen( passwd.bv_val );
1396                         }
1397                 }
1398         }
1399
1400         if ( authmethod == LDAP_AUTH_SASL ) {
1401 #ifdef HAVE_CYRUS_SASL
1402                 void *defaults;
1403                 int rc;
1404
1405                 if( sasl_secprops != NULL ) {
1406                         rc = ldap_set_option( ld, LDAP_OPT_X_SASL_SECPROPS,
1407                                 (void *) sasl_secprops );
1408
1409                         if( rc != LDAP_OPT_SUCCESS ) {
1410                                 fprintf( stderr,
1411                                         "Could not set LDAP_OPT_X_SASL_SECPROPS: %s\n",
1412                                         sasl_secprops );
1413                                 exit( LDAP_LOCAL_ERROR );
1414                         }
1415                 }
1416
1417                 defaults = lutil_sasl_defaults( ld,
1418                         sasl_mech,
1419                         sasl_realm,
1420                         sasl_authc_id,
1421                         passwd.bv_val,
1422                         sasl_authz_id );
1423
1424                 rc = ldap_sasl_interactive_bind_s( ld, binddn, sasl_mech,
1425                         sctrlsp,
1426                         NULL, sasl_flags, lutil_sasl_interact, defaults );
1427
1428                 lutil_sasl_freedefs( defaults );
1429                 if( rc != LDAP_SUCCESS ) {
1430                         char *msg=NULL;
1431                         ldap_get_option( ld, LDAP_OPT_DIAGNOSTIC_MESSAGE, (void*)&msg);
1432                         tool_perror( "ldap_sasl_interactive_bind_s",
1433                                 rc, NULL, NULL, msg, NULL );
1434                         ldap_memfree(msg);
1435                         exit( rc );
1436                 }
1437 #else
1438                 fprintf( stderr, "%s: not compiled with SASL support\n", prog );
1439                 exit( LDAP_NOT_SUPPORTED );
1440 #endif
1441         } else {
1442                 int msgid, err, rc;
1443                 LDAPMessage *result;
1444                 LDAPControl **ctrls;
1445                 char msgbuf[256];
1446                 char *matched = NULL;
1447                 char *info = NULL;
1448                 char **refs = NULL;
1449
1450                 msgbuf[0] = 0;
1451
1452                 {
1453                         /* simple bind */
1454                         rc = ldap_sasl_bind( ld, binddn, LDAP_SASL_SIMPLE, &passwd,
1455                                 sctrlsp, NULL, &msgid );
1456                         if ( msgid == -1 ) {
1457                                 tool_perror( "ldap_sasl_bind(SIMPLE)", rc,
1458                                         NULL, NULL, NULL, NULL );
1459                                 exit( rc );
1460                         }
1461                 }
1462
1463                 rc = ldap_result( ld, msgid, LDAP_MSG_ALL, NULL, &result );
1464                 if ( rc == -1 ) {
1465                         tool_perror( "ldap_result", -1, NULL, NULL, NULL, NULL );
1466                         exit( LDAP_LOCAL_ERROR );
1467                 }
1468
1469                 if ( rc == 0 ) {
1470                         tool_perror( "ldap_result", LDAP_TIMEOUT, NULL, NULL, NULL, NULL );
1471                         exit( LDAP_LOCAL_ERROR );
1472                 }
1473
1474                 rc = ldap_parse_result( ld, result, &err, &matched, &info, &refs,
1475                         &ctrls, 1 );
1476                 if ( rc != LDAP_SUCCESS ) {
1477                         tool_perror( "ldap_bind parse result", rc, NULL, matched, info, refs );
1478                         exit( LDAP_LOCAL_ERROR );
1479                 }
1480
1481 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1482                 if ( ctrls && ppolicy ) {
1483                         LDAPControl *ctrl;
1484                         int expire, grace, len = 0;
1485                         LDAPPasswordPolicyError pErr = -1;
1486                         
1487                         ctrl = ldap_control_find( LDAP_CONTROL_PASSWORDPOLICYRESPONSE,
1488                                 ctrls, NULL );
1489
1490                         if ( ctrl && ldap_parse_passwordpolicy_control( ld, ctrl,
1491                                 &expire, &grace, &pErr ) == LDAP_SUCCESS )
1492                         {
1493                                 if ( pErr != PP_noError ){
1494                                         msgbuf[0] = ';';
1495                                         msgbuf[1] = ' ';
1496                                         strcpy( msgbuf+2, ldap_passwordpolicy_err2txt( pErr ));
1497                                         len = strlen( msgbuf );
1498                                 }
1499                                 if ( expire >= 0 ) {
1500                                         sprintf( msgbuf+len,
1501                                                 " (Password expires in %d seconds)",
1502                                                 expire );
1503                                 } else if ( grace >= 0 ) {
1504                                         sprintf( msgbuf+len,
1505                                                 " (Password expired, %d grace logins remain)",
1506                                                 grace );
1507                                 }
1508                         }
1509                 }
1510 #endif
1511
1512                 if ( ctrls ) {
1513                         ldap_controls_free( ctrls );
1514                 }
1515
1516                 if ( err != LDAP_SUCCESS
1517                         || msgbuf[0]
1518                         || ( matched && matched[ 0 ] )
1519                         || ( info && info[ 0 ] )
1520                         || refs )
1521                 {
1522                         tool_perror( "ldap_bind", err, msgbuf, matched, info, refs );
1523
1524                         if( matched ) ber_memfree( matched );
1525                         if( info ) ber_memfree( info );
1526                         if( refs ) ber_memvfree( (void **)refs );
1527
1528                         if ( err != LDAP_SUCCESS ) exit( err );
1529                 }
1530         }
1531 }
1532
1533 void
1534 tool_unbind( LDAP *ld )
1535 {
1536         int err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, NULL );
1537
1538         if ( err != LDAP_OPT_SUCCESS ) {
1539                 fprintf( stderr, "Could not unset controls\n");
1540         }
1541
1542         (void) ldap_unbind_ext( ld, NULL, NULL );
1543 }
1544
1545
1546 /* Set server controls.  Add controls extra_c[0..count-1], if set. */
1547 void
1548 tool_server_controls( LDAP *ld, LDAPControl *extra_c, int count )
1549 {
1550         int i = 0, j, crit = 0, err;
1551         LDAPControl c[16], **ctrls;
1552
1553         if ( ! ( assertctl
1554                 || authzid
1555 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1556                 || proxydn
1557 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1558                 || manageDIT
1559                 || manageDSAit
1560                 || noop
1561 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1562                 || ppolicy
1563 #endif
1564                 || preread
1565                 || postread
1566 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1567                 || chaining
1568 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
1569 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1570                 || sessionTracking
1571 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1572                 || count
1573                 || unknown_ctrls_num ) )
1574         {
1575                 return;
1576         }
1577
1578         ctrls = (LDAPControl**) malloc(sizeof(c) + (count + unknown_ctrls_num + 1)*sizeof(LDAPControl*));
1579         if ( ctrls == NULL ) {
1580                 fprintf( stderr, "No memory\n" );
1581                 exit( EXIT_FAILURE );
1582         }
1583
1584         if ( assertctl ) {
1585                 if ( BER_BVISNULL( &assertionvalue ) ) {
1586                         err = ldap_create_assertion_control_value( ld,
1587                                 assertion, &assertionvalue );
1588                         if ( err ) {
1589                                 fprintf( stderr,
1590                                         "Unable to create assertion value "
1591                                         "\"%s\" (%d)\n", assertion, err );
1592                         }
1593                 }
1594
1595                 c[i].ldctl_oid = LDAP_CONTROL_ASSERT;
1596                 c[i].ldctl_value = assertionvalue;
1597                 c[i].ldctl_iscritical = assertctl > 1;
1598                 ctrls[i] = &c[i];
1599                 i++;
1600         }
1601
1602         if ( authzid ) {
1603                 c[i].ldctl_value.bv_val = authzid;
1604                 c[i].ldctl_value.bv_len = strlen( authzid );
1605                 c[i].ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
1606                 c[i].ldctl_iscritical = 1;
1607                 ctrls[i] = &c[i];
1608                 i++;
1609         }
1610
1611 #ifdef LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ
1612         /* NOTE: doesn't need an extra count because it's incompatible
1613          * with authzid */
1614         if ( proxydn ) {
1615                 BerElementBuffer berbuf;
1616                 BerElement *ber = (BerElement *)&berbuf;
1617                 
1618                 ber_init2( ber, NULL, LBER_USE_DER );
1619
1620                 if ( ber_printf( ber, "s", proxydn ) == -1 ) {
1621                         exit( EXIT_FAILURE );
1622                 }
1623
1624                 if ( ber_flatten2( ber, &c[i].ldctl_value, 0 ) == -1 ) {
1625                         exit( EXIT_FAILURE );
1626                 }
1627
1628                 c[i].ldctl_oid = LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ;
1629                 c[i].ldctl_iscritical = 1;
1630                 ctrls[i] = &c[i];
1631                 i++;
1632         }
1633 #endif /* LDAP_CONTROL_OBSOLETE_PROXY_AUTHZ */
1634
1635         if ( manageDIT ) {
1636                 c[i].ldctl_oid = LDAP_CONTROL_MANAGEDIT;
1637                 BER_BVZERO( &c[i].ldctl_value );
1638                 c[i].ldctl_iscritical = manageDIT > 1;
1639                 ctrls[i] = &c[i];
1640                 i++;
1641         }
1642
1643         if ( manageDSAit ) {
1644                 c[i].ldctl_oid = LDAP_CONTROL_MANAGEDSAIT;
1645                 BER_BVZERO( &c[i].ldctl_value );
1646                 c[i].ldctl_iscritical = manageDSAit > 1;
1647                 ctrls[i] = &c[i];
1648                 i++;
1649         }
1650
1651         if ( noop ) {
1652                 c[i].ldctl_oid = LDAP_CONTROL_NOOP;
1653                 BER_BVZERO( &c[i].ldctl_value );
1654                 c[i].ldctl_iscritical = noop > 1;
1655                 ctrls[i] = &c[i];
1656                 i++;
1657         }
1658
1659 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
1660         if ( ppolicy ) {
1661                 c[i].ldctl_oid = LDAP_CONTROL_PASSWORDPOLICYREQUEST;
1662                 BER_BVZERO( &c[i].ldctl_value );
1663                 c[i].ldctl_iscritical = 0;
1664                 ctrls[i] = &c[i];
1665                 i++;
1666         }
1667 #endif
1668
1669         if ( preread ) {
1670                 BerElementBuffer berbuf;
1671                 BerElement *ber = (BerElement *)&berbuf;
1672                 char **attrs = NULL;
1673
1674                 if( preread_attrs ) {
1675                         attrs = ldap_str2charray( preread_attrs, "," );
1676                 }
1677
1678                 ber_init2( ber, NULL, LBER_USE_DER );
1679
1680                 if( ber_printf( ber, "{v}", attrs ) == -1 ) {
1681                         fprintf( stderr, "preread attrs encode failed.\n" );
1682                         exit( EXIT_FAILURE );
1683                 }
1684
1685                 err = ber_flatten2( ber, &c[i].ldctl_value, 0 );
1686                 if( err < 0 ) {
1687                         fprintf( stderr, "preread flatten failed (%d)\n", err );
1688                         exit( EXIT_FAILURE );
1689                 }
1690
1691                 c[i].ldctl_oid = LDAP_CONTROL_PRE_READ;
1692                 c[i].ldctl_iscritical = preread > 1;
1693                 ctrls[i] = &c[i];
1694                 i++;
1695
1696                 if( attrs ) ldap_charray_free( attrs );
1697         }
1698
1699         if ( postread ) {
1700                 BerElementBuffer berbuf;
1701                 BerElement *ber = (BerElement *)&berbuf;
1702                 char **attrs = NULL;
1703
1704                 if( postread_attrs ) {
1705                         attrs = ldap_str2charray( postread_attrs, "," );
1706                 }
1707
1708                 ber_init2( ber, NULL, LBER_USE_DER );
1709
1710                 if( ber_printf( ber, "{v}", attrs ) == -1 ) {
1711                         fprintf( stderr, "postread attrs encode failed.\n" );
1712                         exit( EXIT_FAILURE );
1713                 }
1714
1715                 err = ber_flatten2( ber, &c[i].ldctl_value, 0 );
1716                 if( err < 0 ) {
1717                         fprintf( stderr, "postread flatten failed (%d)\n", err );
1718                         exit( EXIT_FAILURE );
1719                 }
1720
1721                 c[i].ldctl_oid = LDAP_CONTROL_POST_READ;
1722                 c[i].ldctl_iscritical = postread > 1;
1723                 ctrls[i] = &c[i];
1724                 i++;
1725
1726                 if( attrs ) ldap_charray_free( attrs );
1727         }
1728
1729 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
1730         if ( chaining ) {
1731                 if ( chainingResolve > -1 ) {
1732                         BerElementBuffer berbuf;
1733                         BerElement *ber = (BerElement *)&berbuf;
1734
1735                         ber_init2( ber, NULL, LBER_USE_DER );
1736
1737                         err = ber_printf( ber, "{e" /* } */, chainingResolve );
1738                         if ( err == -1 ) {
1739                                 ber_free( ber, 1 );
1740                                 fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1741                                 exit( EXIT_FAILURE );
1742                         }
1743
1744                         if ( chainingContinuation > -1 ) {
1745                                 err = ber_printf( ber, "e", chainingContinuation );
1746                                 if ( err == -1 ) {
1747                                         ber_free( ber, 1 );
1748                                         fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1749                                         exit( EXIT_FAILURE );
1750                                 }
1751                         }
1752
1753                         err = ber_printf( ber, /* { */ "N}" );
1754                         if ( err == -1 ) {
1755                                 ber_free( ber, 1 );
1756                                 fprintf( stderr, _("Chaining behavior control encoding error!\n") );
1757                                 exit( EXIT_FAILURE );
1758                         }
1759
1760                         if ( ber_flatten2( ber, &c[i].ldctl_value, 0 ) == -1 ) {
1761                                 exit( EXIT_FAILURE );
1762                         }
1763
1764                 } else {
1765                         BER_BVZERO( &c[i].ldctl_value );
1766                 }
1767
1768                 c[i].ldctl_oid = LDAP_CONTROL_X_CHAINING_BEHAVIOR;
1769                 c[i].ldctl_iscritical = chaining > 1;
1770                 ctrls[i] = &c[i];
1771                 i++;
1772         }
1773 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
1774
1775 #ifdef LDAP_CONTROL_X_SESSION_TRACKING
1776         if ( sessionTracking ) {
1777                 if ( stValue.bv_val == NULL && st_value( ld, &stValue ) ) {
1778                         exit( EXIT_FAILURE );
1779                 }
1780
1781                 c[i].ldctl_oid = LDAP_CONTROL_X_SESSION_TRACKING;
1782                 c[i].ldctl_iscritical = 0;
1783                 ber_dupbv( &c[i].ldctl_value, &stValue );
1784
1785                 ctrls[i] = &c[i];
1786                 i++;
1787         }
1788 #endif /* LDAP_CONTROL_X_SESSION_TRACKING */
1789
1790         while ( count-- ) {
1791                 ctrls[i++] = extra_c++;
1792         }
1793         for ( count = 0; count < unknown_ctrls_num; count++ ) {
1794                 ctrls[i++] = &unknown_ctrls[count];
1795         }
1796         ctrls[i] = NULL;
1797
1798         err = ldap_set_option( ld, LDAP_OPT_SERVER_CONTROLS, ctrls );
1799
1800         if ( err != LDAP_OPT_SUCCESS ) {
1801                 for ( j = 0; j < i; j++ ) {
1802                         if ( ctrls[j]->ldctl_iscritical ) crit = 1;
1803                 }
1804                 fprintf( stderr, "Could not set %scontrols\n",
1805                         crit ? "critical " : "" );
1806         }
1807
1808         free( ctrls );
1809         if ( crit ) {
1810                 exit( EXIT_FAILURE );
1811         }
1812 }
1813
1814 int
1815 tool_check_abandon( LDAP *ld, int msgid )
1816 {
1817         int     rc;
1818
1819         switch ( gotintr ) {
1820         case Intr_Cancel:
1821                 rc = ldap_cancel_s( ld, msgid, NULL, NULL );
1822                 fprintf( stderr, "got interrupt, cancel got %d: %s\n",
1823                                 rc, ldap_err2string( rc ) );
1824                 return -1;
1825
1826         case Intr_Abandon:
1827                 rc = ldap_abandon_ext( ld, msgid, NULL, NULL );
1828                 fprintf( stderr, "got interrupt, abandon got %d: %s\n",
1829                                 rc, ldap_err2string( rc ) );
1830                 return -1;
1831
1832         case Intr_Ignore:
1833                 /* just unbind, ignoring the request */
1834                 return -1;
1835         }
1836
1837         return 0;
1838 }
1839
1840 static int
1841 print_prepostread( LDAP *ld, LDAPControl *ctrl, struct berval *what)
1842 {
1843         BerElement      *ber;
1844         struct berval   bv;
1845
1846         tool_write_ldif( LDIF_PUT_COMMENT, "==> ",
1847                 what->bv_val, what->bv_len );
1848         ber = ber_init( &ctrl->ldctl_value );
1849         if ( ber == NULL ) {
1850                 /* error? */
1851                 return 1;
1852
1853         } else if ( ber_scanf( ber, "{m{" /*}}*/, &bv ) == LBER_ERROR ) {
1854                 /* error? */
1855                 return 1;
1856
1857         } else {
1858                 tool_write_ldif( LDIF_PUT_VALUE, "dn", bv.bv_val, bv.bv_len );
1859
1860                 while ( ber_scanf( ber, "{m" /*}*/, &bv ) != LBER_ERROR ) {
1861                         int             i;
1862                         BerVarray       vals = NULL;
1863
1864                         if ( ber_scanf( ber, "[W]", &vals ) == LBER_ERROR ||
1865                                 vals == NULL )
1866                         {
1867                                 /* error? */
1868                                 return 1;
1869                         }
1870                 
1871                         for ( i = 0; vals[ i ].bv_val != NULL; i++ ) {
1872                                 tool_write_ldif(
1873                                         ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1874                                         bv.bv_val, vals[ i ].bv_val, vals[ i ].bv_len );
1875                         }
1876
1877                         ber_bvarray_free( vals );
1878                 }
1879         }
1880
1881         if ( ber != NULL ) {
1882                 ber_free( ber, 1 );
1883         }
1884
1885         tool_write_ldif( LDIF_PUT_COMMENT, "<== ",
1886                 what->bv_val, what->bv_len );
1887
1888         return 0;
1889 }
1890
1891 static int
1892 print_preread( LDAP *ld, LDAPControl *ctrl )
1893 {
1894         static struct berval what = BER_BVC( "preread" );
1895
1896         return print_prepostread( ld, ctrl, &what );
1897 }
1898
1899 static int
1900 print_postread( LDAP *ld, LDAPControl *ctrl )
1901 {
1902         static struct berval what = BER_BVC( "postread" );
1903
1904         return print_prepostread( ld, ctrl, &what );
1905 }
1906
1907 static int
1908 print_paged_results( LDAP *ld, LDAPControl *ctrl )
1909 {
1910         ber_int_t estimate;
1911
1912         /* note: pr_cookie is being malloced; it's freed
1913          * the next time the control is sent, but the last
1914          * time it's not; we don't care too much, because
1915          * the last time an empty value is returned... */
1916         if ( ldap_parse_pageresponse_control( ld, ctrl, &estimate, &pr_cookie )
1917                 != LDAP_SUCCESS )
1918         {
1919                 /* error? */
1920                 return 1;
1921
1922         } else {
1923                 /* FIXME: check buffer overflow */
1924                 char    buf[ BUFSIZ ], *ptr = buf;
1925
1926                 if ( estimate > 0 ) {
1927                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
1928                                 "estimate=%d", estimate );
1929                 }
1930
1931                 if ( pr_cookie.bv_len > 0 ) {
1932                         struct berval   bv;
1933
1934                         bv.bv_len = LUTIL_BASE64_ENCODE_LEN(
1935                                 pr_cookie.bv_len ) + 1;
1936                         bv.bv_val = ber_memalloc( bv.bv_len + 1 );
1937
1938                         bv.bv_len = lutil_b64_ntop(
1939                                 (unsigned char *) pr_cookie.bv_val,
1940                                 pr_cookie.bv_len,
1941                                 bv.bv_val, bv.bv_len );
1942
1943                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
1944                                 "%scookie=%s", ptr == buf ? "" : " ",
1945                                 bv.bv_val );
1946
1947                         ber_memfree( bv.bv_val );
1948
1949                         pr_morePagedResults = 1;
1950
1951                 } else {
1952                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
1953                                 "%scookie=", ptr == buf ? "" : " " );
1954                 }
1955
1956                 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1957                         "pagedresults", buf, ptr - buf );
1958         }
1959
1960         return 0;
1961 }
1962
1963 static int
1964 print_sss( LDAP *ld, LDAPControl *ctrl )
1965 {
1966         int rc;
1967         ber_int_t err;
1968         char *attr;
1969
1970         rc = ldap_parse_sortresponse_control( ld, ctrl, &err, &attr );
1971         if ( rc == LDAP_SUCCESS ) {
1972                 char buf[ BUFSIZ ];
1973                 rc = snprintf( buf, sizeof(buf), "(%d) %s%s%s",
1974                         err, ldap_err2string(err), attr ? " " : "", attr ? attr : "" );
1975
1976                 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
1977                         "sortResult", buf, rc );
1978         }
1979
1980         return rc;
1981 }
1982
1983 static int
1984 print_vlv( LDAP *ld, LDAPControl *ctrl )
1985 {
1986         int rc;
1987         ber_int_t err;
1988         struct berval bv;
1989
1990         rc = ldap_parse_vlvresponse_control( ld, ctrl, &vlvPos, &vlvCount,
1991                 &vlvContext, &err );
1992         if ( rc == LDAP_SUCCESS ) {
1993                 char buf[ BUFSIZ ];
1994
1995                 if ( vlvContext && vlvContext->bv_len > 0 ) {
1996                         bv.bv_len = LUTIL_BASE64_ENCODE_LEN(
1997                                 vlvContext->bv_len ) + 1;
1998                         bv.bv_val = ber_memalloc( bv.bv_len + 1 );
1999
2000                         bv.bv_len = lutil_b64_ntop(
2001                                 (unsigned char *) vlvContext->bv_val,
2002                                 vlvContext->bv_len,
2003                                 bv.bv_val, bv.bv_len );
2004                 } else {
2005                         bv.bv_val = "";
2006                         bv.bv_len = 0;
2007                 }
2008
2009                 rc = snprintf( buf, sizeof(buf), "pos=%d count=%d context=%s (%d) %s",
2010                         vlvPos, vlvCount, bv.bv_val,
2011                         err, ldap_err2string(err));
2012
2013                 if ( bv.bv_len )
2014                         ber_memfree( bv.bv_val );
2015
2016                 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2017                         "vlvResult", buf, rc );
2018         }
2019
2020         return rc;
2021 }
2022
2023 #ifdef LDAP_CONTROL_X_DEREF
2024 static int
2025 print_deref( LDAP *ld, LDAPControl *ctrl )
2026 {
2027         LDAPDerefRes    *drhead = NULL, *dr;
2028         int             rc;
2029
2030         rc = ldap_parse_derefresponse_control( ld, ctrl, &drhead );
2031         if ( rc != LDAP_SUCCESS ) {
2032                 return rc;
2033         }
2034
2035         for ( dr = drhead; dr != NULL; dr = dr->next ) {
2036                 LDAPDerefVal    *dv;
2037                 ber_len_t       len;
2038                 char            *buf, *ptr;
2039
2040                 len = strlen( dr->derefAttr ) + STRLENOF(": ");
2041
2042                 for ( dv = dr->attrVals; dv != NULL; dv = dv->next ) {
2043                         if ( dv->vals != NULL ) {
2044                                 int j;
2045                                 ber_len_t tlen = strlen(dv->type);
2046
2047                                 for ( j = 0; dv->vals[ j ].bv_val != NULL; j++ ) {
2048                                         len += STRLENOF("<:=>;") + tlen + 4*((dv->vals[ j ].bv_len - 1)/3 + 1);
2049                                 }
2050                         }
2051                 }
2052                 len += dr->derefVal.bv_len + STRLENOF("\n");
2053                 buf = ldap_memalloc( len + 1 );
2054                 if ( buf == NULL ) {
2055                         rc = LDAP_NO_MEMORY;
2056                         goto done;
2057                 }
2058
2059                 ptr = buf;
2060                 ptr = lutil_strcopy( ptr, dr->derefAttr );
2061                 *ptr++ = ':';
2062                 *ptr++ = ' ';
2063                 for ( dv = dr->attrVals; dv != NULL; dv = dv->next ) {
2064                         if ( dv->vals != NULL ) {
2065                                 int j;
2066                                 for ( j = 0; dv->vals[ j ].bv_val != NULL; j++ ) {
2067                                         int k = ldif_is_not_printable( dv->vals[ j ].bv_val, dv->vals[ j ].bv_len );
2068
2069                                         *ptr++ = '<';
2070                                         ptr = lutil_strcopy( ptr, dv->type );
2071                                         if ( k ) {
2072                                                 *ptr++ = ':';
2073                                         }
2074                                         *ptr++ = '=';
2075                                         if ( k ) {
2076                                                 k = lutil_b64_ntop(
2077                                                         (unsigned char *) dv->vals[ j ].bv_val,
2078                                                         dv->vals[ j ].bv_len,
2079                                                         ptr, buf + len - ptr );
2080                                                 assert( k >= 0 );
2081                                                 ptr += k;
2082                                                 
2083                                         } else {
2084                                                 ptr = lutil_memcopy( ptr, dv->vals[ j ].bv_val, dv->vals[ j ].bv_len );
2085                                         }
2086                                         *ptr++ = '>';
2087                                         *ptr++ = ';';
2088                                 }
2089                         }
2090                 }
2091                 ptr = lutil_strncopy( ptr, dr->derefVal.bv_val, dr->derefVal.bv_len );
2092                 *ptr++ = '\n';
2093                 *ptr = '\0';
2094                 assert( ptr <= buf + len );
2095
2096                 tool_write_ldif( LDIF_PUT_COMMENT, NULL, buf, ptr - buf);
2097
2098                 ldap_memfree( buf );
2099         }
2100
2101         rc = LDAP_SUCCESS;
2102
2103 done:;
2104         ldap_derefresponse_free( drhead );
2105
2106         return rc;
2107 }
2108 #endif
2109
2110 #ifdef LDAP_CONTROL_X_WHATFAILED
2111 static int
2112 print_whatfailed( LDAP *ld, LDAPControl *ctrl )
2113 {
2114         BerElement *ber;
2115         ber_tag_t tag;
2116         ber_len_t siz;
2117         BerVarray bva = NULL;
2118
2119         /* Create a BerElement from the berval returned in the control. */
2120         ber = ber_init( &ctrl->ldctl_value );
2121
2122         if ( ber == NULL ) {
2123                 return LDAP_NO_MEMORY;
2124         }
2125
2126         siz = sizeof(struct berval);
2127         tag = ber_scanf( ber, "[M]", &bva, &siz, 0 );
2128         if ( tag != LBER_ERROR ) {
2129                 int i;
2130
2131                 tool_write_ldif( LDIF_PUT_COMMENT, " what failed:", NULL, 0 );
2132
2133                 for ( i = 0; bva[i].bv_val != NULL; i++ ) {
2134                         tool_write_ldif( LDIF_PUT_COMMENT, NULL, bva[i].bv_val, bva[i].bv_len );
2135                 }
2136
2137                 ldap_memfree( bva );
2138         }
2139
2140         ber_free( ber, 1 );
2141
2142
2143         return 0;
2144 }
2145 #endif
2146
2147 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
2148 static int
2149 print_ppolicy( LDAP *ld, LDAPControl *ctrl )
2150 {
2151         int expire = 0, grace = 0, rc;
2152         LDAPPasswordPolicyError pperr;
2153
2154         rc = ldap_parse_passwordpolicy_control( ld, ctrl,
2155                 &expire, &grace, &pperr );
2156         if ( rc == LDAP_SUCCESS ) {
2157                 char    buf[ BUFSIZ ], *ptr = buf;
2158
2159                 if ( expire != -1 ) {
2160                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2161                                 "expire=%d", expire );
2162                 }
2163
2164                 if ( grace != -1 ) {
2165                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2166                                 "%sgrace=%d", ptr == buf ? "" : " ", grace );
2167                 }
2168
2169                 if ( pperr != PP_noError ) {
2170                         ptr += snprintf( ptr, sizeof( buf ) - ( ptr - buf ),
2171                                 "%serror=%d (%s)", ptr == buf ? "" : " ",
2172                                 pperr,
2173                                 ldap_passwordpolicy_err2txt( pperr ) );
2174                 }
2175
2176                 tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2177                         "ppolicy", buf, ptr - buf );
2178         }
2179
2180         return rc;
2181 }
2182 #endif
2183
2184 void tool_print_ctrls(
2185         LDAP            *ld,
2186         LDAPControl     **ctrls )
2187 {
2188         int     i;
2189         char    *ptr;
2190
2191         for ( i = 0; ctrls[i] != NULL; i++ ) {
2192                 /* control: OID criticality base64value */
2193                 struct berval b64 = BER_BVNULL;
2194                 ber_len_t len;
2195                 char *str;
2196                 int j;
2197
2198                 /* FIXME: there might be cases where a control has NULL OID;
2199                  * this makes little sense, especially when returned by the
2200                  * server, but libldap happily allows it */
2201                 if ( ctrls[i]->ldctl_oid == NULL ) {
2202                         continue;
2203                 }
2204
2205                 len = ldif ? 2 : 0;
2206                 len += strlen( ctrls[i]->ldctl_oid );
2207
2208                 /* add enough for space after OID and the critical value itself */
2209                 len += ctrls[i]->ldctl_iscritical
2210                         ? sizeof("true") : sizeof("false");
2211
2212                 /* convert to base64 */
2213                 if ( !BER_BVISNULL( &ctrls[i]->ldctl_value ) ) {
2214                         b64.bv_len = LUTIL_BASE64_ENCODE_LEN(
2215                                 ctrls[i]->ldctl_value.bv_len ) + 1;
2216                         b64.bv_val = ber_memalloc( b64.bv_len + 1 );
2217
2218                         b64.bv_len = lutil_b64_ntop(
2219                                 (unsigned char *) ctrls[i]->ldctl_value.bv_val,
2220                                 ctrls[i]->ldctl_value.bv_len,
2221                                 b64.bv_val, b64.bv_len );
2222                 }
2223
2224                 if ( b64.bv_len ) {
2225                         len += 1 + b64.bv_len;
2226                 }
2227
2228                 ptr = str = malloc( len + 1 );
2229                 if ( ldif ) {
2230                         ptr = lutil_strcopy( ptr, ": " );
2231                 }
2232                 ptr = lutil_strcopy( ptr, ctrls[i]->ldctl_oid );
2233                 ptr = lutil_strcopy( ptr, ctrls[i]->ldctl_iscritical
2234                         ? " true" : " false" );
2235
2236                 if ( b64.bv_len ) {
2237                         ptr = lutil_strcopy( ptr, " " );
2238                         ptr = lutil_strcopy( ptr, b64.bv_val );
2239                 }
2240
2241                 if ( ldif < 2 ) {
2242                         tool_write_ldif( ldif ? LDIF_PUT_COMMENT : LDIF_PUT_VALUE,
2243                                 "control", str, len );
2244                 }
2245
2246                 free( str );
2247                 if ( b64.bv_len ) {
2248                         ber_memfree( b64.bv_val );
2249                 }
2250
2251                 /* known controls */
2252                 for ( j = 0; tool_ctrl_response[j].oid != NULL; j++ ) {
2253                         if ( strcmp( tool_ctrl_response[j].oid, ctrls[i]->ldctl_oid ) == 0 ) {
2254                                 if ( !tool_ctrl_response[j].mask & tool_type ) {
2255                                         /* this control should not appear
2256                                          * with this tool; warning? */
2257                                 }
2258                                 break;
2259                         }
2260                 }
2261
2262                 if ( tool_ctrl_response[j].oid != NULL && tool_ctrl_response[j].func ) {
2263                         (void)tool_ctrl_response[j].func( ld, ctrls[i] );
2264                 }
2265         }
2266 }
2267
2268 int
2269 tool_write_ldif( int type, char *name, char *value, ber_len_t vallen )
2270 {
2271         char    *ldif;
2272
2273         if (( ldif = ldif_put_wrap( type, name, value, vallen, ldif_wrap )) == NULL ) {
2274                 return( -1 );
2275         }
2276
2277         fputs( ldif, stdout );
2278         ber_memfree( ldif );
2279
2280         return( 0 );
2281 }
2282
2283 int
2284 tool_is_oid( const char *s )
2285 {
2286         int             first = 1;
2287
2288         if ( !isdigit( (unsigned char) s[ 0 ] ) ) {
2289                 return 0;
2290         }
2291
2292         for ( ; s[ 0 ]; s++ ) {
2293                 if ( s[ 0 ] == '.' ) {
2294                         if ( s[ 1 ] == '\0' ) {
2295                                 return 0;
2296                         }
2297                         first = 1;
2298                         continue;
2299                 }
2300
2301                 if ( !isdigit( (unsigned char) s[ 0 ] ) ) {
2302                         return 0;
2303                 }
2304
2305                 if ( first == 1 && s[ 0 ] == '0' && s[ 1 ] != '.' ) {
2306                         return 0;
2307                 }
2308                 first = 0;
2309         }
2310
2311         return 1;
2312 }
2313