]> git.sur5r.net Git - openldap/blob - servers/slapd/syncrepl.c
59ba0302aac60baa8dfb41c934cc63b0f4953e62
[openldap] / servers / slapd / syncrepl.c
1 /* syncrepl.c -- Replication Engine which uses the LDAP Sync protocol */
2 /* $OpenLDAP$ */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4  *
5  * Copyright 2003-2005 The OpenLDAP Foundation.
6  * Portions Copyright 2003 by IBM Corporation.
7  * Portions Copyright 2003 by Howard Chu, Symas 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
19 #include "portable.h"
20
21 #include <stdio.h>
22
23 #include <ac/string.h>
24 #include <ac/socket.h>
25
26 #include "lutil.h"
27 #include "slap.h"
28 #include "lutil_ldap.h"
29
30 #include "config.h"
31
32 #include "ldap_rq.h"
33
34 struct nonpresent_entry {
35         struct berval *npe_name;
36         struct berval *npe_nname;
37         LDAP_LIST_ENTRY(nonpresent_entry) npe_link;
38 };
39
40 #define SYNCDATA_DEFAULT        0       /* entries are plain LDAP entries */
41 #define SYNCDATA_ACCESSLOG      1       /* entries are accesslog format */
42 #define SYNCDATA_CHANGELOG      2       /* entries are changelog format */
43
44 typedef struct syncinfo_s {
45         struct slap_backend_db *si_be;
46         struct re_s                     *si_re;
47         long                            si_rid;
48         struct berval           si_provideruri;
49         slap_bindconf           si_bindconf;
50         struct berval           si_filterstr;
51         struct berval           si_base;
52         int                                     si_scope;
53         int                                     si_attrsonly;
54         char                            *si_anfile;
55         AttributeName           *si_anlist;
56         AttributeName           *si_exanlist;
57         char                            **si_attrs;
58         char                            **si_exattrs;
59         int                                     si_allattrs;
60         int                                     si_allopattrs;
61         int                                     si_schemachecking;
62         int                                     si_type;
63         time_t                          si_interval;
64         time_t                          *si_retryinterval;
65         int                                     *si_retrynum_init;
66         int                                     *si_retrynum;
67         struct sync_cookie      si_syncCookie;
68         int                                     si_manageDSAit;
69         int                                     si_slimit;
70         int                                     si_tlimit;
71         int                                     si_refreshDelete;
72         int                                     si_refreshPresent;
73         int                                     si_syncdata;
74         Avlnode                         *si_presentlist;
75         LDAP                            *si_ld;
76         LDAP_LIST_HEAD(np, nonpresent_entry) si_nonpresentlist;
77         ldap_pvt_thread_mutex_t si_mutex;
78 } syncinfo_t;
79
80 static int syncuuid_cmp( const void *, const void * );
81 static void avl_ber_bvfree( void * );
82 static void syncrepl_del_nonpresent( Operation *, syncinfo_t *, BerVarray );
83 static int syncrepl_message_to_op(
84                                         syncinfo_t *, Operation *, LDAPMessage * );
85 static int syncrepl_message_to_entry(
86                                         syncinfo_t *, Operation *, LDAPMessage *,
87                                         Modifications **, Entry **, int );
88 static int syncrepl_entry(
89                                         syncinfo_t *, Operation*, Entry*,
90                                         Modifications**,int, struct berval*,
91                                         struct sync_cookie *,
92                                         struct berval * );
93 static void syncrepl_updateCookie(
94                                         syncinfo_t *, Operation *, struct berval *,
95                                         struct sync_cookie * );
96 static struct berval * slap_uuidstr_from_normalized(
97                                         struct berval *, struct berval *, void * );
98
99 /* callback functions */
100 static int dn_callback( struct slap_op *, struct slap_rep * );
101 static int nonpresent_callback( struct slap_op *, struct slap_rep * );
102 static int null_callback( struct slap_op *, struct slap_rep * );
103
104 static AttributeDescription *sync_descs[4];
105
106 static void
107 init_syncrepl(syncinfo_t *si)
108 {
109         int i, j, k, l, n;
110         char **attrs, **exattrs;
111
112         if ( !sync_descs[0] ) {
113                 sync_descs[0] = slap_schema.si_ad_objectClass;
114                 sync_descs[1] = slap_schema.si_ad_structuralObjectClass;
115                 sync_descs[2] = slap_schema.si_ad_entryCSN;
116                 sync_descs[3] = NULL;
117         }
118
119         if ( si->si_allattrs && si->si_allopattrs )
120                 attrs = NULL;
121         else
122                 attrs = anlist2attrs( si->si_anlist );
123
124         if ( attrs ) {
125                 if ( si->si_allattrs ) {
126                         i = 0;
127                         while ( attrs[i] ) {
128                                 if ( !is_at_operational( at_find( attrs[i] ))) {
129                                         for ( j = i; attrs[j] != NULL; j++ ) {
130                                                 if ( j == i )
131                                                         ch_free( attrs[i] );
132                                                 attrs[j] = attrs[j+1];
133                                         }
134                                 } else {
135                                         i++;
136                                 }
137                         }
138                         attrs = ( char ** ) ch_realloc( attrs, (i + 2)*sizeof( char * ) );
139                         attrs[i] = ch_strdup("*");
140                         attrs[i + 1] = NULL;
141
142                 } else if ( si->si_allopattrs ) {
143                         i = 0;
144                         while ( attrs[i] ) {
145                                 if ( is_at_operational( at_find( attrs[i] ))) {
146                                         for ( j = i; attrs[j] != NULL; j++ ) {
147                                                 if ( j == i )
148                                                         ch_free( attrs[i] );
149                                                 attrs[j] = attrs[j+1];
150                                         }
151                                 } else {
152                                         i++;
153                                 }
154                         }
155                         attrs = ( char ** ) ch_realloc( attrs, (i + 2)*sizeof( char * ) );
156                         attrs[i] = ch_strdup("+");
157                         attrs[i + 1] = NULL;
158                 }
159
160                 for ( i = 0; sync_descs[i] != NULL; i++ ) {
161                         j = 0;
162                         while ( attrs[j] ) {
163                                 if ( !strcmp( attrs[j], sync_descs[i]->ad_cname.bv_val )) {
164                                         for ( k = j; attrs[k] != NULL; k++ ) {
165                                                 if ( k == j )
166                                                         ch_free( attrs[k] );
167                                                 attrs[k] = attrs[k+1];
168                                         }
169                                 } else {
170                                         j++;
171                                 }
172                         }
173                 }
174
175                 for ( n = 0; attrs[ n ] != NULL; n++ ) /* empty */;
176
177                 if ( si->si_allopattrs ) {
178                         attrs = ( char ** ) ch_realloc( attrs, (n + 2)*sizeof( char * ));
179                 } else {
180                         attrs = ( char ** ) ch_realloc( attrs, (n + 4)*sizeof( char * ));
181                 }
182
183                 if ( attrs == NULL ) {
184                         Debug( LDAP_DEBUG_ANY, "out of memory\n", 0,0,0 );
185                 }
186
187                 /* Add Attributes */
188                 if ( si->si_allopattrs ) {
189                         attrs[n++] = ch_strdup( sync_descs[0]->ad_cname.bv_val );
190                 } else {
191                         for ( i = 0; sync_descs[ i ] != NULL; i++ ) {
192                                 attrs[ n++ ] = ch_strdup ( sync_descs[i]->ad_cname.bv_val );
193                         }
194                 }
195                 attrs[ n ] = NULL;
196
197         } else {
198
199                 i = 0;
200                 if ( si->si_allattrs == si->si_allopattrs ) {
201                         attrs = (char**) ch_malloc( 3 * sizeof(char*) );
202                         attrs[i++] = ch_strdup( "*" );
203                         attrs[i++] = ch_strdup( "+" );
204                 } else if ( si->si_allattrs && !si->si_allopattrs ) {
205                         for ( n = 0; sync_descs[ n ] != NULL; n++ ) ;
206                         attrs = (char**) ch_malloc( (n+1)* sizeof(char*) );
207                         attrs[i++] = ch_strdup( "*" );
208                         for ( j = 1; sync_descs[ j ] != NULL; j++ ) {
209                                 attrs[i++] = ch_strdup ( sync_descs[j]->ad_cname.bv_val );
210                         }
211                 } else if ( !si->si_allattrs && si->si_allopattrs ) {
212                         attrs = (char**) ch_malloc( 3 * sizeof(char*) );
213                         attrs[i++] = ch_strdup( "+" );
214                         attrs[i++] = ch_strdup( sync_descs[0]->ad_cname.bv_val );
215                 }
216                 attrs[i] = NULL;
217         }
218         
219         si->si_attrs = attrs;
220
221         exattrs = anlist2attrs( si->si_exanlist );
222
223         if ( exattrs ) {
224                 for ( n = 0; exattrs[n] != NULL; n++ ) ;
225
226                 for ( i = 0; sync_descs[i] != NULL; i++ ) {
227                         j = 0;
228                         while ( exattrs[j] != NULL ) {
229                                 if ( !strcmp( exattrs[j], sync_descs[i]->ad_cname.bv_val )) {
230                                         ch_free( exattrs[j] );
231                                         for ( k = j; exattrs[k] != NULL; k++ ) {
232                                                 exattrs[k] = exattrs[k+1];
233                                         }
234                                 } else {
235                                         j++;
236                                 }
237                         }
238                 }
239
240                 for ( i = 0; exattrs[i] != NULL; i++ ) {
241                         for ( j = 0; si->si_anlist[j].an_name.bv_val; j++ ) {
242                                 ObjectClass     *oc;
243                                 if ( ( oc = si->si_anlist[j].an_oc ) ) {
244                                         k = 0;
245                                         while ( oc->soc_required[k] ) {
246                                                 if ( !strcmp( exattrs[i],
247                                                          oc->soc_required[k]->sat_cname.bv_val )) {
248                                                         ch_free( exattrs[i] );
249                                                         for ( l = i; exattrs[l]; l++ ) {
250                                                                 exattrs[l] = exattrs[l+1];
251                                                         }
252                                                 } else {
253                                                         k++;
254                                                 }
255                                         }
256                                 }
257                         }
258                 }
259
260                 for ( i = 0; exattrs[i] != NULL; i++ ) ;
261
262                 if ( i != n )
263                         exattrs = (char **) ch_realloc( exattrs, (i + 1)*sizeof(char *));
264         }
265
266         si->si_exattrs = exattrs;       
267 }
268
269 static int
270 ldap_sync_search(
271         syncinfo_t *si,
272         void *ctx )
273 {
274         BerElementBuffer berbuf;
275         BerElement *ber = (BerElement *)&berbuf;
276         LDAPControl c[2], *ctrls[3];
277         struct timeval timeout;
278         ber_int_t       msgid;
279         int rc;
280
281         /* setup LDAP SYNC control */
282         ber_init2( ber, NULL, LBER_USE_DER );
283         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &ctx );
284
285         if ( !BER_BVISNULL( &si->si_syncCookie.octet_str ) )
286         {
287                 ber_printf( ber, "{eO}",
288                         abs(si->si_type),
289                         &si->si_syncCookie.octet_str );
290         } else {
291                 ber_printf( ber, "{e}",
292                         abs(si->si_type) );
293         }
294
295         if ( (rc = ber_flatten2( ber, &c[0].ldctl_value, 0 )) == LBER_ERROR ) {
296                 ber_free_buf( ber );
297                 return rc;
298         }
299
300         c[0].ldctl_oid = LDAP_CONTROL_SYNC;
301         c[0].ldctl_iscritical = si->si_type < 0;
302         ctrls[0] = &c[0];
303
304         if ( !BER_BVISNULL( &si->si_bindconf.sb_authzId ) ) {
305                 c[1].ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
306                 c[1].ldctl_value = si->si_bindconf.sb_authzId;
307                 c[1].ldctl_iscritical = 1;
308                 ctrls[1] = &c[1];
309                 ctrls[2] = NULL;
310         } else {
311                 ctrls[1] = NULL;
312         }
313
314         timeout.tv_sec = si->si_tlimit;
315         timeout.tv_usec = 0;
316
317         rc = ldap_search_ext( si->si_ld, si->si_base.bv_val, si->si_scope,
318                 si->si_filterstr.bv_val, si->si_attrs, si->si_attrsonly,
319                 ctrls, NULL, si->si_tlimit > 0 ? &timeout : NULL,
320                 si->si_slimit, &msgid );
321         ber_free_buf( ber );
322         return rc;
323 }
324
325 static int
326 do_syncrep1(
327         Operation *op,
328         syncinfo_t *si )
329 {
330         int     rc;
331         int cmdline_cookie_found = 0;
332
333         struct sync_cookie      *sc = NULL;
334         struct berval   *psub;
335 #ifdef HAVE_TLS
336         void    *ssl;
337 #endif
338
339         psub = &si->si_be->be_nsuffix[0];
340
341         /* Init connection to master */
342         rc = ldap_initialize( &si->si_ld, si->si_provideruri.bv_val );
343         if ( rc != LDAP_SUCCESS ) {
344                 Debug( LDAP_DEBUG_ANY,
345                         "do_syncrep1: ldap_initialize failed (%s)\n",
346                         si->si_provideruri.bv_val, 0, 0 );
347                 return rc;
348         }
349
350         op->o_protocol = LDAP_VERSION3;
351         ldap_set_option( si->si_ld, LDAP_OPT_PROTOCOL_VERSION, &op->o_protocol );
352
353         /* Bind to master */
354
355         if ( si->si_bindconf.sb_tls ) {
356                 rc = ldap_start_tls_s( si->si_ld, NULL, NULL );
357                 if( rc != LDAP_SUCCESS ) {
358                         Debug( LDAP_DEBUG_ANY,
359                                 "%s: ldap_start_tls failed (%d)\n",
360                                 si->si_bindconf.sb_tls == SB_TLS_CRITICAL ? "Error" : "Warning",
361                                 rc, 0 );
362                         if( si->si_bindconf.sb_tls == SB_TLS_CRITICAL ) goto done;
363                 }
364         }
365
366         if ( si->si_bindconf.sb_method == LDAP_AUTH_SASL ) {
367 #ifdef HAVE_CYRUS_SASL
368                 void *defaults;
369
370                 if ( si->si_bindconf.sb_secprops != NULL ) {
371                         rc = ldap_set_option( si->si_ld,
372                                 LDAP_OPT_X_SASL_SECPROPS, si->si_bindconf.sb_secprops);
373
374                         if( rc != LDAP_OPT_SUCCESS ) {
375                                 Debug( LDAP_DEBUG_ANY, "Error: ldap_set_option "
376                                         "(%s,SECPROPS,\"%s\") failed!\n",
377                                         si->si_provideruri.bv_val, si->si_bindconf.sb_secprops, 0 );
378                                 goto done;
379                         }
380                 }
381
382                 defaults = lutil_sasl_defaults( si->si_ld,
383                         si->si_bindconf.sb_saslmech.bv_val,
384                         si->si_bindconf.sb_realm.bv_val,
385                         si->si_bindconf.sb_authcId.bv_val,
386                         si->si_bindconf.sb_cred.bv_val,
387                         si->si_bindconf.sb_authzId.bv_val );
388
389                 rc = ldap_sasl_interactive_bind_s( si->si_ld,
390                                 si->si_bindconf.sb_binddn.bv_val,
391                                 si->si_bindconf.sb_saslmech.bv_val,
392                                 NULL, NULL,
393                                 LDAP_SASL_QUIET,
394                                 lutil_sasl_interact,
395                                 defaults );
396
397                 lutil_sasl_freedefs( defaults );
398
399                 /* FIXME: different error behaviors according to
400                  *      1) return code
401                  *      2) on err policy : exit, retry, backoff ...
402                  */
403                 if ( rc != LDAP_SUCCESS ) {
404                         static struct berval bv_GSSAPI = BER_BVC( "GSSAPI" );
405
406                         Debug( LDAP_DEBUG_ANY, "do_syncrep1: "
407                                 "ldap_sasl_interactive_bind_s failed (%d)\n",
408                                 rc, 0, 0 );
409
410                         /* FIXME (see above comment) */
411                         /* if Kerberos credentials cache is not active, retry */
412                         if ( ber_bvcmp( &si->si_bindconf.sb_saslmech, &bv_GSSAPI ) == 0 &&
413                                 rc == LDAP_LOCAL_ERROR )
414                         {
415                                 rc = LDAP_SERVER_DOWN;
416                         }
417
418                         goto done;
419                 }
420 #else /* HAVE_CYRUS_SASL */
421                 /* Should never get here, we trapped this at config time */
422                 assert(0);
423                 fprintf( stderr, "not compiled with SASL support\n" );
424                 rc = LDAP_OTHER;
425                 goto done;
426 #endif
427
428         } else if ( si->si_bindconf.sb_method == LDAP_AUTH_SIMPLE ) {
429                 rc = ldap_sasl_bind_s( si->si_ld,
430                         si->si_bindconf.sb_binddn.bv_val, LDAP_SASL_SIMPLE,
431                         &si->si_bindconf.sb_cred, NULL, NULL, NULL );
432                 if ( rc != LDAP_SUCCESS ) {
433                         Debug( LDAP_DEBUG_ANY, "do_syncrep1: "
434                                 "ldap_sasl_bind_s failed (%d)\n", rc, 0, 0 );
435                         goto done;
436                 }
437         }
438
439         /* Set SSF to strongest of TLS, SASL SSFs */
440         op->o_sasl_ssf = 0;
441         op->o_tls_ssf = 0;
442         op->o_transport_ssf = 0;
443 #ifdef HAVE_TLS
444         if ( ldap_get_option( si->si_ld, LDAP_OPT_X_TLS_SSL_CTX, &ssl )
445                 == LDAP_SUCCESS && ssl != NULL )
446         {
447                 op->o_tls_ssf = ldap_pvt_tls_get_strength( ssl );
448         }
449 #endif /* HAVE_TLS */
450         ldap_get_option( si->si_ld, LDAP_OPT_X_SASL_SSF, &op->o_sasl_ssf );
451         op->o_ssf = ( op->o_sasl_ssf > op->o_tls_ssf )
452                 ?  op->o_sasl_ssf : op->o_tls_ssf;
453
454
455         if ( BER_BVISNULL( &si->si_syncCookie.octet_str )) {
456                 /* get contextCSN shadow replica from database */
457                 BerVarray csn = NULL;
458
459                 assert( si->si_rid < 1000 );
460                 op->o_req_ndn = op->o_bd->be_nsuffix[0];
461                 op->o_req_dn = op->o_req_ndn;
462
463                 /* try to read stored contextCSN */
464                 backend_attribute( op, NULL, &op->o_req_ndn,
465                         slap_schema.si_ad_contextCSN, &csn, ACL_READ );
466                 if ( csn ) {
467                         ch_free( si->si_syncCookie.ctxcsn.bv_val );
468                         ber_dupbv( &si->si_syncCookie.ctxcsn, csn );
469                         ber_bvarray_free_x( csn, op->o_tmpmemctx );
470                 }
471
472                 si->si_syncCookie.rid = si->si_rid;
473
474                 LDAP_STAILQ_FOREACH( sc, &slap_sync_cookie, sc_next ) {
475                         if ( si->si_rid == sc->rid ) {
476                                 cmdline_cookie_found = 1;
477                                 break;
478                         }
479                 }
480
481                 if ( cmdline_cookie_found ) {
482                         /* cookie is supplied in the command line */
483
484                         LDAP_STAILQ_REMOVE( &slap_sync_cookie, sc, sync_cookie, sc_next );
485
486                         /* ctxcsn wasn't parsed yet, do it now */
487                         slap_parse_sync_cookie( sc, op->o_tmpmemctx );
488                         if ( BER_BVISNULL( &sc->ctxcsn ) ) {
489                                 /* if cmdline cookie does not have ctxcsn */
490                                 /* component, set it to an initial value */
491                                 slap_init_sync_cookie_ctxcsn( sc );
492                         }
493                         slap_sync_cookie_free( &si->si_syncCookie, 0 );
494                         slap_dup_sync_cookie( &si->si_syncCookie, sc );
495                         slap_sync_cookie_free( sc, 1 );
496                 }
497
498                 slap_compose_sync_cookie( NULL, &si->si_syncCookie.octet_str,
499                         &si->si_syncCookie.ctxcsn, si->si_syncCookie.rid );
500         }
501
502         rc = ldap_sync_search( si, op->o_tmpmemctx );
503
504         if( rc != LDAP_SUCCESS ) {
505                 Debug( LDAP_DEBUG_ANY, "do_syncrep1: "
506                         "ldap_search_ext: %s (%d)\n", ldap_err2string( rc ), rc, 0 );
507         }
508
509 done:
510         if ( rc ) {
511                 if ( si->si_ld ) {
512                         ldap_unbind_ext( si->si_ld, NULL, NULL );
513                         si->si_ld = NULL;
514                 }
515         }
516
517         return rc;
518 }
519
520 static int
521 do_syncrep2(
522         Operation *op,
523         syncinfo_t *si )
524 {
525         LDAPControl     **rctrls = NULL;
526         LDAPControl     *rctrlp;
527
528         BerElementBuffer berbuf;
529         BerElement      *ber = (BerElement *)&berbuf;
530
531         LDAPMessage     *res = NULL;
532         LDAPMessage     *msg = NULL;
533
534         char            *retoid = NULL;
535         struct berval   *retdata = NULL;
536
537         Entry           *entry = NULL;
538
539         int             syncstate;
540         struct berval   syncUUID = BER_BVNULL;
541         struct sync_cookie      syncCookie = { BER_BVNULL };
542         struct sync_cookie      syncCookie_req = { BER_BVNULL };
543         struct berval           cookie = BER_BVNULL;
544
545         int     rc, err, i;
546         ber_len_t       len;
547
548         int rc_efree = 1;
549
550         struct berval   *psub;
551         Modifications   *modlist = NULL;
552
553         const char              *text;
554         int                             match;
555
556         struct timeval *tout_p = NULL;
557         struct timeval tout = { 0, 0 };
558
559         int             refreshDeletes = 0;
560         int             refreshDone = 1;
561         BerVarray syncUUIDs = NULL;
562         ber_tag_t si_tag;
563
564         if ( slapd_shutdown ) {
565                 rc = -2;
566                 goto done;
567         }
568
569         ber_init2( ber, NULL, LBER_USE_DER );
570         ber_set_option( ber, LBER_OPT_BER_MEMCTX, &op->o_tmpmemctx );
571
572         Debug( LDAP_DEBUG_TRACE, "=>do_syncrep2\n", 0, 0, 0 );
573
574         psub = &si->si_be->be_nsuffix[0];
575
576         slap_dup_sync_cookie( &syncCookie_req, &si->si_syncCookie );
577
578         if ( abs(si->si_type) == LDAP_SYNC_REFRESH_AND_PERSIST ) {
579                 tout_p = &tout;
580         } else {
581                 tout_p = NULL;
582         }
583
584         while (( rc = ldap_result( si->si_ld, LDAP_RES_ANY, LDAP_MSG_ONE,
585                 tout_p, &res )) > 0 )
586         {
587                 if ( slapd_shutdown ) {
588                         rc = -2;
589                         goto done;
590                 }
591                 for( msg = ldap_first_message( si->si_ld, res );
592                         msg != NULL;
593                         msg = ldap_next_message( si->si_ld, msg ) )
594                 {
595                         if ( slapd_shutdown ) {
596                                 rc = -2;
597                                 goto done;
598                         }
599                         switch( ldap_msgtype( msg ) ) {
600                         case LDAP_RES_SEARCH_ENTRY:
601                                 ldap_get_entry_controls( si->si_ld, msg, &rctrls );
602                                 /* we can't work without the control */
603                                 if ( !rctrls ) {
604                                         Debug( LDAP_DEBUG_ANY, "do_syncrep2: "
605                                                 "got search entry without "
606                                                 "control\n", 0, 0, 0 );
607                                         rc = -1;
608                                         goto done;
609                                 }
610                                 rctrlp = *rctrls;
611                                 ber_init2( ber, &rctrlp->ldctl_value, LBER_USE_DER );
612                                 ber_scanf( ber, "{em" /*"}"*/, &syncstate, &syncUUID );
613                                 /* FIXME: what if syncUUID is NULL or empty? */
614                                 if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE ) {
615                                         ber_scanf( ber, /*"{"*/ "m}", &cookie );
616                                         if ( !BER_BVISNULL( &cookie ) ) {
617                                                 ch_free( syncCookie.octet_str.bv_val );
618                                                 ber_dupbv( &syncCookie.octet_str, &cookie );
619                                         }
620                                         if ( !BER_BVISNULL( &syncCookie.octet_str ) )
621                                         {
622                                                 slap_parse_sync_cookie( &syncCookie, NULL );
623                                         }
624                                 }
625                                 if ( si->si_syncdata ) {
626                                         entry = NULL;
627                                         modlist = NULL;
628                                         if ( syncrepl_message_to_op( si, op, msg ) == LDAP_SUCCESS &&
629                                                 !BER_BVISNULL( &syncCookie.ctxcsn ) ) {
630                                                 syncrepl_updateCookie( si, op, psub, &syncCookie );
631                                         }
632                                 } else if ( syncrepl_message_to_entry( si, op, msg,
633                                         &modlist, &entry, syncstate ) == LDAP_SUCCESS ) {
634                                         rc_efree = syncrepl_entry( si, op, entry, &modlist,
635                                                 syncstate, &syncUUID, &syncCookie_req, &syncCookie.ctxcsn );
636                                         if ( !BER_BVISNULL( &syncCookie.ctxcsn ) )
637                                         {
638                                                 syncrepl_updateCookie( si, op, psub, &syncCookie );
639                                         }
640                                 }
641                                 ldap_controls_free( rctrls );
642                                 if ( modlist ) {
643                                         slap_mods_free( modlist, 1 );
644                                 }
645                                 if ( rc_efree && entry ) {
646                                         entry_free( entry );
647                                 }
648                                 entry = NULL;
649                                 break;
650
651                         case LDAP_RES_SEARCH_REFERENCE:
652                                 Debug( LDAP_DEBUG_ANY,
653                                         "do_syncrep2: reference received error\n", 0, 0, 0 );
654                                 break;
655
656                         case LDAP_RES_SEARCH_RESULT:
657                                 Debug( LDAP_DEBUG_SYNC,
658                                         "do_syncrep2: LDAP_RES_SEARCH_RESULT\n", 0, 0, 0 );
659                                 ldap_parse_result( si->si_ld, msg, &err, NULL, NULL, NULL,
660                                         &rctrls, 0 );
661                                 if ( rctrls ) {
662                                         rctrlp = *rctrls;
663                                         ber_init2( ber, &rctrlp->ldctl_value, LBER_USE_DER );
664
665                                         ber_scanf( ber, "{" /*"}"*/);
666                                         if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE ) {
667                                                 ber_scanf( ber, "m", &cookie );
668                                                 if ( !BER_BVISNULL( &cookie ) ) {
669                                                         ch_free( syncCookie.octet_str.bv_val );
670                                                         ber_dupbv( &syncCookie.octet_str, &cookie);
671                                                 }
672                                                 if ( !BER_BVISNULL( &syncCookie.octet_str ) )
673                                                 {
674                                                         slap_parse_sync_cookie( &syncCookie, NULL );
675                                                 }
676                                         }
677                                         if ( ber_peek_tag( ber, &len ) == LDAP_TAG_REFRESHDELETES )
678                                         {
679                                                 ber_scanf( ber, "b", &refreshDeletes );
680                                         }
681                                         ber_scanf( ber, /*"{"*/ "}" );
682                                 }
683                                 if ( BER_BVISNULL( &syncCookie_req.ctxcsn )) {
684                                         match = -1;
685                                 } else if ( BER_BVISNULL( &syncCookie.ctxcsn )) {
686                                         match = 1;
687                                 } else {
688                                         value_match( &match, slap_schema.si_ad_entryCSN,
689                                                 slap_schema.si_ad_entryCSN->ad_type->sat_ordering,
690                                                 SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
691                                                 &syncCookie_req.ctxcsn, &syncCookie.ctxcsn,
692                                                 &text );
693                                 }
694                                 if ( !BER_BVISNULL( &syncCookie.ctxcsn ) &&
695                                         match < 0 && err == LDAP_SUCCESS )
696                                 {
697                                         syncrepl_updateCookie( si, op, psub, &syncCookie );
698                                 }
699                                 if ( rctrls ) {
700                                         ldap_controls_free( rctrls );
701                                 }
702                                 if (si->si_type != LDAP_SYNC_REFRESH_AND_PERSIST) {
703                                         /* FIXME : different error behaviors according to
704                                          *      1) err code : LDAP_BUSY ...
705                                          *      2) on err policy : stop service, stop sync, retry
706                                          */
707                                         if ( refreshDeletes == 0 && match < 0 &&
708                                                 err == LDAP_SUCCESS )
709                                         {
710                                                 syncrepl_del_nonpresent( op, si, NULL );
711                                         } else {
712                                                 avl_free( si->si_presentlist, avl_ber_bvfree );
713                                                 si->si_presentlist = NULL;
714                                         }
715                                 }
716                                 rc = -2;
717                                 goto done;
718                                 break;
719
720                         case LDAP_RES_INTERMEDIATE:
721                                 rc = ldap_parse_intermediate( si->si_ld, msg,
722                                         &retoid, &retdata, NULL, 0 );
723                                 if ( !rc && !strcmp( retoid, LDAP_SYNC_INFO ) ) {
724                                         ber_init2( ber, retdata, LBER_USE_DER );
725
726                                         switch ( si_tag = ber_peek_tag( ber, &len )) {
727                                         ber_tag_t tag;
728                                         case LDAP_TAG_SYNC_NEW_COOKIE:
729                                                 Debug( LDAP_DEBUG_SYNC,
730                                                         "do_syncrep2: %s - %s%s\n", 
731                                                         "LDAP_RES_INTERMEDIATE", 
732                                                         "NEW_COOKIE", "\n" );
733                                                 ber_scanf( ber, "tm", &tag, &cookie );
734                                                 break;
735                                         case LDAP_TAG_SYNC_REFRESH_DELETE:
736                                         case LDAP_TAG_SYNC_REFRESH_PRESENT:
737                                                 Debug( LDAP_DEBUG_SYNC,
738                                                         "do_syncrep2: %s - %s%s\n", 
739                                                         "LDAP_RES_INTERMEDIATE", 
740                                                         si_tag == LDAP_TAG_SYNC_REFRESH_PRESENT ?
741                                                         "REFRESH_PRESENT" : "REFRESH_DELETE",
742                                                         "\n" );
743                                                 if ( si_tag == LDAP_TAG_SYNC_REFRESH_DELETE ) {
744                                                         si->si_refreshDelete = 1;
745                                                 } else {
746                                                         si->si_refreshPresent = 1;
747                                                 }
748                                                 ber_scanf( ber, "t{" /*"}"*/, &tag );
749                                                 if ( ber_peek_tag( ber, &len ) == LDAP_TAG_SYNC_COOKIE )
750                                                 {
751                                                         ber_scanf( ber, "m", &cookie );
752                                                         if ( !BER_BVISNULL( &cookie ) ) {
753                                                                 ch_free( syncCookie.octet_str.bv_val );
754                                                                 ber_dupbv( &syncCookie.octet_str, &cookie );
755                                                         }
756                                                         if ( !BER_BVISNULL( &syncCookie.octet_str ) )
757                                                         {
758                                                                 slap_parse_sync_cookie( &syncCookie, NULL );
759                                                         }
760                                                 }
761                                                 if ( ber_peek_tag( ber, &len ) ==
762                                                         LDAP_TAG_REFRESHDONE )
763                                                 {
764                                                         ber_scanf( ber, "b", &refreshDone );
765                                                 }
766                                                 ber_scanf( ber, /*"{"*/ "}" );
767                                                 break;
768                                         case LDAP_TAG_SYNC_ID_SET:
769                                                 Debug( LDAP_DEBUG_SYNC,
770                                                         "do_syncrep2: %s - %s%s\n", 
771                                                         "LDAP_RES_INTERMEDIATE", 
772                                                         "SYNC_ID_SET",
773                                                         "\n" );
774                                                 ber_scanf( ber, "t{" /*"}"*/, &tag );
775                                                 if ( ber_peek_tag( ber, &len ) ==
776                                                         LDAP_TAG_SYNC_COOKIE )
777                                                 {
778                                                         ber_scanf( ber, "m", &cookie );
779                                                         if ( !BER_BVISNULL( &cookie ) ) {
780                                                                 ch_free( syncCookie.octet_str.bv_val );
781                                                                 ber_dupbv( &syncCookie.octet_str, &cookie );
782                                                         }
783                                                         if ( !BER_BVISNULL( &syncCookie.octet_str ) )
784                                                         {
785                                                                 slap_parse_sync_cookie( &syncCookie, NULL );
786                                                         }
787                                                 }
788                                                 if ( ber_peek_tag( ber, &len ) ==
789                                                         LDAP_TAG_REFRESHDELETES )
790                                                 {
791                                                         ber_scanf( ber, "b", &refreshDeletes );
792                                                 }
793                                                 ber_scanf( ber, "[W]", &syncUUIDs );
794                                                 ber_scanf( ber, /*"{"*/ "}" );
795                                                 if ( refreshDeletes ) {
796                                                         syncrepl_del_nonpresent( op, si, syncUUIDs );
797                                                         ber_bvarray_free_x( syncUUIDs, op->o_tmpmemctx );
798                                                 } else {
799                                                         for ( i = 0; !BER_BVISNULL( &syncUUIDs[i] ); i++ ) {
800                                                                 struct berval *syncuuid_bv;
801                                                                 syncuuid_bv = ber_dupbv( NULL, &syncUUIDs[i] );
802                                                                 slap_sl_free( syncUUIDs[i].bv_val,op->o_tmpmemctx );
803                                                                 avl_insert( &si->si_presentlist,
804                                                                         (caddr_t) syncuuid_bv,
805                                                                         syncuuid_cmp, avl_dup_error );
806                                                         }
807                                                         slap_sl_free( syncUUIDs, op->o_tmpmemctx );
808                                                 }
809                                                 break;
810                                         default:
811                                                 Debug( LDAP_DEBUG_ANY,
812                                                         "do_syncrep2 : unknown syncinfo tag (%ld)\n",
813                                                 (long) si_tag, 0, 0 );
814                                                 ldap_memfree( retoid );
815                                                 ber_bvfree( retdata );
816                                                 continue;
817                                         }
818
819                                         if ( BER_BVISNULL( &syncCookie_req.ctxcsn )) {
820                                                 match = -1;
821                                         } else if ( BER_BVISNULL( &syncCookie.ctxcsn )) {
822                                                 match = 1;
823                                         } else {
824                                                 value_match( &match, slap_schema.si_ad_entryCSN,
825                                                         slap_schema.si_ad_entryCSN->ad_type->sat_ordering,
826                                                         SLAP_MR_VALUE_OF_ATTRIBUTE_SYNTAX,
827                                                         &syncCookie_req.ctxcsn,
828                                                         &syncCookie.ctxcsn, &text );
829                                         }
830
831                                         if ( !BER_BVISNULL( &syncCookie.ctxcsn ) &&
832                                                 match < 0 )
833                                         {
834                                                 syncrepl_updateCookie( si, op, psub, &syncCookie);
835                                         }
836
837                                         if ( si->si_refreshPresent == 1 ) {
838                                                 if ( match < 0 ) {
839                                                         syncrepl_del_nonpresent( op, si, NULL );
840                                                 }
841                                         } 
842
843                                         ldap_memfree( retoid );
844                                         ber_bvfree( retdata );
845                                         break;
846
847                                 } else {
848                                         Debug( LDAP_DEBUG_ANY, "do_syncrep2 : "
849                                                 "unknown intermediate response (%d)\n",
850                                                 rc, 0, 0 );
851                                         ldap_memfree( retoid );
852                                         ber_bvfree( retdata );
853                                         break;
854                                 }
855                                 break;
856
857                         default:
858                                 Debug( LDAP_DEBUG_ANY, "do_syncrep2 : "
859                                         "unknown message\n", 0, 0, 0 );
860                                 break;
861
862                         }
863                         if ( !BER_BVISNULL( &syncCookie.octet_str )) {
864                                 slap_sync_cookie_free( &syncCookie_req, 0 );
865                                 slap_dup_sync_cookie( &syncCookie_req, &syncCookie );
866                                 slap_sync_cookie_free( &syncCookie, 0 );
867                         }
868                 }
869                 ldap_msgfree( res );
870                 res = NULL;
871         }
872
873         if ( rc == -1 ) {
874                 const char *errstr;
875
876                 ldap_get_option( si->si_ld, LDAP_OPT_ERROR_NUMBER, &rc );
877                 errstr = ldap_err2string( rc );
878                 
879                 Debug( LDAP_DEBUG_ANY,
880                         "do_syncrep2 : %s\n", errstr, 0, 0 );
881         }
882
883 done:
884         slap_sync_cookie_free( &syncCookie, 0 );
885         slap_sync_cookie_free( &syncCookie_req, 0 );
886
887         if ( res ) ldap_msgfree( res );
888
889         if ( rc && si->si_ld ) {
890                 ldap_unbind_ext( si->si_ld, NULL, NULL );
891                 si->si_ld = NULL;
892         }
893
894         return rc;
895 }
896
897 static void *
898 do_syncrepl(
899         void    *ctx,
900         void    *arg )
901 {
902         struct re_s* rtask = arg;
903         syncinfo_t *si = ( syncinfo_t * ) rtask->arg;
904         Connection conn = {0};
905         char opbuf[OPERATION_BUFFER_SIZE];
906         Operation *op;
907         int rc = LDAP_SUCCESS;
908         int first = 0;
909         int dostop = 0;
910         ber_socket_t s;
911         int i, defer = 1;
912         Backend *be;
913
914         Debug( LDAP_DEBUG_TRACE, "=>do_syncrepl\n", 0, 0, 0 );
915
916         if ( si == NULL )
917                 return NULL;
918
919         ldap_pvt_thread_mutex_lock( &si->si_mutex );
920
921         switch( abs( si->si_type )) {
922         case LDAP_SYNC_REFRESH_ONLY:
923         case LDAP_SYNC_REFRESH_AND_PERSIST:
924                 break;
925         default:
926                 ldap_pvt_thread_mutex_unlock( &si->si_mutex );
927                 return NULL;
928         }
929
930         if ( slapd_shutdown ) {
931                 if ( si->si_ld ) {
932                         ldap_get_option( si->si_ld, LDAP_OPT_DESC, &s );
933                         connection_client_stop( s );
934                         ldap_unbind_ext( si->si_ld, NULL, NULL );
935                         si->si_ld = NULL;
936                 }
937                 ldap_pvt_thread_mutex_unlock( &si->si_mutex );
938                 return NULL;
939         }
940
941         op = (Operation *)opbuf;
942         connection_fake_init( &conn, op, ctx );
943
944         /* use global malloc for now */
945         op->o_tmpmemctx = NULL;
946         op->o_tmpmfuncs = &ch_mfuncs;
947
948         op->o_managedsait = SLAP_CONTROL_NONCRITICAL;
949         op->o_bd = be = si->si_be;
950         op->o_dn = op->o_bd->be_rootdn;
951         op->o_ndn = op->o_bd->be_rootndn;
952
953         /* Establish session, do search */
954         if ( !si->si_ld ) {
955                 first = 1;
956                 si->si_refreshDelete = 0;
957                 si->si_refreshPresent = 0;
958                 rc = do_syncrep1( op, si );
959         }
960
961         /* Process results */
962         if ( rc == LDAP_SUCCESS ) {
963                 ldap_get_option( si->si_ld, LDAP_OPT_DESC, &s );
964
965                 rc = do_syncrep2( op, si );
966
967                 if ( abs(si->si_type) == LDAP_SYNC_REFRESH_AND_PERSIST ) {
968                         /* If we succeeded, enable the connection for further listening.
969                          * If we failed, tear down the connection and reschedule.
970                          */
971                         if ( rc == LDAP_SUCCESS ) {
972                                 if ( first ) {
973                                         rc = connection_client_setup( s, do_syncrepl, arg );
974                                 } else {
975                                         connection_client_enable( s );
976                                 } 
977                         } else if ( !first ) {
978                                 dostop = 1;
979                         }
980                 } else {
981                         if ( rc == -2 ) rc = 0;
982                 }
983         }
984
985         /* At this point, we have 4 cases:
986          * 1) for any hard failure, give up and remove this task
987          * 2) for ServerDown, reschedule this task to run
988          * 3) for Refresh and Success, reschedule to run
989          * 4) for Persist and Success, reschedule to defer
990          */
991         ldap_pvt_thread_mutex_lock( &slapd_rq.rq_mutex );
992
993         if ( ldap_pvt_runqueue_isrunning( &slapd_rq, rtask )) {
994                 ldap_pvt_runqueue_stoptask( &slapd_rq, rtask );
995         }
996
997         if ( dostop ) {
998                 connection_client_stop( s );
999         }
1000
1001         if ( rc == LDAP_SUCCESS ) {
1002                 if ( si->si_type == LDAP_SYNC_REFRESH_ONLY ) {
1003                         defer = 0;
1004                 }
1005                 rtask->interval.tv_sec = si->si_interval;
1006                 ldap_pvt_runqueue_resched( &slapd_rq, rtask, defer );
1007                 if ( si->si_retrynum ) {
1008                         for ( i = 0; si->si_retrynum_init[i] != -2; i++ ) {
1009                                 si->si_retrynum[i] = si->si_retrynum_init[i];
1010                         }
1011                         si->si_retrynum[i] = -2;
1012                 }
1013         } else {
1014                 for ( i = 0; si->si_retrynum && si->si_retrynum[i] <= 0; i++ ) {
1015                         if ( si->si_retrynum[i] == -1  || si->si_retrynum[i] == -2 )
1016                                 break;
1017                 }
1018
1019                 if ( !si->si_retrynum || si->si_retrynum[i] == -2 ) {
1020                         ldap_pvt_runqueue_remove( &slapd_rq, rtask );
1021                 } else if ( si->si_retrynum[i] >= -1 ) {
1022                         if ( si->si_retrynum[i] > 0 )
1023                                 si->si_retrynum[i]--;
1024                         rtask->interval.tv_sec = si->si_retryinterval[i];
1025                         ldap_pvt_runqueue_resched( &slapd_rq, rtask, 0 );
1026                         slap_wake_listener();
1027                 }
1028         }
1029         
1030         ldap_pvt_thread_mutex_unlock( &slapd_rq.rq_mutex );
1031         ldap_pvt_thread_mutex_unlock( &si->si_mutex );
1032
1033         return NULL;
1034 }
1035
1036 typedef struct logschema {
1037         struct berval ls_dn;
1038         struct berval ls_req;
1039         struct berval ls_mod;
1040         struct berval ls_newRdn;
1041         struct berval ls_delRdn;
1042         struct berval ls_newSup;
1043 } logschema;
1044
1045 static logschema changelog_sc = {
1046         BER_BVC("targetDN"),
1047         BER_BVC("changeType"),
1048         BER_BVC("changes"),
1049         BER_BVC("newRDN"),
1050         BER_BVC("deleteOldRDN"),
1051         BER_BVC("newSuperior")
1052 };
1053
1054 static logschema accesslog_sc = {
1055         BER_BVC("reqDN"),
1056         BER_BVC("reqType"),
1057         BER_BVC("reqMod"),
1058         BER_BVC("reqNewRDN"),
1059         BER_BVC("reqDeleteOldRDN"),
1060         BER_BVC("reqNewSuperior")
1061 };
1062
1063 static slap_verbmasks modops[] = {
1064         { BER_BVC("add"), LDAP_REQ_ADD },
1065         { BER_BVC("delete"), LDAP_REQ_DELETE },
1066         { BER_BVC("modify"), LDAP_REQ_MODIFY },
1067         { BER_BVC("modrdn"), LDAP_REQ_MODRDN},
1068         { BER_BVNULL, 0 }
1069 };
1070
1071 static Modifications *
1072 syncrepl_accesslog_mods(
1073         syncinfo_t *si,
1074         struct berval *vals
1075 )
1076 {
1077         char *colon;
1078         const char *text;
1079         AttributeDescription *ad;
1080         struct berval bv, bv2;
1081         short op;
1082         Modifications *mod = NULL, *modlist = NULL, **modtail;
1083         int i;
1084
1085         modtail = &modlist;
1086
1087         for (i=0; !BER_BVISNULL( &vals[i] ); i++) {
1088                 ad = NULL;
1089                 bv = vals[i];
1090
1091                 colon = strchr( bv.bv_val, ':' );
1092                 if ( !colon )
1093                         continue;       /* invalid */
1094                 bv.bv_len = colon - bv.bv_val;
1095                 if ( slap_bv2ad( &bv, &ad, &text )) {
1096                         /* Invalid */
1097                         continue;
1098                 }
1099                 /* Ignore dynamically generated attrs */
1100                 if ( ad->ad_type->sat_flags & SLAP_AT_DYNAMIC )
1101                         continue;
1102                 /* Ignore excluded attrs */
1103                 if ( ldap_charray_inlist( si->si_exattrs,
1104                         ad->ad_type->sat_cname.bv_val ))
1105                         continue;
1106
1107                 switch(colon[1]) {
1108                 case '+':       op = LDAP_MOD_ADD; break;
1109                 case '-':       op = LDAP_MOD_DELETE; break;
1110                 case '=':       op = LDAP_MOD_REPLACE; break;
1111                 case '#':       op = LDAP_MOD_INCREMENT; break;
1112                 default:        continue;
1113                 }
1114
1115                 if ( !mod || ad != mod->sml_desc || op != mod->sml_op ) {
1116                         mod = (Modifications *) ch_malloc( sizeof( Modifications ));
1117                         mod->sml_flags = 0;
1118                         mod->sml_op = op;
1119                         mod->sml_next = NULL;
1120                         mod->sml_desc = ad;
1121                         mod->sml_type = ad->ad_cname;
1122                         mod->sml_values = NULL;
1123                         mod->sml_nvalues = NULL;
1124
1125                         *modtail = mod;
1126                         modtail = &mod->sml_next;
1127                 }
1128                 bv.bv_val = colon + 3;
1129                 bv.bv_len = vals[i].bv_len - ( bv.bv_val - vals[i].bv_val );
1130                 ber_dupbv( &bv2, &bv );
1131                 ber_bvarray_add( &mod->sml_values, &bv2 );
1132         }
1133         return modlist;
1134 }
1135
1136 static Modifications *
1137 syncrepl_changelog_mods(
1138         syncinfo_t *si,
1139         struct berval *vals
1140 )
1141 {
1142         return NULL;    /* FIXME */
1143 }
1144
1145 static int
1146 syncrepl_message_to_op(
1147         syncinfo_t      *si,
1148         Operation       *op,
1149         LDAPMessage     *msg
1150 )
1151 {
1152         BerElement      *ber = NULL;
1153         Modifications   *modlist = NULL;
1154         logschema *ls;
1155         SlapReply rs = { REP_RESULT };
1156         slap_callback cb = { NULL, null_callback, NULL, NULL };
1157
1158         const char      *text;
1159         char txtbuf[SLAP_TEXT_BUFLEN];
1160         size_t textlen = sizeof txtbuf;
1161
1162         struct berval   bdn, dn = BER_BVNULL, ndn;
1163         struct berval   bv, *bvals = NULL;
1164         struct berval   rdn = BER_BVNULL, sup = BER_BVNULL,
1165                 prdn = BER_BVNULL, nrdn = BER_BVNULL,
1166                 psup = BER_BVNULL, nsup = BER_BVNULL;
1167         int             rc, deleteOldRdn = 0;
1168
1169         if ( ldap_msgtype( msg ) != LDAP_RES_SEARCH_ENTRY ) {
1170                 Debug( LDAP_DEBUG_ANY,
1171                         "Message type should be entry (%d)", ldap_msgtype( msg ), 0, 0 );
1172                 return -1;
1173         }
1174
1175         if ( si->si_syncdata == SYNCDATA_ACCESSLOG )
1176                 ls = &accesslog_sc;
1177         else
1178                 ls = &changelog_sc;
1179
1180         rc = ldap_get_dn_ber( si->si_ld, msg, &ber, &bdn );
1181
1182         if ( rc != LDAP_SUCCESS ) {
1183                 Debug( LDAP_DEBUG_ANY,
1184                         "syncrepl_message_to_op : dn get failed (%d)", rc, 0, 0 );
1185                 return rc;
1186         }
1187
1188         op->o_tag = LBER_DEFAULT;
1189
1190         while (( rc = ldap_get_attribute_ber( si->si_ld, msg, ber, &bv, &bvals ))
1191                 == LDAP_SUCCESS ) {
1192                 if ( bv.bv_val == NULL )
1193                         break;
1194
1195                 if ( !ber_bvstrcasecmp( &bv, &ls->ls_dn )) {
1196                         bdn = bvals[0];
1197                         dnPrettyNormal( NULL, &bdn, &dn, &ndn, op->o_tmpmemctx );
1198                         ber_dupbv( &op->o_req_dn, &dn );
1199                         ber_dupbv( &op->o_req_ndn, &ndn );
1200                         slap_sl_free( ndn.bv_val, op->o_tmpmemctx );
1201                         slap_sl_free( dn.bv_val, op->o_tmpmemctx );
1202                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_req )) {
1203                         int i = verb_to_mask( bvals[0].bv_val, modops );
1204                         if ( i < 0 ) {
1205                                 Debug( LDAP_DEBUG_ANY,
1206                                         "syncrepl_message_to_op : unknown op %s",
1207                                         bvals[0].bv_val, 0, 0 );
1208                                 ch_free( bvals );
1209                                 rc = -1;
1210                                 goto done;
1211                         }
1212                         op->o_tag = modops[i].mask;
1213                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_mod )) {
1214                         /* Parse attribute into modlist */
1215                         if ( si->si_syncdata == SYNCDATA_ACCESSLOG )
1216                                 modlist = syncrepl_accesslog_mods( si, bvals );
1217                         else
1218                                 modlist = syncrepl_changelog_mods( si, bvals );
1219                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_newRdn )) {
1220                         rdn = bvals[0];
1221                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_delRdn )) {
1222                         if ( !ber_bvstrcasecmp( &slap_true_bv, bvals ))
1223                                 deleteOldRdn = 1;
1224                 } else if ( !ber_bvstrcasecmp( &bv, &ls->ls_newSup )) {
1225                         sup = bvals[0];
1226                 }
1227                 ch_free( bvals );
1228         }
1229
1230         /* If we didn't get a mod type or a target DN, bail out */
1231         if ( op->o_tag == LBER_DEFAULT || BER_BVISNULL( &dn )) {
1232                 rc = -1;
1233                 goto done;
1234         }
1235
1236         op->o_callback = &cb;
1237
1238         switch( op->o_tag ) {
1239         case LDAP_REQ_ADD:
1240         case LDAP_REQ_MODIFY:
1241                 /* If we didn't get required data, bail */
1242                 if ( !modlist ) goto done;
1243
1244                 rc = slap_mods_check( modlist, &text, txtbuf, textlen, NULL );
1245
1246                 if ( rc != LDAP_SUCCESS ) {
1247                         Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_op: mods check (%s)\n",
1248                                 text, 0, 0 );
1249                         goto done;
1250                 }
1251
1252                 if ( op->o_tag == LDAP_REQ_ADD ) {
1253                         op->ora_e = ( Entry * ) ch_calloc( 1, sizeof( Entry ) );
1254                         op->ora_e->e_name = op->o_req_dn;
1255                         op->ora_e->e_nname = op->o_req_ndn;
1256                         rc = slap_mods2entry( modlist, &op->ora_e, 1, 0, &text, txtbuf, textlen);
1257                         if( rc != LDAP_SUCCESS ) {
1258                                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_op: mods2entry (%s)\n",
1259                                         text, 0, 0 );
1260                         } else {
1261                                 rc = op->o_bd->be_add( op, &rs );
1262                         }
1263                         be_entry_release_w( op, op->ora_e );
1264                 } else {
1265                         op->orm_modlist = modlist;
1266                         rc = op->o_bd->be_modify( op, &rs );
1267                 }
1268                 break;
1269         case LDAP_REQ_MODRDN:
1270                 if ( BER_BVISNULL( &rdn )) goto done;
1271
1272                 if ( rdnPretty( NULL, &rdn, &prdn, NULL ))
1273                         goto done;
1274                 if ( rdnNormalize( 0, NULL, NULL, &rdn, &nrdn, NULL ))
1275                         goto done;
1276                 if ( !BER_BVISNULL( &sup )) {
1277                         if ( dnPrettyNormal( NULL, &sup, &psup, &nsup, NULL ))
1278                                 goto done;
1279                         op->orr_newSup = &psup;
1280                         op->orr_nnewSup = &nsup;
1281                 }
1282                 op->orr_newrdn = prdn;
1283                 op->orr_nnewrdn = nrdn;
1284                 op->orr_deleteoldrdn = deleteOldRdn;
1285                 rc = op->o_bd->be_modrdn( op, &rs );
1286                 break;
1287         }
1288 done:
1289         if ( modlist )
1290                 slap_mods_free( modlist, op->o_tag != LDAP_REQ_ADD );
1291         if ( !BER_BVISNULL( &rdn )) {
1292                 if ( !BER_BVISNULL( &nsup ))
1293                         ch_free( nsup.bv_val );
1294                 if ( !BER_BVISNULL( &psup ))
1295                         ch_free( psup.bv_val );
1296                 if ( !BER_BVISNULL( &nrdn ))
1297                         ch_free( nrdn.bv_val );
1298                 if ( !BER_BVISNULL( &prdn ))
1299                         ch_free( prdn.bv_val );
1300         }
1301         ber_free ( ber, 0 );
1302         return rc;
1303 }
1304
1305 static int
1306 syncrepl_message_to_entry(
1307         syncinfo_t      *si,
1308         Operation       *op,
1309         LDAPMessage     *msg,
1310         Modifications   **modlist,
1311         Entry                   **entry,
1312         int             syncstate
1313 )
1314 {
1315         Entry           *e = NULL;
1316         BerElement      *ber = NULL;
1317         Modifications   tmp;
1318         Modifications   *mod;
1319         Modifications   **modtail = modlist;
1320
1321         const char      *text;
1322         char txtbuf[SLAP_TEXT_BUFLEN];
1323         size_t textlen = sizeof txtbuf;
1324
1325         struct berval   bdn = {0, NULL}, dn, ndn;
1326         int             rc;
1327
1328         *modlist = NULL;
1329
1330         if ( ldap_msgtype( msg ) != LDAP_RES_SEARCH_ENTRY ) {
1331                 Debug( LDAP_DEBUG_ANY,
1332                         "Message type should be entry (%d)", ldap_msgtype( msg ), 0, 0 );
1333                 return -1;
1334         }
1335
1336         op->o_tag = LDAP_REQ_ADD;
1337
1338         rc = ldap_get_dn_ber( si->si_ld, msg, &ber, &bdn );
1339
1340         if ( rc != LDAP_SUCCESS ) {
1341                 Debug( LDAP_DEBUG_ANY,
1342                         "syncrepl_message_to_entry : dn get failed (%d)", rc, 0, 0 );
1343                 return rc;
1344         }
1345
1346         dnPrettyNormal( NULL, &bdn, &dn, &ndn, op->o_tmpmemctx );
1347         ber_dupbv( &op->o_req_dn, &dn );
1348         ber_dupbv( &op->o_req_ndn, &ndn );
1349         slap_sl_free( ndn.bv_val, op->o_tmpmemctx );
1350         slap_sl_free( dn.bv_val, op->o_tmpmemctx );
1351
1352         if ( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_DELETE ) {
1353                 if ( entry )
1354                         *entry = NULL;
1355                 return LDAP_SUCCESS;
1356         }
1357
1358         if ( entry == NULL ) {
1359                 return -1;
1360         }
1361
1362         e = ( Entry * ) ch_calloc( 1, sizeof( Entry ) );
1363         *entry = e;
1364         e->e_name = op->o_req_dn;
1365         e->e_nname = op->o_req_ndn;
1366
1367         while ( ber_remaining( ber ) ) {
1368                 if ( (ber_scanf( ber, "{mW}", &tmp.sml_type, &tmp.sml_values ) ==
1369                         LBER_ERROR ) || BER_BVISNULL( &tmp.sml_type ) )
1370                 {
1371                         break;
1372                 }
1373
1374                 mod  = (Modifications *) ch_malloc( sizeof( Modifications ));
1375
1376                 mod->sml_op = LDAP_MOD_REPLACE;
1377                 mod->sml_flags = 0;
1378                 mod->sml_next = NULL;
1379                 mod->sml_desc = NULL;
1380                 mod->sml_type = tmp.sml_type;
1381                 mod->sml_values = tmp.sml_values;
1382                 mod->sml_nvalues = NULL;
1383
1384                 *modtail = mod;
1385                 modtail = &mod->sml_next;
1386         }
1387
1388         if ( *modlist == NULL ) {
1389                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: no attributes\n",
1390                         0, 0, 0 );
1391                 rc = -1;
1392                 goto done;
1393         }
1394
1395         rc = slap_mods_check( *modlist, &text, txtbuf, textlen, NULL );
1396
1397         if ( rc != LDAP_SUCCESS ) {
1398                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: mods check (%s)\n",
1399                         text, 0, 0 );
1400                 goto done;
1401         }
1402
1403         /* Strip out dynamically generated attrs */
1404         for ( modtail = modlist; *modtail ; ) {
1405                 mod = *modtail;
1406                 if ( mod->sml_desc->ad_type->sat_flags & SLAP_AT_DYNAMIC ) {
1407                         *modtail = mod->sml_next;
1408                         slap_mod_free( &mod->sml_mod, 0 );
1409                         ch_free( mod );
1410                 } else {
1411                         modtail = &mod->sml_next;
1412                 }
1413         }
1414
1415         /* Strip out attrs in exattrs list */
1416         for ( modtail = modlist; *modtail ; ) {
1417                 mod = *modtail;
1418                 if ( ldap_charray_inlist( si->si_exattrs,
1419                                         mod->sml_desc->ad_type->sat_cname.bv_val )) {
1420                         *modtail = mod->sml_next;
1421                         slap_mod_free( &mod->sml_mod, 0 );
1422                         ch_free( mod );
1423                 } else {
1424                         modtail = &mod->sml_next;
1425                 }
1426         }
1427         
1428         rc = slap_mods2entry( *modlist, &e, 1, 1, &text, txtbuf, textlen);
1429         if( rc != LDAP_SUCCESS ) {
1430                 Debug( LDAP_DEBUG_ANY, "syncrepl_message_to_entry: mods2entry (%s)\n",
1431                         text, 0, 0 );
1432         }
1433
1434 done:
1435         ber_free ( ber, 0 );
1436         if ( rc != LDAP_SUCCESS ) {
1437                 if ( e ) {
1438                         entry_free( e );
1439                         *entry = e = NULL;
1440                 }
1441         }
1442
1443         return rc;
1444 }
1445
1446 static struct berval generic_filterstr = BER_BVC("(objectclass=*)");
1447
1448 /* During a refresh, we may get an LDAP_SYNC_ADD for an already existing
1449  * entry if a previous refresh was interrupted before sending us a new
1450  * context state. We try to compare the new entry to the existing entry
1451  * and ignore the new entry if they are the same.
1452  *
1453  * Also, we may get an update where the entryDN has changed, due to
1454  * a ModDn on the provider. We detect this as well, so we can issue
1455  * the corresponding operation locally.
1456  *
1457  * In the case of a modify, we get a list of all the attributes
1458  * in the original entry. Rather than deleting the entry and re-adding it,
1459  * we issue a Modify request that deletes all the attributes and adds all
1460  * the new ones. This avoids the issue of trying to delete/add a non-leaf
1461  * entry.
1462  *
1463  * We don't try to otherwise distinguish ModDN from Modify; in the case of
1464  * a ModDN we will issue both operations on the local database.
1465  */
1466 typedef struct dninfo {
1467         Entry *new_entry;
1468         struct berval dn;
1469         struct berval ndn;
1470         int renamed;    /* Was an existing entry renamed? */
1471         int wasChanged; /* are the attributes changed? */
1472         int attrs;              /* how many attribute types are in the ads list */
1473         AttributeDescription **ads;
1474 } dninfo;
1475
1476 static int
1477 syncrepl_entry(
1478         syncinfo_t* si,
1479         Operation *op,
1480         Entry* entry,
1481         Modifications** modlist,
1482         int syncstate,
1483         struct berval* syncUUID,
1484         struct sync_cookie* syncCookie_req,
1485         struct berval* syncCSN )
1486 {
1487         Backend *be = op->o_bd;
1488         slap_callback   cb = { NULL, NULL, NULL, NULL };
1489         struct berval   *syncuuid_bv = NULL;
1490         struct berval   syncUUID_strrep = BER_BVNULL;
1491         struct berval   uuid_bv = BER_BVNULL;
1492
1493         SlapReply       rs_search = {REP_RESULT};
1494         SlapReply       rs_delete = {REP_RESULT};
1495         SlapReply       rs_add = {REP_RESULT};
1496         SlapReply       rs_modify = {REP_RESULT};
1497         Filter f = {0};
1498 #ifdef LDAP_COMP_MATCH
1499         AttributeAssertion ava = { NULL, BER_BVNULL, NULL };
1500 #else
1501         AttributeAssertion ava = { NULL, BER_BVNULL };
1502 #endif
1503         int rc = LDAP_SUCCESS;
1504         int ret = LDAP_SUCCESS;
1505
1506         struct berval pdn = BER_BVNULL;
1507         dninfo dni = {0};
1508         int     retry = 1;
1509
1510         switch( syncstate ) {
1511         case LDAP_SYNC_PRESENT:
1512                 Debug( LDAP_DEBUG_SYNC, "%s: %s\n",
1513                                         "syncrepl_entry",
1514                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_PRESENT)", 0 );
1515                 break;
1516         case LDAP_SYNC_ADD:
1517                 Debug( LDAP_DEBUG_SYNC, "%s: %s\n",
1518                                         "syncrepl_entry",
1519                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_ADD)", 0 );
1520                 break;
1521         case LDAP_SYNC_DELETE:
1522                 Debug( LDAP_DEBUG_SYNC, "%s: %s\n",
1523                                         "syncrepl_entry",
1524                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_DELETE)", 0 );
1525                 break;
1526         case LDAP_SYNC_MODIFY:
1527                 Debug( LDAP_DEBUG_SYNC, "%s: %s\n",
1528                                         "syncrepl_entry",
1529                                         "LDAP_RES_SEARCH_ENTRY(LDAP_SYNC_MODIFY)", 0 );
1530                 break;
1531         default:
1532                 Debug( LDAP_DEBUG_ANY, "%s: %s\n",
1533                                         "syncrepl_entry",
1534                                         "LDAP_RES_SEARCH_ENTRY(UNKNOWN syncstate)", 0 );
1535         }
1536
1537         if (( syncstate == LDAP_SYNC_PRESENT || syncstate == LDAP_SYNC_ADD )) {
1538                 if ( !si->si_refreshPresent ) {
1539                         syncuuid_bv = ber_dupbv( NULL, syncUUID );
1540                         avl_insert( &si->si_presentlist, (caddr_t) syncuuid_bv,
1541                                 syncuuid_cmp, avl_dup_error );
1542                 }
1543         }
1544
1545         if ( syncstate == LDAP_SYNC_PRESENT ) {
1546                 return 0;
1547         } else if ( syncstate != LDAP_SYNC_DELETE ) {
1548                 if ( entry == NULL ) {
1549                         return 0;
1550                 }
1551         }
1552
1553         f.f_choice = LDAP_FILTER_EQUALITY;
1554         f.f_ava = &ava;
1555         ava.aa_desc = slap_schema.si_ad_entryUUID;
1556         (void)slap_uuidstr_from_normalized( &syncUUID_strrep, syncUUID, op->o_tmpmemctx );
1557         ava.aa_value = *syncUUID;
1558         op->ors_filter = &f;
1559
1560         op->ors_filterstr.bv_len = STRLENOF( "(entryUUID=)" ) + syncUUID->bv_len;
1561         op->ors_filterstr.bv_val = (char *) slap_sl_malloc(
1562                 op->ors_filterstr.bv_len + 1, op->o_tmpmemctx ); 
1563         AC_MEMCPY( op->ors_filterstr.bv_val, "(entryUUID=", STRLENOF( "(entryUUID=" ) );
1564         AC_MEMCPY( &op->ors_filterstr.bv_val[STRLENOF( "(entryUUID=" )],
1565                 syncUUID->bv_val, syncUUID->bv_len );
1566         op->ors_filterstr.bv_val[op->ors_filterstr.bv_len - 1] = ')';
1567         op->ors_filterstr.bv_val[op->ors_filterstr.bv_len] = '\0';
1568
1569         op->o_tag = LDAP_REQ_SEARCH;
1570         op->ors_scope = LDAP_SCOPE_SUBTREE;
1571         op->ors_deref = LDAP_DEREF_NEVER;
1572
1573         /* get the entry for this UUID */
1574         op->o_req_dn = si->si_base;
1575         op->o_req_ndn = si->si_base;
1576
1577         op->o_time = slap_get_time();
1578         op->ors_tlimit = SLAP_NO_LIMIT;
1579         op->ors_slimit = 1;
1580
1581         op->ors_attrs = slap_anlist_all_attributes;
1582         op->ors_attrsonly = 0;
1583
1584         /* set callback function */
1585         op->o_callback = &cb;
1586         cb.sc_response = dn_callback;
1587         cb.sc_private = &dni;
1588         dni.new_entry = entry;
1589
1590         if ( limits_check( op, &rs_search ) == 0 ) {
1591                 rc = be->be_search( op, &rs_search );
1592                 Debug( LDAP_DEBUG_SYNC,
1593                                 "syncrepl_entry: %s (%d)\n", 
1594                                 "be_search", rc, 0 );
1595         }
1596
1597         if ( !BER_BVISNULL( &op->ors_filterstr ) ) {
1598                 slap_sl_free( op->ors_filterstr.bv_val, op->o_tmpmemctx );
1599         }
1600
1601         cb.sc_response = null_callback;
1602         cb.sc_private = si;
1603
1604         if ( entry && !BER_BVISNULL( &entry->e_name ) ) {
1605                 Debug( LDAP_DEBUG_SYNC,
1606                                 "syncrepl_entry: %s\n",
1607                                 entry->e_name.bv_val, 0, 0 );
1608         } else {
1609                 Debug( LDAP_DEBUG_SYNC,
1610                                 "syncrepl_entry: %s\n",
1611                                 dni.dn.bv_val ? dni.dn.bv_val : "(null)", 0, 0 );
1612         }
1613
1614         if ( syncstate != LDAP_SYNC_DELETE ) {
1615                 Attribute       *a = attr_find( entry->e_attrs, slap_schema.si_ad_entryUUID );
1616
1617                 if ( a == NULL ) {
1618                         /* add if missing */
1619                         attr_merge_one( entry, slap_schema.si_ad_entryUUID,
1620                                 &syncUUID_strrep, syncUUID );
1621
1622                 } else if ( !bvmatch( &a->a_nvals[0], syncUUID ) ) {
1623                         /* replace only if necessary */
1624                         if ( a->a_nvals != a->a_vals ) {
1625                                 ber_memfree( a->a_nvals[0].bv_val );
1626                                 ber_dupbv( &a->a_nvals[0], syncUUID );
1627                         }
1628                         ber_memfree( a->a_vals[0].bv_val );
1629                         ber_dupbv( &a->a_vals[0], &syncUUID_strrep );
1630                 }
1631         }
1632
1633         switch ( syncstate ) {
1634         case LDAP_SYNC_ADD:
1635         case LDAP_SYNC_MODIFY:
1636 retry_add:;
1637                 if ( BER_BVISNULL( &dni.dn )) {
1638
1639                         op->o_req_dn = entry->e_name;
1640                         op->o_req_ndn = entry->e_nname;
1641                         op->o_tag = LDAP_REQ_ADD;
1642                         op->ora_e = entry;
1643
1644                         rc = be->be_add( op, &rs_add );
1645                         Debug( LDAP_DEBUG_SYNC,
1646                                         "syncrepl_entry: %s (%d)\n", 
1647                                         "be_add", rc, 0 );
1648                         switch ( rs_add.sr_err ) {
1649                         case LDAP_SUCCESS:
1650                                 be_entry_release_w( op, entry );
1651                                 ret = 0;
1652                                 break;
1653
1654                         case LDAP_REFERRAL:
1655                         /* we assume that LDAP_NO_SUCH_OBJECT is returned 
1656                          * only if the suffix entry is not present */
1657                         case LDAP_NO_SUCH_OBJECT:
1658                                 syncrepl_add_glue( op, entry );
1659                                 ret = 0;
1660                                 break;
1661
1662                         /* if an entry was added via syncrepl_add_glue(),
1663                          * it likely has no entryUUID, so the previous
1664                          * be_search() doesn't find it.  In this case,
1665                          * give syncrepl a chance to modify it. Also
1666                          * allow for entries that were recreated with the
1667                          * same DN but a different entryUUID.
1668                          */
1669                         case LDAP_ALREADY_EXISTS:
1670                                 if ( retry ) {
1671                                         Operation       op2 = *op;
1672                                         SlapReply       rs2 = { 0 };
1673                                         slap_callback   cb2 = { 0 };
1674
1675                                         op2.o_tag = LDAP_REQ_SEARCH;
1676                                         op2.o_req_dn = entry->e_name;
1677                                         op2.o_req_ndn = entry->e_nname;
1678                                         op2.ors_scope = LDAP_SCOPE_BASE;
1679                                         op2.ors_deref = LDAP_DEREF_NEVER;
1680                                         op2.ors_attrs = slap_anlist_all_attributes;
1681                                         op2.ors_attrsonly = 0;
1682                                         op2.ors_limit = NULL;
1683                                         op2.ors_slimit = 1;
1684                                         op2.ors_tlimit = SLAP_NO_LIMIT;
1685
1686                                         f.f_choice = LDAP_FILTER_PRESENT;
1687                                         f.f_desc = slap_schema.si_ad_objectClass;
1688                                         op2.ors_filter = &f;
1689                                         op2.ors_filterstr = generic_filterstr;
1690
1691                                         op2.o_callback = &cb2;
1692                                         cb2.sc_response = dn_callback;
1693                                         cb2.sc_private = &dni;
1694
1695                                         be->be_search( &op2, &rs2 );
1696
1697                                         retry = 0;
1698                                         goto retry_add;
1699                                 }
1700                                 /* FALLTHRU */
1701
1702                         default:
1703                                 Debug( LDAP_DEBUG_ANY,
1704                                         "syncrepl_entry : be_add failed (%d)\n",
1705                                         rs_add.sr_err, 0, 0 );
1706                                 ret = 1;
1707                                 break;
1708                         }
1709                         goto done;
1710                 }
1711                 /* FALLTHRU */
1712                 op->o_req_dn = dni.dn;
1713                 op->o_req_ndn = dni.ndn;
1714                 if ( dni.renamed ) {
1715                         struct berval noldp, newp, nnewp;
1716
1717                         op->o_tag = LDAP_REQ_MODRDN;
1718                         dnRdn( &entry->e_name, &op->orr_newrdn );
1719                         dnRdn( &entry->e_nname, &op->orr_nnewrdn );
1720
1721                         dnParent( &dni.ndn, &noldp );
1722                         dnParent( &entry->e_nname, &nnewp );
1723                         if ( !dn_match( &noldp, &newp )) {
1724                                 dnParent( &entry->e_name, &newp );
1725                                 op->orr_newSup = &newp;
1726                                 op->orr_nnewSup = &nnewp;
1727                         }
1728                         op->orr_deleteoldrdn = 0;
1729                         rc = be->be_modrdn( op, &rs_modify );
1730                         Debug( LDAP_DEBUG_SYNC,
1731                                         "syncrepl_entry: %s (%d)\n", 
1732                                         "be_modrdn", rc, 0 );
1733                         if ( rs_modify.sr_err == LDAP_SUCCESS ) {
1734                                 op->o_req_dn = entry->e_name;
1735                                 op->o_req_ndn = entry->e_nname;
1736                         } else {
1737                                 ret = 1;
1738                                 goto done;
1739                         }
1740                 }
1741                 if ( dni.wasChanged ) {
1742                         Modifications *mod, *modhead = NULL;
1743                         Modifications *modtail = NULL;
1744                         int i;
1745
1746                         op->o_tag = LDAP_REQ_MODIFY;
1747
1748                         assert( *modlist != NULL );
1749
1750                         /* Delete all the old attrs */
1751                         for ( i = 0; i < dni.attrs; i++ ) {
1752                                 mod = ch_malloc( sizeof( Modifications ) );
1753                                 mod->sml_op = LDAP_MOD_DELETE;
1754                                 mod->sml_flags = 0;
1755                                 mod->sml_desc = dni.ads[i];
1756                                 mod->sml_type = mod->sml_desc->ad_cname;
1757                                 mod->sml_values = NULL;
1758                                 mod->sml_nvalues = NULL;
1759                                 if ( !modhead ) modhead = mod;
1760                                 if ( modtail ) {
1761                                         modtail->sml_next = mod;
1762                                 }
1763                                 modtail = mod;
1764                         }
1765
1766                         /* Append passed in list to ours */
1767                         if ( modtail ) {
1768                                 modtail->sml_next = *modlist;
1769                                 *modlist = modhead;
1770                         } else {
1771                                 mod = *modlist;
1772                         }
1773
1774                         /* Find end of this list */
1775                         for ( ; mod != NULL; mod = mod->sml_next ) {
1776                                 modtail = mod;
1777                         }
1778
1779                         mod = (Modifications *)ch_calloc(1, sizeof(Modifications));
1780                         mod->sml_op = LDAP_MOD_REPLACE;
1781                         mod->sml_flags = 0;
1782                         mod->sml_desc = slap_schema.si_ad_entryUUID;
1783                         mod->sml_type = mod->sml_desc->ad_cname;
1784                         ber_dupbv( &uuid_bv, &syncUUID_strrep );
1785                         ber_bvarray_add( &mod->sml_values, &uuid_bv );
1786                         ber_dupbv( &uuid_bv, syncUUID );
1787                         ber_bvarray_add( &mod->sml_nvalues, &uuid_bv );
1788                         modtail->sml_next = mod;
1789                                         
1790                         op->o_tag = LDAP_REQ_MODIFY;
1791                         op->orm_modlist = *modlist;
1792
1793                         rc = be->be_modify( op, &rs_modify );
1794                         Debug( LDAP_DEBUG_SYNC,
1795                                         "syncrepl_entry: %s (%d)\n", 
1796                                         "be_modify", rc, 0 );
1797                         if ( rs_modify.sr_err != LDAP_SUCCESS ) {
1798                                 Debug( LDAP_DEBUG_ANY,
1799                                         "syncrepl_entry : be_modify failed (%d)\n",
1800                                         rs_modify.sr_err, 0, 0 );
1801                         }
1802                 }
1803                 ret = 1;
1804                 goto done;
1805         case LDAP_SYNC_DELETE :
1806                 if ( !BER_BVISNULL( &dni.dn )) {
1807                         op->o_req_dn = dni.dn;
1808                         op->o_req_ndn = dni.ndn;
1809                         op->o_tag = LDAP_REQ_DELETE;
1810                         rc = be->be_delete( op, &rs_delete );
1811                         Debug( LDAP_DEBUG_SYNC,
1812                                         "syncrepl_entry: %s (%d)\n", 
1813                                         "be_delete", rc, 0 );
1814
1815                         while ( rs_delete.sr_err == LDAP_SUCCESS
1816                                 && op->o_delete_glue_parent ) {
1817                                 op->o_delete_glue_parent = 0;
1818                                 if ( !be_issuffix( op->o_bd, &op->o_req_ndn )) {
1819                                         slap_callback cb = { NULL };
1820                                         cb.sc_response = slap_null_cb;
1821                                         dnParent( &op->o_req_ndn, &pdn );
1822                                         op->o_req_dn = pdn;
1823                                         op->o_req_ndn = pdn;
1824                                         op->o_callback = &cb;
1825                                         op->o_bd->be_delete( op, &rs_delete );
1826                                 } else {
1827                                         break;
1828                                 }
1829                         }
1830                 }
1831                 ret = 0;
1832                 goto done;
1833
1834         default :
1835                 Debug( LDAP_DEBUG_ANY,
1836                         "syncrepl_entry : unknown syncstate\n", 0, 0, 0 );
1837                 ret = 1;
1838                 goto done;
1839         }
1840
1841 done :
1842         if ( !BER_BVISNULL( &syncUUID_strrep ) ) {
1843                 slap_sl_free( syncUUID_strrep.bv_val, op->o_tmpmemctx );
1844                 BER_BVZERO( &syncUUID_strrep );
1845         }
1846         if ( dni.ads ) {
1847                 op->o_tmpfree( dni.ads, op->o_tmpmemctx );
1848         }
1849         if ( !BER_BVISNULL( &dni.ndn ) ) {
1850                 op->o_tmpfree( dni.ndn.bv_val, op->o_tmpmemctx );
1851         }
1852         if ( !BER_BVISNULL( &dni.dn ) ) {
1853                 op->o_tmpfree( dni.dn.bv_val, op->o_tmpmemctx );
1854         }
1855         return ret;
1856 }
1857
1858 static struct berval gcbva[] = {
1859         BER_BVC("top"),
1860         BER_BVC("glue"),
1861         BER_BVNULL
1862 };
1863
1864 #define NP_DELETE_ONE   2
1865
1866 static void
1867 syncrepl_del_nonpresent(
1868         Operation *op,
1869         syncinfo_t *si,
1870         BerVarray uuids )
1871 {
1872         Backend* be = op->o_bd;
1873         slap_callback   cb = { NULL };
1874         SlapReply       rs_search = {REP_RESULT};
1875         SlapReply       rs_delete = {REP_RESULT};
1876         SlapReply       rs_modify = {REP_RESULT};
1877         struct nonpresent_entry *np_list, *np_prev;
1878         int rc;
1879         AttributeName   an[2];
1880
1881         struct berval pdn = BER_BVNULL;
1882
1883         op->o_req_dn = si->si_base;
1884         op->o_req_ndn = si->si_base;
1885
1886         cb.sc_response = nonpresent_callback;
1887         cb.sc_private = si;
1888
1889         op->o_callback = &cb;
1890         op->o_tag = LDAP_REQ_SEARCH;
1891         op->ors_scope = si->si_scope;
1892         op->ors_deref = LDAP_DEREF_NEVER;
1893         op->o_time = slap_get_time();
1894         op->ors_tlimit = SLAP_NO_LIMIT;
1895
1896
1897         if ( uuids ) {
1898                 Filter uf;
1899 #ifdef LDAP_COMP_MATCH
1900                 AttributeAssertion eq = { NULL, BER_BVNULL, NULL };
1901 #else
1902                 AttributeAssertion eq = { NULL, BER_BVNULL };
1903 #endif
1904                 int i;
1905
1906                 op->ors_attrsonly = 1;
1907                 op->ors_attrs = slap_anlist_no_attrs;
1908                 op->ors_limit = NULL;
1909                 op->ors_filter = &uf;
1910
1911                 uf.f_ava = &eq;
1912                 uf.f_av_desc = slap_schema.si_ad_entryUUID;
1913                 uf.f_next = NULL;
1914                 uf.f_choice = LDAP_FILTER_EQUALITY;
1915                 si->si_refreshDelete |= NP_DELETE_ONE;
1916
1917                 for (i=0; uuids[i].bv_val; i++) {
1918                         op->ors_slimit = 1;
1919                         uf.f_av_value = uuids[i];
1920                         rc = be->be_search( op, &rs_search );
1921                 }
1922                 si->si_refreshDelete ^= NP_DELETE_ONE;
1923         } else {
1924                 memset( &an[0], 0, 2 * sizeof( AttributeName ) );
1925                 an[0].an_name = slap_schema.si_ad_entryUUID->ad_cname;
1926                 an[0].an_desc = slap_schema.si_ad_entryUUID;
1927                 op->ors_attrs = an;
1928                 op->ors_slimit = SLAP_NO_LIMIT;
1929                 op->ors_attrsonly = 0;
1930                 op->ors_filter = str2filter_x( op, si->si_filterstr.bv_val );
1931                 op->ors_filterstr = si->si_filterstr;
1932                 op->o_nocaching = 1;
1933
1934                 if ( limits_check( op, &rs_search ) == 0 ) {
1935                         rc = be->be_search( op, &rs_search );
1936                 }
1937                 if ( op->ors_filter ) filter_free_x( op, op->ors_filter );
1938         }
1939
1940         op->o_nocaching = 0;
1941
1942         if ( !LDAP_LIST_EMPTY( &si->si_nonpresentlist ) ) {
1943
1944                 slap_queue_csn( op, &si->si_syncCookie.ctxcsn );
1945
1946                 np_list = LDAP_LIST_FIRST( &si->si_nonpresentlist );
1947                 while ( np_list != NULL ) {
1948                         LDAP_LIST_REMOVE( np_list, npe_link );
1949                         np_prev = np_list;
1950                         np_list = LDAP_LIST_NEXT( np_list, npe_link );
1951                         op->o_tag = LDAP_REQ_DELETE;
1952                         op->o_callback = &cb;
1953                         cb.sc_response = null_callback;
1954                         cb.sc_private = si;
1955                         op->o_req_dn = *np_prev->npe_name;
1956                         op->o_req_ndn = *np_prev->npe_nname;
1957                         rc = op->o_bd->be_delete( op, &rs_delete );
1958
1959                         if ( rs_delete.sr_err == LDAP_NOT_ALLOWED_ON_NONLEAF ) {
1960                                 Modifications mod1, mod2;
1961                                 mod1.sml_op = LDAP_MOD_REPLACE;
1962                                 mod1.sml_flags = 0;
1963                                 mod1.sml_desc = slap_schema.si_ad_objectClass;
1964                                 mod1.sml_type = mod1.sml_desc->ad_cname;
1965                                 mod1.sml_values = &gcbva[0];
1966                                 mod1.sml_nvalues = NULL;
1967                                 mod1.sml_next = &mod2;
1968
1969                                 mod2.sml_op = LDAP_MOD_REPLACE;
1970                                 mod2.sml_flags = 0;
1971                                 mod2.sml_desc = slap_schema.si_ad_structuralObjectClass;
1972                                 mod2.sml_type = mod2.sml_desc->ad_cname;
1973                                 mod2.sml_values = &gcbva[1];
1974                                 mod2.sml_nvalues = NULL;
1975                                 mod2.sml_next = NULL;
1976
1977                                 op->o_tag = LDAP_REQ_MODIFY;
1978                                 op->orm_modlist = &mod1;
1979
1980                                 rc = be->be_modify( op, &rs_modify );
1981                         }
1982
1983                         while ( rs_delete.sr_err == LDAP_SUCCESS &&
1984                                         op->o_delete_glue_parent ) {
1985                                 op->o_delete_glue_parent = 0;
1986                                 if ( !be_issuffix( op->o_bd, &op->o_req_ndn )) {
1987                                         slap_callback cb = { NULL };
1988                                         cb.sc_response = slap_null_cb;
1989                                         dnParent( &op->o_req_ndn, &pdn );
1990                                         op->o_req_dn = pdn;
1991                                         op->o_req_ndn = pdn;
1992                                         op->o_callback = &cb;
1993                                         /* give it a root privil ? */
1994                                         op->o_bd->be_delete( op, &rs_delete );
1995                                 } else {
1996                                         break;
1997                             }
1998                         }
1999
2000                         op->o_delete_glue_parent = 0;
2001
2002                         ber_bvfree( np_prev->npe_name );
2003                         ber_bvfree( np_prev->npe_nname );
2004                         ch_free( np_prev );
2005                 }
2006
2007                 slap_graduate_commit_csn( op );
2008         }
2009
2010         return;
2011 }
2012
2013 void
2014 syncrepl_add_glue(
2015         Operation* op,
2016         Entry *e )
2017 {
2018         Backend *be = op->o_bd;
2019         slap_callback cb = { NULL };
2020         Attribute       *a;
2021         int     rc;
2022         int suffrdns;
2023         int i;
2024         struct berval dn = {0, NULL};
2025         struct berval ndn = {0, NULL};
2026         Entry   *glue;
2027         SlapReply       rs_add = {REP_RESULT};
2028         char    *ptr, *comma;
2029
2030         op->o_tag = LDAP_REQ_ADD;
2031         op->o_callback = &cb;
2032         cb.sc_response = null_callback;
2033         cb.sc_private = NULL;
2034
2035         dn = e->e_name;
2036         ndn = e->e_nname;
2037
2038         /* count RDNs in suffix */
2039         if ( !BER_BVISEMPTY( &be->be_nsuffix[0] ) ) {
2040                 for ( i = 0, ptr = be->be_nsuffix[0].bv_val; ptr; ptr = strchr( ptr, ',' ) ) {
2041                         ptr++;
2042                         i++;
2043                 }
2044                 suffrdns = i;
2045         } else {
2046                 /* suffix is "" */
2047                 suffrdns = 0;
2048         }
2049
2050         /* Start with BE suffix */
2051         for ( i = 0, ptr = NULL; i < suffrdns; i++ ) {
2052                 comma = strrchr( dn.bv_val, ',' );
2053                 if ( ptr ) *ptr = ',';
2054                 if ( comma ) *comma = '\0';
2055                 ptr = comma;
2056         }
2057         if ( ptr ) {
2058                 *ptr++ = ',';
2059                 dn.bv_len -= ptr - dn.bv_val;
2060                 dn.bv_val = ptr;
2061         }
2062         /* the normalizedDNs are always the same length, no counting
2063          * required.
2064          */
2065         if ( ndn.bv_len > be->be_nsuffix[0].bv_len ) {
2066                 ndn.bv_val += ndn.bv_len - be->be_nsuffix[0].bv_len;
2067                 ndn.bv_len = be->be_nsuffix[0].bv_len;
2068         }
2069
2070         while ( ndn.bv_val > e->e_nname.bv_val ) {
2071                 glue = (Entry *) ch_calloc( 1, sizeof(Entry) );
2072                 ber_dupbv( &glue->e_name, &dn );
2073                 ber_dupbv( &glue->e_nname, &ndn );
2074
2075                 a = ch_calloc( 1, sizeof( Attribute ));
2076                 a->a_desc = slap_schema.si_ad_objectClass;
2077
2078                 a->a_vals = ch_calloc( 3, sizeof( struct berval ));
2079                 ber_dupbv( &a->a_vals[0], &gcbva[0] );
2080                 ber_dupbv( &a->a_vals[1], &gcbva[1] );
2081                 ber_dupbv( &a->a_vals[2], &gcbva[2] );
2082
2083                 a->a_nvals = a->a_vals;
2084
2085                 a->a_next = glue->e_attrs;
2086                 glue->e_attrs = a;
2087
2088                 a = ch_calloc( 1, sizeof( Attribute ));
2089                 a->a_desc = slap_schema.si_ad_structuralObjectClass;
2090
2091                 a->a_vals = ch_calloc( 2, sizeof( struct berval ));
2092                 ber_dupbv( &a->a_vals[0], &gcbva[1] );
2093                 ber_dupbv( &a->a_vals[1], &gcbva[2] );
2094
2095                 a->a_nvals = a->a_vals;
2096
2097                 a->a_next = glue->e_attrs;
2098                 glue->e_attrs = a;
2099
2100                 op->o_req_dn = glue->e_name;
2101                 op->o_req_ndn = glue->e_nname;
2102                 op->ora_e = glue;
2103                 rc = be->be_add ( op, &rs_add );
2104                 if ( rs_add.sr_err == LDAP_SUCCESS ) {
2105                         be_entry_release_w( op, glue );
2106                 } else {
2107                 /* incl. ALREADY EXIST */
2108                         entry_free( glue );
2109                 }
2110
2111                 /* Move to next child */
2112                 for (ptr = dn.bv_val-2; ptr > e->e_name.bv_val && *ptr != ','; ptr--) {
2113                         /* empty */
2114                 }
2115                 if ( ptr == e->e_name.bv_val ) break;
2116                 dn.bv_val = ++ptr;
2117                 dn.bv_len = e->e_name.bv_len - (ptr-e->e_name.bv_val);
2118                 for( ptr = ndn.bv_val-2;
2119                         ptr > e->e_nname.bv_val && *ptr != ',';
2120                         ptr--)
2121                 {
2122                         /* empty */
2123                 }
2124                 ndn.bv_val = ++ptr;
2125                 ndn.bv_len = e->e_nname.bv_len - (ptr-e->e_nname.bv_val);
2126         }
2127
2128         op->o_req_dn = e->e_name;
2129         op->o_req_ndn = e->e_nname;
2130         op->ora_e = e;
2131         rc = be->be_add ( op, &rs_add );
2132         if ( rs_add.sr_err == LDAP_SUCCESS ) {
2133                 be_entry_release_w( op, e );
2134         } else {
2135                 entry_free( e );
2136         }
2137
2138         return;
2139 }
2140
2141 static void
2142 syncrepl_updateCookie(
2143         syncinfo_t *si,
2144         Operation *op,
2145         struct berval *pdn,
2146         struct sync_cookie *syncCookie )
2147 {
2148         Backend *be = op->o_bd;
2149         Modifications mod = { { 0 } };
2150         struct berval vals[ 2 ];
2151
2152         int rc;
2153
2154         slap_callback cb = { NULL };
2155         SlapReply       rs_modify = {REP_RESULT};
2156
2157         slap_sync_cookie_free( &si->si_syncCookie, 0 );
2158         slap_dup_sync_cookie( &si->si_syncCookie, syncCookie );
2159
2160         mod.sml_op = LDAP_MOD_REPLACE;
2161         mod.sml_desc = slap_schema.si_ad_contextCSN;
2162         mod.sml_type = mod.sml_desc->ad_cname;
2163         mod.sml_values = vals;
2164         vals[0] = si->si_syncCookie.ctxcsn;
2165         vals[1].bv_val = NULL;
2166         vals[1].bv_len = 0;
2167
2168         slap_queue_csn( op, &si->si_syncCookie.ctxcsn );
2169
2170         op->o_tag = LDAP_REQ_MODIFY;
2171
2172         assert( si->si_rid < 1000 );
2173
2174         cb.sc_response = null_callback;
2175         cb.sc_private = si;
2176
2177         op->o_callback = &cb;
2178         op->o_req_dn = op->o_bd->be_suffix[0];
2179         op->o_req_ndn = op->o_bd->be_nsuffix[0];
2180
2181         /* update contextCSN */
2182         op->o_msgid = SLAP_SYNC_UPDATE_MSGID;
2183         op->orm_modlist = &mod;
2184         rc = be->be_modify( op, &rs_modify );
2185         op->o_msgid = 0;
2186
2187         if ( rs_modify.sr_err != LDAP_SUCCESS ) {
2188                 Debug( LDAP_DEBUG_ANY,
2189                         "be_modify failed (%d)\n", rs_modify.sr_err, 0, 0 );
2190         }
2191
2192         slap_graduate_commit_csn( op );
2193
2194         return;
2195 }
2196
2197 static int
2198 dn_callback(
2199         Operation*      op,
2200         SlapReply*      rs )
2201 {
2202         dninfo *dni = op->o_callback->sc_private;
2203
2204         if ( rs->sr_type == REP_SEARCH ) {
2205                 if ( !BER_BVISNULL( &dni->dn ) ) {
2206                         Debug( LDAP_DEBUG_ANY,
2207                                 "dn_callback : consistency error - "
2208                                 "entryUUID is not unique\n", 0, 0, 0 );
2209                 } else {
2210                         ber_dupbv_x( &dni->dn, &rs->sr_entry->e_name, op->o_tmpmemctx );
2211                         ber_dupbv_x( &dni->ndn, &rs->sr_entry->e_nname, op->o_tmpmemctx );
2212                         /* If there is a new entry, see if it differs from the old.
2213                          * We compare the non-normalized values so that cosmetic changes
2214                          * in the provider are always propagated.
2215                          */
2216                         if ( dni->new_entry ) {
2217                                 Attribute *old, *new;
2218                                 int i;
2219
2220                                 /* Did the DN change? Note that we don't explicitly try to
2221                                  * discover if the deleteOldRdn argument applies here. It
2222                                  * would save an unnecessary Modify if we detected it, but
2223                                  * that's a fair amount of trouble to compare the two attr
2224                                  * lists in detail. (Just test normalized DN; we ignore
2225                                  * insignificant changes here.)
2226                                  */
2227                                 if ( !dn_match( &rs->sr_entry->e_nname,
2228                                                 &dni->new_entry->e_nname ) )
2229                                 {
2230                                         dni->renamed = 1;
2231                                 }
2232
2233                                 for ( i = 0, old = rs->sr_entry->e_attrs;
2234                                                 old;
2235                                                 i++, old = old->a_next )
2236                                         ;
2237
2238                                 dni->attrs = i;
2239
2240                                 /* We assume that attributes are saved in the same order
2241                                  * in the remote and local databases. So if we walk through
2242                                  * the attributeDescriptions one by one they should match in
2243                                  * lock step. If not, we signal a change. Otherwise we test
2244                                  * all the values...
2245                                  */
2246                                 for ( old = rs->sr_entry->e_attrs, new = dni->new_entry->e_attrs;
2247                                                 old && new;
2248                                                 old = old->a_next, new = new->a_next )
2249                                 {
2250                                         if ( old->a_desc != new->a_desc ) {
2251                                                 dni->wasChanged = 1;
2252                                                 break;
2253                                         }
2254                                         for ( i = 0; ; i++ ) {
2255                                                 int nold, nnew;
2256                                                 nold = BER_BVISNULL( &old->a_vals[i] );
2257                                                 nnew = BER_BVISNULL( &new->a_vals[i] );
2258                                                 /* If both are empty, stop looking */
2259                                                 if ( nold && nnew ) {
2260                                                         break;
2261                                                 }
2262                                                 /* If they are different, stop looking */
2263                                                 if ( nold != nnew ) {
2264                                                         dni->wasChanged = 1;
2265                                                         break;
2266                                                 }
2267                                                 if ( ber_bvcmp( &old->a_vals[i], &new->a_vals[i] )) {
2268                                                         dni->wasChanged = 1;
2269                                                         break;
2270                                                 }
2271                                         }
2272                                         if ( dni->wasChanged ) break;
2273                                 }
2274                                 if ( dni->wasChanged ) {
2275                                         dni->ads = op->o_tmpalloc( dni->attrs *
2276                                                 sizeof(AttributeDescription *), op->o_tmpmemctx );
2277                                         i = 0;
2278                                         for ( old = rs->sr_entry->e_attrs; old; old = old->a_next ) {
2279                                                 dni->ads[i] = old->a_desc;
2280                                                 i++;
2281                                         }
2282                                 }
2283                         }
2284                 }
2285         } else if ( rs->sr_type == REP_RESULT ) {
2286                 if ( rs->sr_err == LDAP_SIZELIMIT_EXCEEDED ) {
2287                         Debug( LDAP_DEBUG_ANY,
2288                                 "dn_callback : consistency error - "
2289                                 "entryUUID is not unique\n", 0, 0, 0 );
2290                 }
2291         }
2292
2293         return LDAP_SUCCESS;
2294 }
2295
2296 static int
2297 nonpresent_callback(
2298         Operation*      op,
2299         SlapReply*      rs )
2300 {
2301         syncinfo_t *si = op->o_callback->sc_private;
2302         Attribute *a;
2303         int count = 0;
2304         struct berval* present_uuid = NULL;
2305         struct nonpresent_entry *np_entry;
2306
2307         if ( rs->sr_type == REP_RESULT ) {
2308                 count = avl_free( si->si_presentlist, avl_ber_bvfree );
2309                 si->si_presentlist = NULL;
2310
2311         } else if ( rs->sr_type == REP_SEARCH ) {
2312                 if ( !(si->si_refreshDelete & NP_DELETE_ONE )) {
2313                         a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_entryUUID );
2314
2315                         if ( a == NULL ) return 0;
2316
2317                         present_uuid = avl_find( si->si_presentlist, &a->a_nvals[0],
2318                                 syncuuid_cmp );
2319                 }
2320
2321                 if ( present_uuid == NULL ) {
2322                         np_entry = (struct nonpresent_entry *)
2323                                 ch_calloc( 1, sizeof( struct nonpresent_entry ));
2324                         np_entry->npe_name = ber_dupbv( NULL, &rs->sr_entry->e_name );
2325                         np_entry->npe_nname = ber_dupbv( NULL, &rs->sr_entry->e_nname );
2326                         LDAP_LIST_INSERT_HEAD( &si->si_nonpresentlist, np_entry, npe_link );
2327
2328                 } else {
2329                         avl_delete( &si->si_presentlist,
2330                                         &a->a_nvals[0], syncuuid_cmp );
2331                         ch_free( present_uuid->bv_val );
2332                         ch_free( present_uuid );
2333                 }
2334         }
2335         return LDAP_SUCCESS;
2336 }
2337
2338 static int
2339 null_callback(
2340         Operation*      op,
2341         SlapReply*      rs )
2342 {
2343         if ( rs->sr_err != LDAP_SUCCESS &&
2344                 rs->sr_err != LDAP_REFERRAL &&
2345                 rs->sr_err != LDAP_ALREADY_EXISTS &&
2346                 rs->sr_err != LDAP_NO_SUCH_OBJECT &&
2347                 rs->sr_err != LDAP_NOT_ALLOWED_ON_NONLEAF )
2348         {
2349                 Debug( LDAP_DEBUG_ANY,
2350                         "null_callback : error code 0x%x\n",
2351                         rs->sr_err, 0, 0 );
2352         }
2353         return LDAP_SUCCESS;
2354 }
2355
2356 static struct berval *
2357 slap_uuidstr_from_normalized(
2358         struct berval* uuidstr,
2359         struct berval* normalized,
2360         void *ctx )
2361 {
2362         struct berval *new;
2363         unsigned char nibble;
2364         int i, d = 0;
2365
2366         if ( normalized == NULL ) return NULL;
2367         if ( normalized->bv_len != 16 ) return NULL;
2368
2369         if ( uuidstr ) {
2370                 new = uuidstr;
2371         } else {
2372                 new = (struct berval *)slap_sl_malloc( sizeof(struct berval), ctx );
2373                 if ( new == NULL ) {
2374                         return NULL;
2375                 }
2376         }
2377
2378         new->bv_len = 36;
2379
2380         if ( ( new->bv_val = slap_sl_malloc( new->bv_len + 1, ctx ) ) == NULL ) {
2381                 if ( new != uuidstr ) {
2382                         slap_sl_free( new, ctx );
2383                 }
2384                 return NULL;
2385         }
2386
2387         for ( i = 0; i < 16; i++ ) {
2388                 if ( i == 4 || i == 6 || i == 8 || i == 10 ) {
2389                         new->bv_val[(i<<1)+d] = '-';
2390                         d += 1;
2391                 }
2392
2393                 nibble = (normalized->bv_val[i] >> 4) & 0xF;
2394                 if ( nibble < 10 ) {
2395                         new->bv_val[(i<<1)+d] = nibble + '0';
2396                 } else {
2397                         new->bv_val[(i<<1)+d] = nibble - 10 + 'a';
2398                 }
2399
2400                 nibble = (normalized->bv_val[i]) & 0xF;
2401                 if ( nibble < 10 ) {
2402                         new->bv_val[(i<<1)+d+1] = nibble + '0';
2403                 } else {
2404                         new->bv_val[(i<<1)+d+1] = nibble - 10 + 'a';
2405                 }
2406         }
2407
2408         new->bv_val[new->bv_len] = '\0';
2409         return new;
2410 }
2411
2412 static int
2413 syncuuid_cmp( const void* v_uuid1, const void* v_uuid2 )
2414 {
2415         const struct berval *uuid1 = v_uuid1;
2416         const struct berval *uuid2 = v_uuid2;
2417         int rc = uuid1->bv_len - uuid2->bv_len;
2418         if ( rc ) return rc;
2419         return ( memcmp( uuid1->bv_val, uuid2->bv_val, uuid1->bv_len ) );
2420 }
2421
2422 static void
2423 avl_ber_bvfree( void *v_bv )
2424 {
2425         struct berval   *bv = (struct berval *)v_bv;
2426         
2427         if( v_bv == NULL ) return;
2428         if ( !BER_BVISNULL( bv ) ) {
2429                 ch_free( bv->bv_val );
2430         }
2431         ch_free( (char *) bv );
2432 }
2433
2434 void
2435 syncinfo_free( syncinfo_t *sie )
2436 {
2437         ldap_pvt_thread_mutex_destroy( &sie->si_mutex );
2438         if ( !BER_BVISNULL( &sie->si_provideruri ) ) {
2439                 ch_free( sie->si_provideruri.bv_val );
2440         }
2441
2442         bindconf_free( &sie->si_bindconf );
2443
2444         if ( sie->si_filterstr.bv_val ) {
2445                 ch_free( sie->si_filterstr.bv_val );
2446         }
2447         if ( sie->si_base.bv_val ) {
2448                 ch_free( sie->si_base.bv_val );
2449         }
2450         if ( sie->si_attrs ) {
2451                 int i = 0;
2452                 while ( sie->si_attrs[i] != NULL ) {
2453                         ch_free( sie->si_attrs[i] );
2454                         i++;
2455                 }
2456                 ch_free( sie->si_attrs );
2457         }
2458         if ( sie->si_exattrs ) {
2459                 int i = 0;
2460                 while ( sie->si_exattrs[i] != NULL ) {
2461                         ch_free( sie->si_exattrs[i] );
2462                         i++;
2463                 }
2464                 ch_free( sie->si_exattrs );
2465         }
2466         if ( sie->si_anlist ) {
2467                 int i = 0;
2468                 while ( sie->si_anlist[i].an_name.bv_val != NULL ) {
2469                         ch_free( sie->si_anlist[i].an_name.bv_val );
2470                         i++;
2471                 }
2472                 ch_free( sie->si_anlist );
2473         }
2474         if ( sie->si_exanlist ) {
2475                 int i = 0;
2476                 while ( sie->si_exanlist[i].an_name.bv_val != NULL ) {
2477                         ch_free( sie->si_exanlist[i].an_name.bv_val );
2478                         i++;
2479                 }
2480                 ch_free( sie->si_exanlist );
2481         }
2482         if ( sie->si_retryinterval ) {
2483                 ch_free( sie->si_retryinterval );
2484         }
2485         if ( sie->si_retrynum ) {
2486                 ch_free( sie->si_retrynum );
2487         }
2488         if ( sie->si_retrynum_init ) {
2489                 ch_free( sie->si_retrynum_init );
2490         }
2491         slap_sync_cookie_free( &sie->si_syncCookie, 0 );
2492         if ( sie->si_presentlist ) {
2493             avl_free( sie->si_presentlist, avl_ber_bvfree );
2494         }
2495         if ( sie->si_ld ) {
2496                 ldap_unbind_ext( sie->si_ld, NULL, NULL );
2497         }
2498         while ( !LDAP_LIST_EMPTY( &sie->si_nonpresentlist )) {
2499                 struct nonpresent_entry* npe;
2500                 npe = LDAP_LIST_FIRST( &sie->si_nonpresentlist );
2501                 LDAP_LIST_REMOVE( npe, npe_link );
2502                 if ( npe->npe_name ) {
2503                         if ( npe->npe_name->bv_val ) {
2504                                 ch_free( npe->npe_name->bv_val );
2505                         }
2506                         ch_free( npe->npe_name );
2507                 }
2508                 if ( npe->npe_nname ) {
2509                         if ( npe->npe_nname->bv_val ) {
2510                                 ch_free( npe->npe_nname->bv_val );
2511                         }
2512                         ch_free( npe->npe_nname );
2513                 }
2514                 ch_free( npe );
2515         }
2516         ch_free( sie );
2517 }
2518
2519
2520
2521 /* NOTE: used & documented in slapd.conf(5) */
2522 #define IDSTR                   "rid"
2523 #define PROVIDERSTR             "provider"
2524 #define SCHEMASTR               "schemachecking"
2525 #define FILTERSTR               "filter"
2526 #define SEARCHBASESTR           "searchbase"
2527 #define SCOPESTR                "scope"
2528 #define ATTRSONLYSTR            "attrsonly"
2529 #define ATTRSSTR                "attrs"
2530 #define TYPESTR                 "type"
2531 #define INTERVALSTR             "interval"
2532 #define RETRYSTR                "retry"
2533 #define SLIMITSTR               "sizelimit"
2534 #define TLIMITSTR               "timelimit"
2535 #define SYNCDATASTR             "syncdata"
2536
2537 /* FIXME: undocumented */
2538 #define OLDAUTHCSTR             "bindprincipal"
2539 #define EXATTRSSTR              "exattrs"
2540 #define MANAGEDSAITSTR          "manageDSAit"
2541
2542 /* FIXME: unused */
2543 #define LASTMODSTR              "lastmod"
2544 #define LMGENSTR                "gen"
2545 #define LMNOSTR                 "no"
2546 #define LMREQSTR                "req"
2547 #define SRVTABSTR               "srvtab"
2548 #define SUFFIXSTR               "suffix"
2549
2550 /* mandatory */
2551 #define GOT_ID                  0x0001
2552 #define GOT_PROVIDER            0x0002
2553
2554 /* check */
2555 #define GOT_ALL                 (GOT_ID|GOT_PROVIDER)
2556
2557 static struct {
2558         struct berval key;
2559         int val;
2560 } scopes[] = {
2561         { BER_BVC("base"), LDAP_SCOPE_BASE },
2562         { BER_BVC("one"), LDAP_SCOPE_ONELEVEL },
2563         { BER_BVC("onelevel"), LDAP_SCOPE_ONELEVEL },   /* OpenLDAP extension */
2564 #ifdef LDAP_SCOPE_SUBORDINATE
2565         { BER_BVC("children"), LDAP_SCOPE_SUBORDINATE },
2566         { BER_BVC("subordinate"), LDAP_SCOPE_SUBORDINATE },
2567 #endif
2568         { BER_BVC("sub"), LDAP_SCOPE_SUBTREE },
2569         { BER_BVC("subtree"), LDAP_SCOPE_SUBTREE },     /* OpenLDAP extension */
2570         { BER_BVNULL, 0 }
2571 };
2572
2573 static slap_verbmasks datamodes[] = {
2574         { BER_BVC("default"), SYNCDATA_DEFAULT },
2575         { BER_BVC("accesslog"), SYNCDATA_ACCESSLOG },
2576         { BER_BVC("changelog"), SYNCDATA_CHANGELOG },
2577         { BER_BVNULL, 0 }
2578 };
2579
2580 static int
2581 parse_syncrepl_line(
2582         char            **cargv,
2583         int             cargc,
2584         syncinfo_t      *si
2585 )
2586 {
2587         int     gots = 0;
2588         int     i;
2589         char    *val;
2590
2591         for ( i = 1; i < cargc; i++ ) {
2592                 if ( !strncasecmp( cargv[ i ], IDSTR "=",
2593                                         STRLENOF( IDSTR "=" ) ) )
2594                 {
2595                         int tmp;
2596                         /* '\0' string terminator accounts for '=' */
2597                         val = cargv[ i ] + STRLENOF( IDSTR "=" );
2598                         tmp= atoi( val );
2599                         if ( tmp >= 1000 || tmp < 0 ) {
2600                                 fprintf( stderr, "Error: parse_syncrepl_line: "
2601                                          "syncrepl id %d is out of range [0..999]\n", tmp );
2602                                 return -1;
2603                         }
2604                         si->si_rid = tmp;
2605                         gots |= GOT_ID;
2606                 } else if ( !strncasecmp( cargv[ i ], PROVIDERSTR "=",
2607                                         STRLENOF( PROVIDERSTR "=" ) ) )
2608                 {
2609                         val = cargv[ i ] + STRLENOF( PROVIDERSTR "=" );
2610                         ber_str2bv( val, 0, 1, &si->si_provideruri );
2611                         gots |= GOT_PROVIDER;
2612                 } else if ( !strncasecmp( cargv[ i ], SCHEMASTR "=",
2613                                         STRLENOF( SCHEMASTR "=" ) ) )
2614                 {
2615                         val = cargv[ i ] + STRLENOF( SCHEMASTR "=" );
2616                         if ( !strncasecmp( val, "on", STRLENOF( "on" ) )) {
2617                                 si->si_schemachecking = 1;
2618                         } else if ( !strncasecmp( val, "off", STRLENOF( "off" ) ) ) {
2619                                 si->si_schemachecking = 0;
2620                         } else {
2621                                 si->si_schemachecking = 1;
2622                         }
2623                 } else if ( !strncasecmp( cargv[ i ], FILTERSTR "=",
2624                                         STRLENOF( FILTERSTR "=" ) ) )
2625                 {
2626                         val = cargv[ i ] + STRLENOF( FILTERSTR "=" );
2627                         if ( si->si_filterstr.bv_val )
2628                                 ch_free( si->si_filterstr.bv_val );
2629                         ber_str2bv( val, 0, 1, &si->si_filterstr );
2630                 } else if ( !strncasecmp( cargv[ i ], SEARCHBASESTR "=",
2631                                         STRLENOF( SEARCHBASESTR "=" ) ) )
2632                 {
2633                         struct berval   bv;
2634                         int             rc;
2635
2636                         val = cargv[ i ] + STRLENOF( SEARCHBASESTR "=" );
2637                         if ( si->si_base.bv_val ) {
2638                                 ch_free( si->si_base.bv_val );
2639                         }
2640                         ber_str2bv( val, 0, 0, &bv );
2641                         rc = dnNormalize( 0, NULL, NULL, &bv, &si->si_base, NULL );
2642                         if ( rc != LDAP_SUCCESS ) {
2643                                 fprintf( stderr, "Invalid base DN \"%s\": %d (%s)\n",
2644                                         val, rc, ldap_err2string( rc ) );
2645                                 return -1;
2646                         }
2647                 } else if ( !strncasecmp( cargv[ i ], SCOPESTR "=",
2648                                         STRLENOF( SCOPESTR "=" ) ) )
2649                 {
2650                         int j;
2651                         val = cargv[ i ] + STRLENOF( SCOPESTR "=" );
2652                         for ( j=0; !BER_BVISNULL(&scopes[j].key); j++ ) {
2653                                 if (!strcasecmp( val, scopes[j].key.bv_val )) {
2654                                         si->si_scope = scopes[j].val;
2655                                         break;
2656                                 }
2657                         }
2658                         if ( BER_BVISNULL(&scopes[j].key) ) {
2659                                 fprintf( stderr, "Error: parse_syncrepl_line: "
2660                                         "unknown scope \"%s\"\n", val);
2661                                 return -1;
2662                         }
2663                 } else if ( !strncasecmp( cargv[ i ], ATTRSONLYSTR "=",
2664                                         STRLENOF( ATTRSONLYSTR "=" ) ) )
2665                 {
2666                         si->si_attrsonly = 1;
2667                 } else if ( !strncasecmp( cargv[ i ], ATTRSSTR "=",
2668                                         STRLENOF( ATTRSSTR "=" ) ) )
2669                 {
2670                         val = cargv[ i ] + STRLENOF( ATTRSSTR "=" );
2671                         if ( !strncasecmp( val, ":include:", STRLENOF(":include:") ) ) {
2672                                 char *attr_fname;
2673                                 attr_fname = ch_strdup( val + STRLENOF(":include:") );
2674                                 si->si_anlist = file2anlist( si->si_anlist, attr_fname, " ,\t" );
2675                                 if ( si->si_anlist == NULL ) {
2676                                         ch_free( attr_fname );
2677                                         return -1;
2678                                 }
2679                                 si->si_anfile = attr_fname;
2680                         } else {
2681                                 char *str, *s, *next;
2682                                 char delimstr[] = " ,\t";
2683                                 str = ch_strdup( val );
2684                                 for ( s = ldap_pvt_strtok( str, delimstr, &next );
2685                                                 s != NULL;
2686                                                 s = ldap_pvt_strtok( NULL, delimstr, &next ) )
2687                                 {
2688                                         if ( strlen(s) == 1 && *s == '*' ) {
2689                                                 si->si_allattrs = 1;
2690                                                 *(val + ( s - str )) = delimstr[0];
2691                                         }
2692                                         if ( strlen(s) == 1 && *s == '+' ) {
2693                                                 si->si_allopattrs = 1;
2694                                                 *(val + ( s - str )) = delimstr[0];
2695                                         }
2696                                 }
2697                                 ch_free( str );
2698                                 si->si_anlist = str2anlist( si->si_anlist, val, " ,\t" );
2699                                 if ( si->si_anlist == NULL ) {
2700                                         return -1;
2701                                 }
2702                         }
2703                 } else if ( !strncasecmp( cargv[ i ], EXATTRSSTR "=",
2704                                         STRLENOF( EXATTRSSTR "=" ) ) )
2705                 {
2706                         val = cargv[ i ] + STRLENOF( EXATTRSSTR "=" );
2707                         if ( !strncasecmp( val, ":include:", STRLENOF(":include:") )) {
2708                                 char *attr_fname;
2709                                 attr_fname = ch_strdup( val + STRLENOF(":include:") );
2710                                 si->si_exanlist = file2anlist(
2711                                                                         si->si_exanlist, attr_fname, " ,\t" );
2712                                 if ( si->si_exanlist == NULL ) {
2713                                         ch_free( attr_fname );
2714                                         return -1;
2715                                 }
2716                                 ch_free( attr_fname );
2717                         } else {
2718                                 si->si_exanlist = str2anlist( si->si_exanlist, val, " ,\t" );
2719                                 if ( si->si_exanlist == NULL ) {
2720                                         return -1;
2721                                 }
2722                         }
2723                 } else if ( !strncasecmp( cargv[ i ], TYPESTR "=",
2724                                         STRLENOF( TYPESTR "=" ) ) )
2725                 {
2726                         val = cargv[ i ] + STRLENOF( TYPESTR "=" );
2727                         if ( !strncasecmp( val, "refreshOnly",
2728                                                 STRLENOF("refreshOnly") ))
2729                         {
2730                                 si->si_type = LDAP_SYNC_REFRESH_ONLY;
2731                         } else if ( !strncasecmp( val, "refreshAndPersist",
2732                                                 STRLENOF("refreshAndPersist") ))
2733                         {
2734                                 si->si_type = LDAP_SYNC_REFRESH_AND_PERSIST;
2735                                 si->si_interval = 60;
2736                         } else {
2737                                 fprintf( stderr, "Error: parse_syncrepl_line: "
2738                                         "unknown sync type \"%s\"\n", val);
2739                                 return -1;
2740                         }
2741                 } else if ( !strncasecmp( cargv[ i ], INTERVALSTR "=",
2742                                         STRLENOF( INTERVALSTR "=" ) ) )
2743                 {
2744                         val = cargv[ i ] + STRLENOF( INTERVALSTR "=" );
2745                         if ( si->si_type == LDAP_SYNC_REFRESH_AND_PERSIST ) {
2746                                 si->si_interval = 0;
2747                         } else {
2748                                 char *hstr;
2749                                 char *mstr;
2750                                 char *dstr;
2751                                 char *sstr;
2752                                 int dd, hh, mm, ss;
2753                                 dstr = val;
2754                                 hstr = strchr( dstr, ':' );
2755                                 if ( hstr == NULL ) {
2756                                         fprintf( stderr, "Error: parse_syncrepl_line: "
2757                                                 "invalid interval \"%s\"\n", val );
2758                                         return -1;
2759                                 }
2760                                 *hstr++ = '\0';
2761                                 mstr = strchr( hstr, ':' );
2762                                 if ( mstr == NULL ) {
2763                                         fprintf( stderr, "Error: parse_syncrepl_line: "
2764                                                 "invalid interval \"%s\"\n", val );
2765                                         return -1;
2766                                 }
2767                                 *mstr++ = '\0';
2768                                 sstr = strchr( mstr, ':' );
2769                                 if ( sstr == NULL ) {
2770                                         fprintf( stderr, "Error: parse_syncrepl_line: "
2771                                                 "invalid interval \"%s\"\n", val );
2772                                         return -1;
2773                                 }
2774                                 *sstr++ = '\0';
2775
2776                                 dd = atoi( dstr );
2777                                 hh = atoi( hstr );
2778                                 mm = atoi( mstr );
2779                                 ss = atoi( sstr );
2780                                 if (( hh > 24 ) || ( hh < 0 ) ||
2781                                         ( mm > 60 ) || ( mm < 0 ) ||
2782                                         ( ss > 60 ) || ( ss < 0 ) || ( dd < 0 )) {
2783                                         fprintf( stderr, "Error: parse_syncrepl_line: "
2784                                                 "invalid interval \"%s\"\n", val );
2785                                         return -1;
2786                                 }
2787                                 si->si_interval = (( dd * 24 + hh ) * 60 + mm ) * 60 + ss;
2788                         }
2789                         if ( si->si_interval < 0 ) {
2790                                 fprintf( stderr, "Error: parse_syncrepl_line: "
2791                                         "invalid interval \"%ld\"\n",
2792                                         (long) si->si_interval);
2793                                 return -1;
2794                         }
2795                 } else if ( !strncasecmp( cargv[ i ], RETRYSTR "=",
2796                                         STRLENOF( RETRYSTR "=" ) ) )
2797                 {
2798                         char **retry_list;
2799                         int j, k, n;
2800
2801                         val = cargv[ i ] + STRLENOF( RETRYSTR "=" );
2802                         retry_list = (char **) ch_calloc( 1, sizeof( char * ));
2803                         retry_list[0] = NULL;
2804
2805                         slap_str2clist( &retry_list, val, " ,\t" );
2806
2807                         for ( k = 0; retry_list && retry_list[k]; k++ ) ;
2808                         n = k / 2;
2809                         if ( k % 2 ) {
2810                                 fprintf( stderr,
2811                                                 "Error: incomplete syncrepl retry list\n" );
2812                                 for ( k = 0; retry_list && retry_list[k]; k++ ) {
2813                                         ch_free( retry_list[k] );
2814                                 }
2815                                 ch_free( retry_list );
2816                                 exit( EXIT_FAILURE );
2817                         }
2818                         si->si_retryinterval = (time_t *) ch_calloc( n + 1, sizeof( time_t ));
2819                         si->si_retrynum = (int *) ch_calloc( n + 1, sizeof( int ));
2820                         si->si_retrynum_init = (int *) ch_calloc( n + 1, sizeof( int ));
2821                         for ( j = 0; j < n; j++ ) {
2822                                 si->si_retryinterval[j] = atoi( retry_list[j*2] );
2823                                 if ( *retry_list[j*2+1] == '+' ) {
2824                                         si->si_retrynum_init[j] = -1;
2825                                         si->si_retrynum[j] = -1;
2826                                         j++;
2827                                         break;
2828                                 } else {
2829                                         si->si_retrynum_init[j] = atoi( retry_list[j*2+1] );
2830                                         si->si_retrynum[j] = atoi( retry_list[j*2+1] );
2831                                 }
2832                         }
2833                         si->si_retrynum_init[j] = -2;
2834                         si->si_retrynum[j] = -2;
2835                         si->si_retryinterval[j] = 0;
2836                         
2837                         for ( k = 0; retry_list && retry_list[k]; k++ ) {
2838                                 ch_free( retry_list[k] );
2839                         }
2840                         ch_free( retry_list );
2841                 } else if ( !strncasecmp( cargv[ i ], MANAGEDSAITSTR "=",
2842                                         STRLENOF( MANAGEDSAITSTR "=" ) ) )
2843                 {
2844                         val = cargv[ i ] + STRLENOF( MANAGEDSAITSTR "=" );
2845                         si->si_manageDSAit = atoi( val );
2846                 } else if ( !strncasecmp( cargv[ i ], SLIMITSTR "=",
2847                                         STRLENOF( SLIMITSTR "=") ) )
2848                 {
2849                         val = cargv[ i ] + STRLENOF( SLIMITSTR "=" );
2850                         si->si_slimit = atoi( val );
2851                 } else if ( !strncasecmp( cargv[ i ], TLIMITSTR "=",
2852                                         STRLENOF( TLIMITSTR "=" ) ) )
2853                 {
2854                         val = cargv[ i ] + STRLENOF( TLIMITSTR "=" );
2855                         si->si_tlimit = atoi( val );
2856                 } else if ( !strncasecmp( cargv[ i ], SYNCDATASTR "=",
2857                                         STRLENOF( SYNCDATASTR "=" ) ) )
2858                 {
2859                         val = cargv[ i ] + STRLENOF( SYNCDATASTR "=" );
2860                         si->si_syncdata = verb_to_mask( val, datamodes );
2861                 } else if ( bindconf_parse( cargv[i], &si->si_bindconf )) {
2862                         fprintf( stderr, "Error: parse_syncrepl_line: "
2863                                 "unknown keyword \"%s\"\n", cargv[ i ] );
2864                         return -1;
2865                 }
2866         }
2867
2868         if ( gots != GOT_ALL ) {
2869                 fprintf( stderr,
2870                         "Error: Malformed \"syncrepl\" line in slapd config file" );
2871                 return -1;
2872         }
2873
2874         return 0;
2875 }
2876
2877 static int
2878 add_syncrepl(
2879         Backend *be,
2880         char    **cargv,
2881         int     cargc
2882 )
2883 {
2884         syncinfo_t *si;
2885         int     rc = 0;
2886
2887         if ( !( be->be_search && be->be_add && be->be_modify && be->be_delete )) {
2888                 Debug( LDAP_DEBUG_ANY, "database %s does not support operations "
2889                         "required for syncrepl\n", be->be_type, 0, 0 );
2890                 return 1;
2891         }
2892         si = (syncinfo_t *) ch_calloc( 1, sizeof( syncinfo_t ) );
2893
2894         if ( si == NULL ) {
2895                 Debug( LDAP_DEBUG_ANY, "out of memory in add_syncrepl\n", 0, 0, 0 );
2896                 return 1;
2897         }
2898
2899         si->si_bindconf.sb_tls = SB_TLS_OFF;
2900         si->si_bindconf.sb_method = LDAP_AUTH_SIMPLE;
2901         si->si_schemachecking = 0;
2902         ber_str2bv( "(objectclass=*)", STRLENOF("(objectclass=*)"), 1,
2903                 &si->si_filterstr );
2904         si->si_base.bv_val = NULL;
2905         si->si_scope = LDAP_SCOPE_SUBTREE;
2906         si->si_attrsonly = 0;
2907         si->si_anlist = (AttributeName *) ch_calloc( 1, sizeof( AttributeName ));
2908         si->si_exanlist = (AttributeName *) ch_calloc( 1, sizeof( AttributeName ));
2909         si->si_attrs = NULL;
2910         si->si_allattrs = 0;
2911         si->si_allopattrs = 0;
2912         si->si_exattrs = NULL;
2913         si->si_type = LDAP_SYNC_REFRESH_ONLY;
2914         si->si_interval = 86400;
2915         si->si_retryinterval = NULL;
2916         si->si_retrynum_init = NULL;
2917         si->si_retrynum = NULL;
2918         si->si_manageDSAit = 0;
2919         si->si_tlimit = 0;
2920         si->si_slimit = 0;
2921
2922         si->si_presentlist = NULL;
2923         LDAP_LIST_INIT( &si->si_nonpresentlist );
2924         ldap_pvt_thread_mutex_init( &si->si_mutex );
2925
2926         rc = parse_syncrepl_line( cargv, cargc, si );
2927
2928         if ( rc == 0 ) {
2929                 si->si_be = be;
2930                 init_syncrepl( si );
2931                 si->si_re = ldap_pvt_runqueue_insert( &slapd_rq, si->si_interval,
2932                         do_syncrepl, si, "do_syncrepl", be->be_suffix[0].bv_val );
2933                 if ( !si->si_re )
2934                         rc = -1;
2935         }
2936         if ( rc < 0 ) {
2937                 Debug( LDAP_DEBUG_ANY, "failed to add syncinfo\n", 0, 0, 0 );
2938                 syncinfo_free( si );    
2939                 return 1;
2940         } else {
2941                 Debug( LDAP_DEBUG_CONFIG,
2942                         "Config: ** successfully added syncrepl \"%s\"\n",
2943                         BER_BVISNULL( &si->si_provideruri ) ?
2944                         "(null)" : si->si_provideruri.bv_val, 0, 0 );
2945                 if ( !si->si_schemachecking ) {
2946                         SLAP_DBFLAGS(be) |= SLAP_DBFLAG_NO_SCHEMA_CHECK;
2947                 }
2948                 be->be_syncinfo = si;
2949                 return 0;
2950         }
2951 }
2952
2953 static void
2954 syncrepl_unparse( syncinfo_t *si, struct berval *bv )
2955 {
2956         struct berval bc;
2957         char buf[BUFSIZ*2], *ptr;
2958         int i;
2959
2960         bindconf_unparse( &si->si_bindconf, &bc );
2961         ptr = buf;
2962         ptr += sprintf( ptr, IDSTR "=%03ld " PROVIDERSTR "=%s",
2963                 si->si_rid, si->si_provideruri.bv_val );
2964         if ( !BER_BVISNULL( &bc )) {
2965                 ptr = lutil_strcopy( ptr, bc.bv_val );
2966                 free( bc.bv_val );
2967         }
2968         if ( !BER_BVISEMPTY( &si->si_filterstr )) {
2969                 ptr = lutil_strcopy( ptr, " " FILTERSTR "=\"" );
2970                 ptr = lutil_strcopy( ptr, si->si_filterstr.bv_val );
2971                 *ptr++ = '"';
2972         }
2973         if ( !BER_BVISNULL( &si->si_base )) {
2974                 ptr = lutil_strcopy( ptr, " " SEARCHBASESTR "=\"" );
2975                 ptr = lutil_strcopy( ptr, si->si_base.bv_val );
2976                 *ptr++ = '"';
2977         }
2978         for (i=0; !BER_BVISNULL(&scopes[i].key);i++) {
2979                 if ( si->si_scope == scopes[i].val ) {
2980                         ptr = lutil_strcopy( ptr, " " SCOPESTR "=" );
2981                         ptr = lutil_strcopy( ptr, scopes[i].key.bv_val );
2982                         break;
2983                 }
2984         }
2985         if ( si->si_attrsonly ) {
2986                 ptr = lutil_strcopy( ptr, " " ATTRSONLYSTR "=yes" );
2987         }
2988         if ( si->si_anfile ) {
2989                 ptr = lutil_strcopy( ptr, " " ATTRSSTR "=:include:" );
2990                 ptr = lutil_strcopy( ptr, si->si_anfile );
2991         } else if ( si->si_allattrs || si->si_allopattrs ||
2992                 ( si->si_anlist && !BER_BVISNULL(&si->si_anlist[0].an_name) )) {
2993                 char *old;
2994                 ptr = lutil_strcopy( ptr, " " ATTRSSTR "=\"" );
2995                 old = ptr;
2996                 ptr = anlist_unparse( si->si_anlist, ptr );
2997                 if ( si->si_allattrs ) {
2998                         if ( old != ptr ) *ptr++ = ',';
2999                         *ptr++ = '*';
3000                 }
3001                 if ( si->si_allopattrs ) {
3002                         if ( old != ptr ) *ptr++ = ',';
3003                         *ptr++ = '+';
3004                 }
3005                 *ptr++ = '"';
3006         }
3007         if ( si->si_exanlist && !BER_BVISNULL(&si->si_exanlist[0].an_name) ) {
3008                 ptr = lutil_strcopy( ptr, " " EXATTRSSTR "=" );
3009                 ptr = anlist_unparse( si->si_exanlist, ptr );
3010         }
3011         ptr = lutil_strcopy( ptr, " " SCHEMASTR "=" );
3012         ptr = lutil_strcopy( ptr, si->si_schemachecking ? "on" : "off" );
3013         
3014         ptr = lutil_strcopy( ptr, " " TYPESTR "=" );
3015         ptr = lutil_strcopy( ptr, si->si_type == LDAP_SYNC_REFRESH_AND_PERSIST ?
3016                 "refreshAndPersist" : "refreshOnly" );
3017
3018         if ( si->si_type == LDAP_SYNC_REFRESH_ONLY ) {
3019                 int dd, hh, mm, ss;
3020
3021                 dd = si->si_interval;
3022                 ss = dd % 60;
3023                 dd /= 60;
3024                 mm = dd % 60;
3025                 dd /= 60;
3026                 hh = dd % 24;
3027                 dd /= 24;
3028                 ptr = lutil_strcopy( ptr, " " INTERVALSTR "=" );
3029                 ptr += sprintf( ptr, "%02d:%02d:%02d:%02d", dd, hh, mm, ss );
3030         } else if ( si->si_retryinterval ) {
3031                 int space=0;
3032                 ptr = lutil_strcopy( ptr, " " RETRYSTR "=\"" );
3033                 for (i=0; si->si_retryinterval[i]; i++) {
3034                         if ( space ) *ptr++ = ' ';
3035                         space = 1;
3036                         ptr += sprintf( ptr, "%ld ", (long) si->si_retryinterval[i] );
3037                         if ( si->si_retrynum_init[i] == -1 )
3038                                 *ptr++ = '+';
3039                         else
3040                                 ptr += sprintf( ptr, "%d", si->si_retrynum_init[i] );
3041                 }
3042                 *ptr++ = '"';
3043         }
3044
3045         if ( si->si_slimit ) {
3046                 ptr = lutil_strcopy( ptr, " " SLIMITSTR "=" );
3047                 ptr += sprintf( ptr, "%d", si->si_slimit );
3048         }
3049
3050         if ( si->si_tlimit ) {
3051                 ptr = lutil_strcopy( ptr, " " TLIMITSTR "=" );
3052                 ptr += sprintf( ptr, "%d", si->si_tlimit );
3053         }
3054
3055         if ( si->si_syncdata ) {
3056                 if ( enum_to_verb( datamodes, si->si_syncdata, &bc ) >= 0 ) {
3057                         ptr = lutil_strcopy( ptr, " " SYNCDATASTR "=" );
3058                         ptr = lutil_strcopy( ptr, bc.bv_val );
3059                 }
3060         }
3061         bc.bv_len = ptr - buf;
3062         bc.bv_val = buf;
3063         ber_dupbv( bv, &bc );
3064 }
3065
3066 int
3067 syncrepl_config(ConfigArgs *c) {
3068         if (c->op == SLAP_CONFIG_EMIT) {
3069                 if ( c->be->be_syncinfo ) {
3070                         struct berval bv;
3071                         syncrepl_unparse( c->be->be_syncinfo, &bv ); 
3072                         ber_bvarray_add( &c->rvalue_vals, &bv );
3073                         return 0;
3074                 }
3075                 return 1;
3076         } else if ( c->op == LDAP_MOD_DELETE ) {
3077                 struct re_s *re;
3078
3079                 if ( c->be->be_syncinfo ) {
3080                         re = c->be->be_syncinfo->si_re;
3081                         if ( re ) {
3082                                 if ( ldap_pvt_runqueue_isrunning( &slapd_rq, re ))
3083                                         ldap_pvt_runqueue_stoptask( &slapd_rq, re );
3084                                 ldap_pvt_runqueue_remove( &slapd_rq, re );
3085                         }
3086                         syncinfo_free( c->be->be_syncinfo );
3087                         c->be->be_syncinfo = NULL;
3088                 }
3089                 SLAP_DBFLAGS(c->be) &= ~(SLAP_DBFLAG_SHADOW|SLAP_DBFLAG_SYNC_SHADOW);
3090                 return 0;
3091         }
3092         if(SLAP_SHADOW(c->be)) {
3093                 Debug(LDAP_DEBUG_ANY, "%s: "
3094                         "syncrepl: database already shadowed.\n",
3095                         c->log, 0, 0);
3096                 return(1);
3097         } else if(add_syncrepl(c->be, c->argv, c->argc)) {
3098                 return(1);
3099         }
3100         SLAP_DBFLAGS(c->be) |= (SLAP_DBFLAG_SHADOW | SLAP_DBFLAG_SYNC_SHADOW);
3101         return(0);
3102 }