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