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