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