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