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