]> git.sur5r.net Git - openldap/blob - servers/slapd/tools/centipede.c
Per ITS#419, don't require SLAPD_RLOOKUPS when HAVE_TCPD
[openldap] / servers / slapd / tools / centipede.c
1 /* centipede.c - generate and install indexing information (view w/tabstop=4) */
2 /* $OpenLDAP$ */
3
4 #include "portable.h"
5
6 #include <stdio.h>
7 #include <ac/stdlib.h>
8
9 #include <ac/ctype.h>
10 #include <ac/string.h>
11 #include <ac/time.h>
12 #include <ac/unistd.h>          /* get link(), unlink() */
13
14 #include <ldap.h>
15 #include <ldbm.h>
16
17 int     slap_debug;
18
19 #define DEFAULT_LDAPFILTER      "(objectclass=*)"
20
21 #define CENTROID_VALUE  1
22 #define CENTROID_WORD   2
23
24 #define CENTROID_RELATIVE       1
25 #define CENTROID_FULL           2
26
27 #define WORD_BREAKS     " -',.()!;:&$%*\"/\\+_<>=?[]|^~"
28
29 char    *centdir;
30 int             ldbmcachesize;
31 int             centroidvalues;
32 int             centroidtype;
33 int             doweights;
34 char    *ldaphost;
35 char    *srcldapbinddn;
36 char    *srcldappasswd;
37 char    *destldapbinddn;
38 char    *destldappasswd;
39 char    *ldapbase;
40 int             srcldapauthmethod;
41 int             destldapauthmethod;
42 int             verbose;
43 int             not;
44
45 static LDAP             *start_ldap_search(char *ldapsrcurl, char *ldapfilter, char **attrs);
46 static LDAP             *bind_to_destination_ldap(char *ldapsrcurl, char *ldapdesturl);
47 static int              create_tmp_files(char **attrs, char ***tmpfile, LDBM **ldbm);
48 static int              generate_new_centroids(LDAP *ld, char **attrs, LDBM *ldbm);
49 static LDAPMod  **diff_centroids(char *attr, LDBM oldbm, LDBM nldbm, int nentries);
50 static LDAPMod  **full_centroid(char *attr, LDBM ldbm, int nentries);
51 static char             **charray_add_dup(char ***a, int *cur, int *max, char *s);
52
53 static void usage( char *name )
54 {
55         fprintf( stderr, "usage: %s [options] -s url -d url attributes\n", name );
56         fprintf( stderr, "where:\n" );
57         fprintf( stderr, "\t-s url\t\t[[ldap://][host[:port]]/]searchbasedn\n");
58         fprintf( stderr, "\t-d url\t\t[[ldap://][host[:port]]/]centroidentrydn\n");
59         fprintf( stderr, "options:\n" );
60         fprintf( stderr, "\t-v \t\tturn on verbose mode\n" );
61         fprintf( stderr, "\t-n \t\tgenerate, but do not install index info\n" );
62         fprintf( stderr, "\t-f filter\tentry selection filter\n" );
63         fprintf( stderr, "\t-F \t\tgenerate a full centroid\n" );
64         fprintf( stderr, "\t-R \t\tgenerate a relative centroid\n" );
65         fprintf( stderr, "\t-w \t\tgenerate a word-based centroid\n" );
66         fprintf( stderr, "\t-t directory\tcentroid directory\n" );
67         fprintf( stderr, "\t-b binddn\tsource bind dn\n" );
68         fprintf( stderr, "\t-p passwd\tsource bind passwd (for simple auth)\n" );
69         fprintf( stderr, "\t-m authmethod\tsource authmethod \"simple\" or \"kerberos\"\n" );
70         fprintf( stderr, "\t-B binddn\tdestination bind dn\n" );
71         fprintf( stderr, "\t-P passwd\tdestination bind passwd (for simple auth)\n" );
72         fprintf( stderr, "\t-M authmethod\tdestination authmethod \"simple\" or \"kerberos\"\n" );
73         fprintf( stderr, "\t-c size\t\tldbm cache size\n" );
74 }
75
76 int
77 main( int argc, char **argv )
78 {
79         char            *ldapfilter;
80         char            *ldapsrcurl, *ldapdesturl;
81         LDAP            *ld;
82         LDAPMod         **mods;
83         char            **attrs;
84         char            **tmpfile;
85         LDBM            *ldbm;
86         LDBM            oldbm;
87         char            buf[BUFSIZ];
88         int                     i, j, k, count;
89         char            *s;
90
91         ldapsrcurl = NULL;
92         ldapdesturl = NULL;
93         ldaphost = NULL;
94         ldapbase = NULL;
95         srcldapauthmethod = LDAP_AUTH_SIMPLE;
96         destldapauthmethod = LDAP_AUTH_SIMPLE;
97         srcldapbinddn = NULL;
98         srcldappasswd = NULL;
99         destldapbinddn = NULL;
100         destldappasswd = NULL;
101         ldapfilter = DEFAULT_LDAPFILTER;
102         centroidvalues = CENTROID_VALUE;
103         centroidtype = CENTROID_RELATIVE;
104         centdir = NULL;
105         tmpfile = NULL;
106         ldbmcachesize = 0;
107
108         while ( (i = getopt( argc, argv, "s:d:c:b:B:f:FRWp:P:m:M:t:vwn" ))
109             != EOF ) {
110                 switch ( i ) {
111                 case 's':       /* source url [[ldap://][host[:port]]/]basedn */
112                         ldapsrcurl = strdup( optarg );
113                         break;
114
115                 case 'd':       /* destination url [[ldap://][host[:port]]/]entrydn */
116                         ldapdesturl = strdup( optarg );
117                         break;
118
119                 case 'f':       /* specify a filter */
120                         ldapfilter = strdup( optarg );
121                         break;
122
123                 case 'F':       /* generate full centroid */
124                         centroidtype = CENTROID_FULL;
125                         break;
126
127                 case 'R':       /* generate relative centroid */
128                         centroidtype = CENTROID_RELATIVE;
129                         break;
130
131                 case 'w':       /* generate word centroid */
132                         centroidvalues = CENTROID_WORD;
133                         break;
134
135                 case 'W':       /* generate weights */
136                         doweights = 1;
137                         break;
138
139                 case 't':       /* temp file directory */
140                         centdir = strdup( optarg );
141                         break;
142
143                 case 'b':       /* src bind dn */
144                         srcldapbinddn = strdup( optarg );
145                         break;
146
147                 case 'p':       /* src bind password */
148                         srcldappasswd = strdup( optarg );
149                         while ( *optarg )
150                                 *optarg++ = 'x';
151                         break;
152
153                 case 'B':       /* dest bind dn */
154                         destldapbinddn = strdup( optarg );
155                         break;
156
157                 case 'P':       /* dest bind password */
158                         destldappasswd = strdup( optarg );
159                         while ( *optarg )
160                                 *optarg++ = 'x';
161                         break;
162
163                 case 'm':       /* src bind method */
164                         if ( strcasecmp( optarg, "simple" ) == 0 ) {
165                                 srcldapauthmethod = LDAP_AUTH_SIMPLE;
166                         } else if ( strcasecmp( optarg, "kerberos" ) == 0 ) {
167                                 srcldapauthmethod = LDAP_AUTH_KRBV4;
168                         } else {
169                                 fprintf( stderr, "%s: unknown auth method\n", optarg );
170                                 fputs( "expecting \"simple\" or \"kerberos\"\n", stderr );
171                                 exit( EXIT_FAILURE );
172                         }
173                         break;
174
175                 case 'M':       /* dest bind method */
176                         if ( strcasecmp( optarg, "simple" ) == 0 ) {
177                                 destldapauthmethod = LDAP_AUTH_SIMPLE;
178                         } else if ( strcasecmp( optarg, "kerberos" ) == 0 ) {
179                                 destldapauthmethod = LDAP_AUTH_KRBV4;
180                         } else {
181                                 fprintf( stderr, "%s: unknown auth method\n", optarg );
182                                 fputs( "expecting \"simple\" or \"kerberos\"\n", stderr );
183                                 exit( EXIT_FAILURE );
184                         }
185                         break;
186
187                 case 'c':       /* ldbm cache size */
188                         ldbmcachesize = atoi( optarg );
189                         break;
190
191                 case 'v':       /* turn on verbose mode */
192                         verbose++;
193                         break;
194
195                 case 'n':       /* don't actually install index info */
196                         not++;
197                         break;
198
199                 default:
200                         usage( argv[0] );
201                         exit( EXIT_FAILURE );
202                 }
203         }
204         if ( optind == argc || ldapsrcurl == NULL || ldapdesturl == NULL ) {
205                 usage( argv[0] );
206                 exit( EXIT_FAILURE );
207         }
208         attrs = &argv[optind];
209
210         /*
211          * open the ldap connection and start searching for the entries
212          * we will use to generate the centroids.
213          */
214
215         if ( (ld = start_ldap_search( ldapsrcurl, ldapfilter, attrs )) == NULL ) {
216                 fprintf( stderr, "could not initiate ldap search\n" );
217                 exit( EXIT_FAILURE );
218         }
219
220         if ( create_tmp_files( attrs, &tmpfile, &ldbm ) != 0 ) {
221                 fprintf( stderr, "could not create temp files\n" );
222                 exit( EXIT_FAILURE );
223         }
224
225         /*
226          * go through the entries returned, building a centroid for each
227          * attribute as we go.
228          */
229
230         if ( (count = generate_new_centroids( ld, attrs, ldbm )) < 1 ) {
231                 if ( count == 0 ) {
232                     fprintf( stderr, "no entries matched\n" );
233                     exit( EXIT_SUCCESS );
234                 } else {
235                     fprintf( stderr, "could not generate new centroid\n" );
236                     exit( EXIT_FAILURE );
237                 }
238         }
239
240         /*
241          * for each centroid we generated above, compare to the existing
242          * centroid, if any, and produce adds and deletes, or produce
243          * an entirely new centroid. in either case, update the "current"
244          * centroid version with the new one we just generated.
245          */
246
247         if ( (ld = bind_to_destination_ldap( ldapsrcurl, ldapdesturl )) == NULL ) {
248                 fprintf( stderr,
249                   "could not bind to index server, or could not create index entry\n" );
250                 exit( EXIT_FAILURE );
251         }
252
253         for ( i = 0; ldbm[i] != NULL; i++ ) {
254                 /* generate the name of the existing centroid, if any */
255                 s = strrchr( tmpfile[i], '/' );
256                 *s = '\0';
257                 sprintf( buf, "%s/cent.%s", tmpfile[i], attrs[i] );
258                 *s = '/';
259
260                 /* generate the full centroid changes */
261                 if ( centroidtype == CENTROID_FULL || (oldbm = ldbm_open( buf,
262                   LDBM_WRITER, 0, ldbmcachesize )) == NULL ) {
263                         if ( (mods = full_centroid( attrs[i], ldbm[i], count )) == NULL ) {
264                                 fprintf( stderr, "could not produce full centroid for %s\n",
265                                   attrs[i] );
266                                 continue;
267                         }
268
269                 /* generate the differential centroid changes */
270                 } else {
271                         if ( (mods = diff_centroids( attrs[i], oldbm, ldbm[i], count ))
272                           == NULL ) {
273                                 fprintf( stderr, "could not diff centroids\n" );
274                                 ldbm_close( oldbm );
275                                 continue;
276                         }
277                         ldbm_close( oldbm );
278                 }
279
280                 if ( verbose > 1 ) {
281                         printf("changes:\n");
282                         for ( j = 0; mods[j] != NULL; j++ ) {
283                                 switch( mods[j]->mod_op ) {
284                                 case LDAP_MOD_ADD:
285                                         printf( "\tadd: %s\n",mods[j]->mod_type );
286                                         break;
287                                 case LDAP_MOD_DELETE:
288                                         printf( "\tdelete: %s\n",mods[j]->mod_type );
289                                         break;
290                                 case LDAP_MOD_REPLACE:
291                                         printf( "\treplace: %s\n",mods[j]->mod_type );
292                                         break;
293                                 }
294                                 if ( mods[j]->mod_values != NULL ) {
295                                         for ( k = 0; mods[j]->mod_values[k] != NULL; k++ ) {
296                                                 printf( "\t\t%s\n", mods[j]->mod_values[k] );
297                                         }
298                                 }
299                         }
300                         printf("end changes:\n");
301                 }
302
303                 if ( verbose ) {
304                         printf( "%sModifying centroid...", not ? "Not " : "" );
305                         fflush( stdout );
306                 }
307
308                 /* attempt to make the changes to the index server entry */
309                 if ( !not && ldap_modify_s( ld, ldapbase, mods ) != LDAP_SUCCESS ) {
310                         fprintf( stderr, "could not apply centroid modification for %s\n",
311                           attrs[i] );
312                         ldap_perror( ld, ldapbase );
313                 }
314                 ldap_mods_free( mods, 1 );
315
316                 if ( verbose ) {
317                         printf( "\n" );
318                         fflush( stdout );
319                 }
320
321                 /* move the new centroid into the old one's place */
322                 if ( ! not ) {
323                         (void) unlink( buf );
324                         if ( link( tmpfile[i], buf ) != 0 ) {
325                                 perror( "link" );
326                                 fprintf( stderr, "could not rename %s to %s\n", buf,
327                                   tmpfile[i] );
328                                 continue;
329                         }
330                 }
331                 (void) unlink( tmpfile[i] );
332         }
333
334         /* clean up */
335         for ( i = 0; attrs[i] != NULL; i++ ) {
336                 ldbm_close( ldbm[i] );
337                 free( tmpfile[i] );
338         }
339         free( ldbm );
340         free( tmpfile );
341
342         exit( EXIT_SUCCESS );
343 }
344
345 /*
346  * open an ldap connection, bind, and initiate the search
347  */
348
349 static LDAP *
350 start_ldap_search(
351         char    *ldapsrcurl,
352         char    *ldapfilter,
353         char    **attrs
354 )
355 {
356         LDAP    *ld;
357         char    *s, *s2;
358         int             i;
359
360         if ( strncmp( ldapsrcurl, "ldap://", 7 ) != 0 ) {
361                 fputs( "Not an LDAP URL", stderr ); /* Should be smarter? */
362                 return( NULL );
363         }
364         s = ldapsrcurl + 7;
365         if ( (s2 = strchr( s, '/' )) == NULL ) {
366                 ldapbase = strdup( s );
367         } else {
368                 if ( *s != '/' ) {
369                         *s2 = '\0';
370                         ldaphost = strdup( s );
371                         *s2 = '/';
372                 }
373                 ldapbase = strdup( s2 + 1 );
374         }
375
376         if ( verbose ) {
377                 printf( "Base: %s\n", ldapbase );
378                 printf( "Attributes:" );
379                 for ( i = 0; attrs[i] != NULL; i++ ) {
380                         printf( " %s", attrs[i] );
381                 }
382                 printf( "\n" );
383                 printf( "Binding to source LDAP server..." );
384                 fflush( stdout );
385         }
386
387         if ( (ld = ldap_init( ldaphost, 0 )) == NULL ) {
388                 perror( "ldap_init" );
389                 return( NULL );
390         }
391
392         if ( ldap_bind_s( ld, srcldapbinddn, srcldappasswd, srcldapauthmethod )
393           != LDAP_SUCCESS) {
394                 ldap_perror( ld, "ldap_bind_s" );
395                 ldap_unbind( ld );
396                 return( NULL );
397         }
398
399         printf( "\nInitiating search..." );
400         if ( ldap_search( ld, ldapbase, LDAP_SCOPE_SUBTREE, ldapfilter, attrs, 0 )
401           == -1 ) {
402                 ldap_perror( ld, "ldap_search" );
403                 ldap_unbind( ld );
404                 return( NULL );
405         }
406
407         if ( verbose ) {
408                 printf( "\n" );
409         }
410
411         return( ld );
412 }
413
414 /*
415  * create the temporary ldbm files we will use to hold the new centroids
416  */
417
418 static int
419 create_tmp_files(
420         char    **attrs,
421         char    ***tmpfile,
422         LDBM    **ldbm
423 )
424 {
425         int     i;
426
427         for ( i = 0; attrs[i] != NULL; i++ )
428                 ;       /* NULL */
429         i++;
430
431         if ( (*tmpfile = (char **) malloc( i * sizeof(char *) )) == NULL ) {
432                 perror( "malloc" );
433                 return( -1 );
434         }
435         if ( (*ldbm = (LDBM *) malloc( i * sizeof(LDBM) )) == NULL ) {
436                 perror( "malloc" );
437                 return( -1 );
438         }
439         for ( i = 0; attrs[i] != NULL; i++ ) {
440                 if ( ((*tmpfile)[i] = tempnam( centdir, NULL )) == NULL ) {
441                         perror( "tmpnam" );
442                         return( -1 );
443                 }
444
445                 if ( ((*ldbm)[i] = ldbm_open( (*tmpfile)[i], LDBM_WRCREAT, 0600,
446                   ldbmcachesize )) == NULL ) {
447                         fprintf( stderr, "ldbm_open of \"%s\" failed\n", (*tmpfile)[i] );
448                         perror( "ldbm_open" );
449                         return( -1 );
450                 }
451         }
452         (*tmpfile)[i] = NULL;
453         (*ldbm)[i] = NULL;
454
455         return( 0 );
456 }
457
458 /*
459  * step through each entry returned from the search and generate
460  * the appropriate centroid values.
461  */
462
463 static int
464 generate_new_centroids(
465         LDAP    *ld,
466         char    **attrs,
467         LDBM    *ldbm
468 )
469 {
470         Datum           key, data;
471         int                     rc, i, j, count;
472         LDAPMessage     *res, *e;
473         char            *dn, *s, *w;
474         char            **val;
475         char            last;
476
477         ldbm_datum_init( data );
478
479         if ( verbose ) {
480                 printf( "Generating new centroids for..." );
481                 fflush( stdout );
482         }
483
484         data.dptr = "";
485         data.dsize = 1;
486         count = 0;
487         while ( (rc = ldap_result( ld, LDAP_RES_ANY, 0, NULL, &res ))
488           == LDAP_RES_SEARCH_ENTRY ) {
489                 count++;
490                 e = ldap_first_entry( ld, res );
491                 dn = ldap_get_dn( ld, e );
492
493                 /* for each attr we want to generate a centroid for */
494                 for ( i = 0; attrs[i] != NULL; i++ ) {
495                         if ( (val = ldap_get_values( ld, e, attrs[i] )) == NULL ) {
496                                 continue;
497                         }
498
499                         /* for each value */
500                         for ( j = 0; val[j] != NULL; j++ ) {
501
502                                 ldbm_datum_init( key );
503
504                                 /* normalize the value */
505                                 for ( s = val[j]; *s; s++ ) {
506                                         *s = TOLOWER( (unsigned char) *s );
507                                         last = *s;
508                                 }
509                                 if ( isascii( last ) && isdigit( last ) ) {
510                                         continue;
511                                 }
512
513                                 /* generate a value-based centroid */
514                                 if ( centroidvalues == CENTROID_VALUE ) {
515                                         key.dptr = val[j];
516                                         key.dsize = strlen( key.dptr ) + 1;
517                                         (void) ldbm_store( ldbm[i], key, data, LDBM_INSERT );
518
519                                 /* generate a word-based centroid */
520                                 } else {
521                                         char *lasts;
522                                         for ( w = ldap_pvt_strtok( val[j], WORD_BREAKS, &lasts );
523                                           w != NULL;
524                                           w = ldap_pvt_strtok( NULL, WORD_BREAKS, &lasts ) ) {
525                                                 key.dptr = w;
526                                                 key.dsize = strlen( key.dptr ) + 1;
527                                                 (void) ldbm_store( ldbm[i], key, data, LDBM_INSERT );
528                                         }
529                                 }
530                         }
531                         ldap_value_free( val );
532                 }
533                 free( dn );
534                 ldap_msgfree( res );
535         }
536         ldap_msgfree( res );
537         ldap_unbind( ld );
538
539         if ( verbose ) {
540                 printf( "%d entries\n", count );
541         }
542
543         return( count );
544 }
545
546 /*
547  * compare the old and new centroids, generating the appropriate add
548  * and delete operations. if the underlying database is ordered, we
549  * can do this more efficiently.
550  */
551
552 static LDAPMod **
553 diff_centroids(
554         char    *attr,
555         LDBM    oldbm,
556         LDBM    nldbm,
557     int         nentries
558 )
559 {
560 #ifdef LDBM_ORDERED
561         Datum   okey, nkey;
562         Datum   olast, nlast;
563 #endif
564         Datum   lastkey, key;
565         Datum   data;
566         LDAPMod **mods;
567         char    **avals, **dvals;
568         int             amax, acur, dmax, dcur;
569         char    **vals;
570
571         LDBMCursor      *ocursorp;
572         LDBMCursor      *ncursorp;
573
574         if ( verbose ) {
575                 printf( "Generating mods for differential %s centroid...", attr );
576                 fflush( stdout );
577         }
578
579         ldbm_datum_init( lastkey );
580         ldbm_datum_init( key );
581         ldbm_datum_init( data );
582
583         if ( (mods = (LDAPMod **) malloc( sizeof(LDAPMod *) * 4 )) == NULL ||
584              (mods[0] = (LDAPMod *) malloc( sizeof(LDAPMod) )) == NULL ||
585              (mods[1] = (LDAPMod *) malloc( sizeof(LDAPMod) )) == NULL ||
586              (mods[2] = (LDAPMod *) malloc( sizeof(LDAPMod) )) == NULL ||
587              (vals = (char **) malloc( 2 * sizeof(char *) )) == NULL ||
588                  (vals[0] = (char *) malloc( 20 )) == NULL )
589         {
590                 perror( "malloc" );
591                 exit( EXIT_FAILURE );
592         }
593         /* add values in mods[0] */
594         mods[0]->mod_op = LDAP_MOD_ADD;
595         mods[0]->mod_type = attr;
596         mods[0]->mod_values = NULL;
597         avals = NULL;
598         acur = amax = 0;
599         /* delete values in mods[1] */
600         mods[1]->mod_op = LDAP_MOD_DELETE;
601         mods[1]->mod_type = attr;
602         mods[1]->mod_values = NULL;
603         dvals = NULL;
604         dcur = dmax = 0;
605         /* number of entries in mods[2] */
606         sprintf( vals[0], "%d", nentries );
607         vals[1] = NULL;
608         mods[2]->mod_op = LDAP_MOD_REPLACE;
609         mods[2]->mod_type = "nentries";
610         mods[2]->mod_values = vals;
611         /* null terminate list of mods */
612         mods[3] = NULL;
613
614 #ifdef LDBM_ORDERED
615         /*
616          * if the underlying database is ordered, we can do a more efficient
617          * dual traversal, yielding O(N) performance.
618          */
619
620         ldbm_datum_init( okey );
621         ldbm_datum_init( nkey );
622         ldbm_datum_init( olast );
623         ldbm_datum_init( nlast );
624
625         olast.dptr = NULL;
626         nlast.dptr = NULL;
627
628         for ( okey = ldbm_firstkey( oldbm, &ocursorp ),
629                         nkey = ldbm_firstkey( nldbm, &ncursorp );
630               okey.dptr != NULL && nkey.dptr != NULL; )
631         {
632                 int     rc = strcmp( okey.dptr, nkey.dptr );
633
634                 if ( rc == 0 ) {
635                         /* value is in both places - leave it */
636                         if ( olast.dptr != NULL ) {
637                                 ldbm_datum_free( oldbm, olast );
638                         }
639                         olast = okey;
640                         if ( nlast.dptr != NULL ) {
641                                 ldbm_datum_free( nldbm, nlast );
642                         }
643                         nlast = nkey;
644
645                         okey = ldbm_nextkey( oldbm, olast, ocursorp );
646                         nkey = ldbm_nextkey( nldbm, nlast, ncursorp );
647
648                 } else if ( rc > 0 ) {
649                         /* new value is not in old centroid - add it */
650                         if ( charray_add_dup( &avals, &acur, &amax, nkey.dptr ) == NULL ) {
651                                 ldap_mods_free( mods, 1 );
652                                 return( NULL );
653                         }
654
655                         if ( nlast.dptr != NULL ) {
656                                 ldbm_datum_free( nldbm, nlast );
657                         }
658                         nlast = nkey;
659
660                         nkey = ldbm_nextkey( nldbm, nlast, ncursorp );
661
662                 } else {
663                         /* old value is not in new centroid - delete it */
664                         if ( charray_add_dup( &dvals, &dcur, &dmax, okey.dptr ) == NULL ) {
665                                 ldap_mods_free( mods, 1 );
666                                 return( NULL );
667                         }
668
669                         if ( olast.dptr != NULL ) {
670                                 ldbm_datum_free( oldbm, olast );
671                         }
672                         olast = okey;
673
674                         okey = ldbm_nextkey( oldbm, olast, ocursorp );
675                 }
676         }
677
678         while ( okey.dptr != NULL ) {
679                 if ( charray_add_dup( &dvals, &dcur, &dmax, okey.dptr ) == NULL ) {
680                         ldap_mods_free( mods, 1 );
681                         return( NULL );
682                 }
683
684                 okey = ldbm_nextkey( oldbm, olast, ocursorp );
685                 if ( olast.dptr != NULL ) {
686                         ldbm_datum_free( oldbm, olast );
687                 }
688                 olast = okey;
689         }
690         if ( olast.dptr != NULL ) {
691                 ldbm_datum_free( oldbm, olast );
692         }
693         while ( nkey.dptr != NULL ) {
694                 if ( charray_add_dup( &avals, &acur, &amax, nkey.dptr ) == NULL ) {
695                         ldap_mods_free( mods, 1 );
696                         return( NULL );
697                 }
698
699                 nkey = ldbm_nextkey( nldbm, nlast, ncursorp );
700                 if ( nlast.dptr != NULL ) {
701                         ldbm_datum_free( nldbm, nlast );
702                 }
703                 nlast = nkey;
704         }
705         if ( nlast.dptr != NULL ) {
706                 ldbm_datum_free( nldbm, nlast );
707         }
708 #else
709         /*
710          * if the underlying database is not ordered, we have to
711          * generate list of values to add by stepping through all new
712          * values and looking them up in the old centroid (not there => add),
713          * then stepping through all old values and looking them up in the
714          * new centroid (not there => delete). this yields O(Nf(N)) performance,
715          * where f(N) is the order to retrieve a single item.
716          */
717
718         /* generate list of values to add */
719         lastkey.dptr = NULL;
720         for ( key = ldbm_firstkey( nldbm, &ncursorp ); key.dptr != NULL;
721           key = ldbm_nextkey( nldbm, lastkey, ncursorp ) )
722         {
723                 /* see if it's in the old one */
724                 data = ldbm_fetch( oldbm, key );
725
726                 /* not there - add it */
727                 if ( data.dptr == NULL ) {
728                         if ( charray_add_dup( &avals, &acur, &amax, key.dptr ) == NULL ) {
729                                 ldap_mods_free( mods, 1 );
730                                 return( NULL );
731                         }
732                 } else {
733                         ldbm_datum_free( oldbm, data );
734                 }
735                 if ( lastkey.dptr != NULL ) {
736                         ldbm_datum_free( nldbm, lastkey );
737                 }
738                 lastkey = key;
739         }
740         if ( lastkey.dptr != NULL ) {
741                 ldbm_datum_free( nldbm, lastkey );
742         }
743
744         /* generate list of values to delete */
745         lastkey.dptr = NULL;
746         for ( key = ldbm_firstkey( oldbm, &ocursorp ); key.dptr != NULL;
747           key = ldbm_nextkey( oldbm, lastkey, ocursorp ) )
748         {
749                 /* see if it's in the new one */
750                 data = ldbm_fetch( nldbm, key );
751
752                 /* not there - delete it */
753                 if ( data.dptr == NULL ) {
754                         if ( charray_add_dup( &dvals, &dcur, &dmax, key.dptr ) == NULL ) {
755                                 ldap_mods_free( mods, 1 );
756                                 return( NULL );
757                         }
758                 } else {
759                         ldbm_datum_free( nldbm, data );
760                 }
761                 if ( lastkey.dptr != NULL ) {
762                         ldbm_datum_free( oldbm, lastkey );
763                 }
764                 lastkey = key;
765         }
766         if ( lastkey.dptr != NULL ) {
767                 ldbm_datum_free( oldbm, lastkey );
768         }
769 #endif
770
771         mods[0]->mod_values = avals;
772         mods[1]->mod_values = dvals;
773
774         if ( verbose ) {
775                 printf( "\n" );
776                 fflush( stdout );
777         }
778
779         if ( mods[1]->mod_values == NULL ) {
780                 free( (char *) mods[1] );
781                 mods[1] = NULL;
782         }
783         if ( mods[0]->mod_values == NULL ) {
784                 free( (char *) mods[0] );
785                 mods[0] = mods[1];
786                 mods[1] = NULL;
787         }
788         if ( mods[0] == NULL ) {
789                 free( (char *) mods );
790                 return( NULL );
791         } else {
792                 return( mods );
793         }
794 }
795
796 static LDAPMod **
797 full_centroid(
798         char    *attr,
799         LDBM    ldbm,
800     int         nentries
801 )
802 {
803         Datum   key, lastkey;
804         LDAPMod **mods;
805         char    **vals;
806         int             vcur, vmax;
807
808         LDBMCursor *cursorp;
809
810         if ( verbose ) {
811                 printf( "Generating mods for full %s centroid...", attr );
812                 fflush( stdout );
813         }
814
815         ldbm_datum_init( key );
816         ldbm_datum_init( lastkey );
817
818         if ( (mods = (LDAPMod **) malloc( sizeof(LDAPMod *) * 3 )) == NULL ||
819              (mods[0] = (LDAPMod *) malloc( sizeof(LDAPMod) )) == NULL ||
820              (mods[1] = (LDAPMod *) malloc( sizeof(LDAPMod) )) == NULL ||
821              (vals = (char **) malloc( 2 * sizeof(char *) )) == NULL ||
822              (vals[0] = (char *) malloc( 20 )) == NULL )
823         {
824                 perror( "malloc" );
825                 exit( EXIT_FAILURE );
826         }
827         mods[0]->mod_op = LDAP_MOD_REPLACE;
828         mods[0]->mod_type = attr;
829         mods[0]->mod_values = NULL;
830         sprintf( vals[0], "%d", nentries );
831         vals[1] = NULL;
832         mods[1]->mod_op = LDAP_MOD_REPLACE;
833         mods[1]->mod_type = "nentries";
834         mods[1]->mod_values = vals;
835         mods[2] = NULL;
836
837         lastkey.dptr = NULL;
838         vals = NULL;
839         vcur = vmax = 0;
840
841         for ( key = ldbm_firstkey( ldbm, &cursorp ); key.dptr != NULL;
842           key = ldbm_nextkey( ldbm, lastkey, cursorp ) )
843         {
844                 if ( charray_add_dup( &vals, &vcur, &vmax, key.dptr ) == NULL ) {
845                         ldap_mods_free( mods, 1 );
846                         return( NULL );
847                 }
848
849                 if ( lastkey.dptr != NULL ) {
850                         ldbm_datum_free( ldbm, lastkey );
851                 }
852                 lastkey = key;
853         }
854         if ( lastkey.dptr != NULL ) {
855                 ldbm_datum_free( ldbm, lastkey );
856         }
857         mods[0]->mod_values = vals;
858
859         if ( verbose ) {
860                 printf( "\n" );
861                 fflush( stdout );
862         }
863
864         if ( mods[0]->mod_values == NULL ) {
865                 free( (char *) mods[0] );
866                 free( (char *) mods );
867                 return( NULL );
868         } else {
869                 return( mods );
870         }
871 }
872
873 /*
874  * extract the destination ldap host, port, and base object for the
875  * server to receive the index information. then, open a connection,
876  * bind, and see if the entry exists. if not, create it and set things
877  * up so the centroid full and diff routines can modify it to contain
878  * the new centroid information.
879  */
880
881 static LDAP *
882 bind_to_destination_ldap(
883         char    *ldapsrcurl,
884         char    *ldapdesturl
885 )
886 {
887         LDAP            *ld;
888         LDAPMessage     *res;
889         int                     rc;
890         char            *s, *s2, *d;
891         char            *attrs[2], *refvalues[2], *ocvalues[2];
892         LDAPMod         *mp[3];
893         LDAPMod         m[2];
894         char            buf[BUFSIZ];
895
896         if ( verbose ) {
897                 printf( "Binding to destination LDAP server..." );
898                 fflush( stdout );
899         }
900
901         /* first, pick out the destination ldap server info */
902         if ( ldapbase != NULL ) {
903                 free( ldapbase );
904                 ldapbase = NULL;
905         }
906         if ( strncmp( ldapdesturl, "ldap://", 7 ) != 0 ) {
907                 fputs( "Not an LDAP URL", stderr ); /* Should be smarter? */
908                 return( NULL );
909         }
910         s = ldapdesturl + 7;
911         if ( (s2 = strchr( s, '/' )) == NULL ) {
912                 ldapbase = strdup( s );
913         } else {
914                 if ( *s != '/' ) {
915                         *s2 = '\0';
916                         if ( ldaphost != NULL )
917                                 free( ldaphost );
918                         ldaphost = strdup( s );
919                         *s2 = '/';
920                 }
921                 ldapbase = strdup( s2 + 1 );
922         }
923         strcpy( buf, "ref=" );
924         if ( strpbrk( ldapsrcurl, " ,;" ) != NULL ) {
925                 strcat( buf, "\"" );
926         }
927         for ( s = d = ldapsrcurl; *s; s++ ) {
928                 if ( *s != '"' ) {
929                         *d++ = *s;
930                 }
931         }
932         *d = '\0';
933         strcat( buf, ldapsrcurl );
934         if ( strpbrk( ldapsrcurl, " ,;" ) != NULL ) {
935                 strcat( buf, "\"" );
936         }
937         strcat( buf, ", " );
938         strcat( buf, ldapbase );
939         free( ldapbase );
940         ldapbase = strdup( buf );
941
942         if ( (ld = ldap_init( ldaphost, 0 )) == NULL ) {
943                 perror( "ldap_init" );
944                 return( NULL );
945         }
946
947         if ( ldap_bind_s( ld, destldapbinddn, destldappasswd, destldapauthmethod )
948           != LDAP_SUCCESS) {
949                 ldap_perror( ld, "ldap_bind_s" );
950                 ldap_unbind( ld );
951                 return( NULL );
952         }
953         if ( verbose ) {
954                 printf( "\n" );
955         }
956
957         attrs[0] = "c";
958         attrs[1] = NULL;
959         rc = ldap_search_s( ld, ldapbase, LDAP_SCOPE_BASE, "(objectclass=*)",
960           attrs, 0, &res );
961         ldap_msgfree( res );
962
963         if ( rc == LDAP_NO_SUCH_OBJECT ) {
964                 if ( verbose ) {
965                         printf( "%sCreating centroid entry...", not ? "Not " : "" );
966                         fflush( stdout );
967                 }
968
969                 /* create the centroid index entry */
970                 m[0].mod_op = 0;
971                 m[0].mod_type = "ref";
972                 refvalues[0] = ldapsrcurl;
973                 refvalues[1] = NULL;
974                 m[0].mod_values = refvalues;
975                 m[1].mod_op = 0;
976                 m[1].mod_type = "objectclass";
977                 ocvalues[0] = "indexentry";
978                 ocvalues[1] = NULL;
979                 m[1].mod_values = ocvalues;
980                 mp[0] = &m[0];
981                 mp[1] = &m[1];
982                 mp[2] = NULL;
983
984                 if ( !not && ldap_add_s( ld, ldapbase, mp ) != LDAP_SUCCESS ) {
985                         ldap_perror( ld, ldapbase );
986                         ldap_unbind( ld );
987                         return( NULL );
988                 }
989
990                 if ( verbose ) {
991                         printf( "\n" );
992                         fflush( stdout );
993                 }
994         } else if ( rc != LDAP_SUCCESS ) {
995                 ldap_perror( ld, "ldap_search_s" );
996                 ldap_unbind( ld );
997                 return( NULL );
998         }
999
1000         return( ld );
1001 }
1002
1003 static char **
1004 charray_add_dup(
1005         char    ***a,
1006     int         *cur,
1007     int         *max,
1008         char    *s
1009 )
1010 {
1011         if ( *a == NULL ) {
1012                 *a = (char **) malloc( (BUFSIZ + 1) * sizeof(char *) );
1013                 *cur = 0;
1014                 *max = BUFSIZ;
1015         } else if ( *cur >= *max ) {
1016                 *max += BUFSIZ;
1017                 *a = (char **) realloc( *a, (*max + 1) * sizeof(char *) );
1018         }
1019         if ( *a == NULL ) {
1020                 return( NULL );
1021         }
1022
1023         (*a)[(*cur)++] = strdup( s );
1024         (*a)[*cur] = NULL;
1025         return( *a );
1026 }