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