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