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