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